Search This Blog

Friday 27 September 2013

Object Disposal best practice

If we are not performing any operations on the SPSite object, we can write as in the following code example.

void CombiningCallsBestPractice()
{
    using (SPSite siteCollection = new SPSite(SPContext.Current.Web.Url))
    using (SPWeb web = siteCollection.OpenWeb())
        {
        //Perform operations on site.
        } // SPWeb object web.Dispose() automatically called; SPSite object
          // siteCollection.Dispose() automatically called.
}

Thursday 26 September 2013

radio button validation using jquery in sharepoint Designer form

<script  type="text/javascript">
   $(function() {
    var str = $('input[name*=ff200]').get(1).id;
    document.getElementById(str).setAttribute('checked','checked');
  })
</script>
Here we have a Radio button with Yes and No Options.

The XSLT of Radio button in SharePoint is

<SharePoint:FormField runat="server" id="ff200{$Pos}" ControlMode="Edit" FieldName="FeedbackCompleted" __designer:bind="{ddwrt:DataBind('u',concat('ff200',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@FeedbackCompleted')}"/>



$('input[name*=ff200]') - It searches the input element whose name contains ff200 which is the in ID of the SharePoint FormField.

var str = $('input[name*=ff200]').get(1).id; line finds the ID of the Element, As radio button has two or more options but in SharePoint it is FormField. So you want to find id of First Radio Button use get(0), Second Radio button use get(1) etc. 

Tuesday 24 September 2013

How to display text box value of custom form in Indian rupees format


Use the following code to get the text value to be assigned to the text box/label of the currency field in VS form. 

double aNumber = 2073635.00; 
System.Globalization.CultureInfo info = System.Globalization.CultureInfo.GetCultureInfo("hi-IN"); 
string str = aNumber.ToString("C2",info); 

And now str is: "(Rupee sign) 20,73,635.00" 

Wednesday 18 September 2013

Sharepoint Designer Forms-Conditional Display of fields


<xsl:choose>
    <xsl:when test="@Status != 'Closed'">
     <SharePoint:FormField runat="server" id="ff1{$Pos}" ControlMode="Edit" FieldName="Title" __designer:bind="{ddwrt:DataBind('u',concat('ff1',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Title')}"/>
     <SharePoint:FieldDescription runat="server" id="ff1description{$Pos}" FieldName="Title" ControlMode="Edit"/>
    </xsl:when>
    <xsl:otherwise>
     <xsl:value-of select="@Title"></xsl:value-of>
    </xsl:otherwise>
</xsl:choose>

Monday 9 September 2013

Sharepoint ClientPeoplePicker Validation

In user control page
<SharePoint:ClientPeoplePicker
            id="ppApprover"
            runat="server" Rows="1" AllowMultipleEntities="false" CssClass="ms-long"/>
                 <asp:CustomValidator ID="cstmVald2" runat="server" ControlToValidate="ppApprover" Display="Dynamic" ValidationGroup="vgCreateSE"
              ValidateEmptyText="true" SetFocusOnError="true" ErrorMessage="Please enter SDU Head(GM & above)" CssClass="ms-error" ClientValidationFunction="peoplvalidator"></asp:CustomValidator>


function peoplvalidator(sender, args) {
          args.IsValid = false;
          var user = $("span.ms-entity-resolved").attr("title");//Returns the Login Name
        
          if (user != undefined) {
              args.IsValid = true;
          }
       
      }

Ajax calls to services not working (Cache Problem)


var thiSite = _spPageContextInfo.webAbsoluteUrl;
var servicePath= "/_vti_bin/WCF/LeaveService.svc/Data";
            var MyUrl = thiSite + servicePath; 
$.ajax({
                type: "GET",
                url: MyUrl,
                cache:false,//Ensure that calls are not depend on cache
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                processdata: true,
                success: function (msg) {
                    alert("Sucess");
                    var Array = new Array();
                    //Gets the Data                    $.each(msg, function (i, item) {
                        Array[i] = item;
                    });                                                      },
                error: function (msg) { alert("Eror"); }
            });

Get Current site name from javascript


var site=_spPageContextInfo.webAbsoluteUrl;

Radio button validation not working using javascript


var radioButtonlist = document.getElementById('<%=rbTransferType.ClientID%>');
 var opt = radioButtonlist.getElementsByTagName('input');
 for (var i = 0; i < opt.length; i++) {
                var rbref = opt[i];
                if (rbref.checked == true) {
                    if (rbref.value == "Third Party") {                      
                        break;
                    }
                    else if (rbref.value == "Inter IBS") {                       
                        break;
                    }
                }
      }

Client Picker Validation client side


Use the following function in onclient click .
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
function IsEmptyPeoplePicker(pickerClientId) {
            var r = false;
            try {
  var txt = pickerClientId.text(); //Enter Name or Email Address...Rajesh Sivaprasadx             
    //If their is a selection in picker, always last character is 'x'.
                    //If last index of 'x' and total lenth is same,means picker has a resolved entity.
                 if (txt.lastIndexOf("x") != (txt.length - 1)) { return r = true; } 
               } catch (e) {return r = true; }
            return r;
        }
''''''''''''''''''''''''''''''''''''''
It will return true if the picker empty.

Use a div with class me-error just below client picker in the same <td> to show validation message

eg: var isEmptyUserPicker = IsEmptyPeoplePicker($('#<%=userPicker.ClientID%>'));                
                    if (isEmptyUserPicker) {
                        $("#divUserPickerValidator").text("Please select Recommender");
                        $("#divUserPickerValidator").show();
                        $("#divUserPickerValidator").fadeOut(5000);
                        return r = false;
                    }

Not able to create Site Pages/ Site Pages option not available under Site Contents

Go to Site Settings -> Site Actions -> Manage Site Features on the publishing site and activate the 'Wiki Page Home Page' feature. Go back to the Site Contents, you will find a document library by name Site Pages that would have been created.

Hide Quick Launch bar


/* Hide quick launch bar */

#sideNavBox {

display: none;

}

/* Hide quick launch bar */

#contentBox {

margin-left:20px !important;

}

Error occurred in deployment step 'Add Solution': A feature with ID 15/bb6298f9-f2c1-4dba-b8fa-1ae0c752bcf2 has already been installed in this farm. Use the force attribute to explicitly re-install the feature


Sometimes when we try deploy the visaul web parts solution to share point site, we might get an error like

"Error occurred in deployment step 'Add Solution': A feature with ID 15/bb6298f9-f2c1-4dba-b8fa-1ae0c752bcf2 has already been installed in this farm.  Use the force attribute to explicitly re-install the feature"

In order to resolve this issue, set AlwaysForceInstall atttribute to True in featurename.Template.xml file.

<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" AlwaysForceInstall="TRUE">
</Feature>

Alternatively, we can use power shell command also.
Install-SPSolution <solutionname>.wsp -GACDeployment -Force  

How to control the Redirect URL after saving content in a Data Form View Control

To avoid closing of sharepoint designer edit form after saving/or to redirect to another url after saving of Sharepoint designer form.

Source Reference :- http://social.msdn.microsoft.com/Forums/sharepoint/en-US/7aff3de2-4250-47ac-9175-2fdc0a685005/how-to-control-the-redirect-url-after-saving-content-in-a-data-form-view-control

Details:
  I have customized a Page Layout to include a custom Data Form View Web Part that will allow users to enter comments on a news story page in a publishing site.

I was having a difficult time because when I clicked the button to save the data to the list, everything saved correctly, but the control was redirecting me to the AllItems.aspx page of the list.  This wasn't the desired behavior since the end user would prefer to see that their comment was posted on the news story page and wouldn't know what the AllItems.aspx page was for.

The save button that was created in the XSL seciton of the web part was:

<SharePoint: SaveButton runat="server" ControlMode="New" id="savebutton1" />

Microsoft has documented a RedirectUrl property on this button that I figured could change what page was loaded after the user saved the form data.  However, try as I might I could not get it to work.Some more searching lead me to this article:

http://office.microsoft.com/en-us/sharepointdesigner/HA101191121033.aspx

Which details how to create a "Form Action" for a save button rendered in the XSL of a DataFormWebPart.  This was a great article, but it doesn't detail the code that Sharepoint Designer outputs for this action.  After following the instructions, I discovered this code for a button:

<input type="button" value="Save" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={}')}" />

When used instead of my SharePoint: SaveButton above, the form saved it's data correctly, and the current page that the form was submitted from was reloaded for the user.

You could also put any URL in the __redirect={} that you want, for example __redirect={http://www.google.com} or __redirect={/news/PressReleases/}

Notice that there are no quotes around the URLs passed into the __redirect directive.

Set Content Approval status by code


SPModerationInformation ApprovalStatus = item.ModerationInformation;

ApprovalStatus.Status = SPModerationStatusType.Approved;

item.Update();

upgraded from a VS 2010 project to VS 2013


I was able to get my solution upgraded from a 2010 project to 2013 using the following. Note that this will update your solution to use the new 2013 API. It is possible to update just the project file but still run in 2010 mode.

First edit your .csproj file (for c#).

Modify the target framework to this: <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>

Add this a node for the office version, I put mine directly below the TargetFrameworkVersion tag <TargetOfficeVersion>15.0</TargetOfficeVersion>

Update references

Reload the project and update your referenced assemblies. If you haven't specified a specific version they should already be referencing the v15 (SharePoint 2013) assemblies.

Do a find replace for 14.0.0.0 to 15.0.0.0. This updates any references on your pages, layouts, and master pages to the v15 assemblies.

Change calls

Change any calls to SPUtility.GetGenericSetupPath() to SPUtility.GetVersionedGenericSetupPath()

Check each file to do a check for any hive references. You'll need to add a /15/ to these. EG: _layouts/ to _layouts/15/

Open the package "folder" in visual studio then update the properties for that package to use version 15.

Clean up

Finally do a compile clean up any missed items. Deploy your solution and make sure to test thoroughly.

Overcoming the Lack of a Design View in SharePoint Designer 2013

http://www.wonderlaura.com/Lists/Posts/Post.aspx?ID=187
http://www.synergyonline.com/Blog/Lists/Posts/Post.aspx?ID=259

If you noticed that the design view doesn’t exist anymore in SharePoint Designer 2013, here is a hack which lets you create data view web parts for your SharePoint 2013 site. 

Note that this is most likely NOT supported by Microsoft.  This is just one way that I figured out, so if you really need to create data view web parts, and you’re not a developer, you may want to try this as a very funky workaround.

1.Create an empty document library in your SharePoint 2013 site, which will be the temporary holding place for web part creation.  I just called mine “Web Part Pages”.

2.Open your SharePoint 2013 site in SharePoint Designer 2010.

3.Click the little pin icon next to All Files on the left.  That will put a tree view of the site on the left.

4.Right click on your new library, and choose New –> ASPX.


5.Give your file a name, like test.aspx. Double click the file to open it, and click Edit File.

6.Yes, open the page in advanced mode.


7.On the Insert tab, choose Web part zone.  Then, on the Insert tab, choose the Data View drop-down and choose Empty data view.

8.Click on Click here to select a data source (in the middle of the page), and choose your list, library or whatever.  I’ll choose Tasks.  Click OK.

9.On the right, in the data source details pane, select the fields you need, and click Insert Fields as, and choose Multiple Item View.


10.There, now you can do whatever you need to do with your data view web part, etc, and get it how you want it.  This is the page that you will go back to in order to make any needed changes.

11.On the Web Part tab in the ribbon, click To File.  Save this .webpart file to your computer, and just remember where.

12.Open your site in the browser, and go to the page on which you would like to place your web part.  With the page in edit mode, click the Page tab, and the Insert tab.  Click Web Part.

13.On the left side, under the web part categories, click the Browse… button under Upload a web part.  Browse to that .webpart file you saved at step 11.  Click Upload.

14.Now you’ll have to click to insert a web part again, and this time you’ll see it in the Imported Web Parts category.  Click Add to add the web part to your page.


Now that this is done, again, any changes you make will have to be in that temporary aspx page that you created.  IT’S ALL ABOUT THE MASTER PAGE.  The key is that I did not attach a master page to my blank aspx page.  I tried to find a way to edit existing views, by attaching the v4.master page and trying to make changes before re-attaching the v15.master.  That did not work out.  Anyway, let me know what you guys think.  I know it takes a few extra clicks, but at least DVWPs are doable.

couldnot find find feature dataconnectionlibrary - site import


You have to deactivate the DataConnectionLibrary feature on your site before exporting it. The DataConnectionLibrary feature is invisible so you can't do this through the UI, you'll have to do this via stsadm:


stsadm -o deactivatefeature -name DataConnectionLibrary -url [[YOUR-SPECIFIC-WEB-URL-HERE]] -force

http://social.technet.microsoft.com/forums/en-US/sharepointadmin/thread/057c53ef-3541-47ec-9152-7e6852fbd669?prof=required

To Sign in as different user in Sharepoint 2013


Use the following link
/_layouts/closeConnection.aspx?loginasanotheruser=true

How to attach CompareValidator to DateTime control

<sharePoint:DateTimeControl ID="dteDemo" runat="server" DateOnly="true" /> 
<asp:CompareValidator id="valDate" runat="server"
        ControlToValidate="dteDemo$dteDemoDate"
         Type="Date"
 Operator="DataTypeCheck"

 ErrorMessage="Please enter an valid date"> 

</asp:CompareValidator >

Username showing ibsplc.com than domain\id in user profiles OR Enable NETBIOSNAME


1. Create a new user profile service application and start user profile sync service by associating this service application.
2. Create an AD connection to IBSPLC.com and import users.
3. Make sure issue is reproduced in this new service application.
4. Follow http://technet.microsoft.com/en-us/library/ee721049.aspx#NetBIOSProc and make sure that on this new service application NetBIOSDomainNamesEnabled is set to 1. You can decide to change only this new user profile service application.
5. Disable My Site Cleanup job.
6. Restart user profile sync service.
7. Do a fully sync and observe behavior.
8. If the issue is not resolved then delete existing AD connection and create a new AD connection with same domain for new user profile service application we created for testing purpose.
9. Do two full syncs and observe the behavior.


$ServiceApps = Get-SPServiceApplication
$UserProfileServiceApp = ""
foreach ($sa in $ServiceApps)
  {if ($sa.DisplayName -eq "<UPSAName>")
    {$UserProfileServiceApp = $sa}
  }
$UserProfileServiceApp.NetBIOSDomainNamesEnabled = 1
$UserProfileServiceApp.Update()

Visual studio 2012 Sharepoint template


Date & Time column display strange value in disp form


Use something like:

<xsl:value-of select="ddwrt:FormatDate(@ArticleStartDate, 1033, 3)"/>  Change 1033 to you LocalID and the second number is a format specifier. See here for possible values.

Make sure you have the ddwrt namespace reference xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" in the top of your xsl.

how to remove empty record message ,ie There are no items to show in this view....' from a list


add the following code in the page

<script>
function ChangeDiscussionMessage()
{

  var a = document.getElementsByTagName("TD")
  for (var i=0;i<a.length;i++)
  {
    if (a[i].className=="ms-vb")
    {
      if (a[i].innerText.indexOf("There are no items to show in this view")>-1)
      {
         a[i].innerHTML = "&nbsp;<b>&LT;--&nbsp;&nbsp;Your message here.</b>";
      }
    }
  }
}

_spBodyOnLoadFunctionNames.push("ChangeDiscussionMessage")

</script>

how to close a sharepoint modal dialog


SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, "some string here")

For example...

SP.UI.ModalDialog.commonModalDialogClose(0,'Canceled the dialog.'); is like using SP.UI.DialogResult.cancel

SP.UI.ModalDialog.commonModalDialogClose(1,'Yay Success!'); is like using SP.UI.DialogResult.OK

SP.UI.ModalDialog.commonModalDialogClose(-1,'Uh oh... Error'); is like using SP.UI.DialogResult.invalid

Javascript print

function CallPrint() {
            var prtContent = document.getElementById('<%=ReportViewer1.ClientID %>');

            var WinPrint = window.open('', '', 'left=0,top=0,width=800%,height=600,toolbar=1,scrollbars=1,status=1');
            WinPrint.document.write(prtContent.innerHTML);
            WinPrint.document.close();
            winPrint.focus();
            WinPrint.print();
            WinPrint.close();
        }

To stop Sharepoint user profile and Sync Service which is in 'Stopping' stat


will get all the services

stsadm -o enumservices > c:\services.txt

For Sharepoint 2010
stsadm -o provisionservice  -action stop -servicetype "Microsoft.Office.Server.Administration.UserProfileService, Microsoft.Office.Server.UserProfiles, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" -servicename ""

stsadm -o provisionservice  -action stop -servicetype "Microsoft.Office.Server.Administration.ProfileSynchronizationService, Microsoft.Office.Server.UserProfiles, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" -servicename FIMSynchronizationService





For Sharepoint 2013

stsadm -o provisionservice  -action stop -servicetype "Microsoft.Office.Server.Administration.UserProfileService, Microsoft.Office.Server.UserProfiles, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" -servicename ""

stsadm -o provisionservice  -action stop -servicetype "Microsoft.Office.Server.Administration.ProfileSynchronizationService, Microsoft.Office.Server.UserProfiles, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" -servicename FIMSynchronizationService

Claim based authentication (SP13) cannot resolve user ids from Classic windows authentication


SP13 people picker cannot resolve SP10 user ids(e.g: domainname\userid). You have to prefix the user id with "i:0#.W|".
You can add this string as a property, because it wont work with SP10, so you have make it as empty string for SP10.

string mangr = "i:0#.W|" + userProfile["Manager"].ToString();                                                                               
                                        peApprover.Accounts.Clear();
                                                                         
                                        PickerEntity pickerEntity = new PickerEntity();
                                        pickerEntity.Key = mangr;
                                        pickerEntity.IsResolved = true;
                                        ArrayList arrayList = new ArrayList();
                                        arrayList.Add(pickerEntity);
                                        peApprover.UpdateEntities(arrayList);

SharePoint website's style sheet in apps for SharePoint 2013


Customize a list view in apps for SharePoint using client-side rendering


client-side People Picker control in apps for SharePoint 2013


Powershell command to get all event recievers


$web = Get-SPWeb http://sp2010/Site/
$list = $web.Lists["List Name"]
$list.EventReceivers

Programmatically uploading multiple files to Custom sharepoint list


Asset Picker or Sharepoint content browser


To Show an user with presence indicator on a webpart


<span>
 <img width="12" src="/_layouts/images/blank.gif" onload="IMNRC('[USERMAIL]')" id="IMID[GUID]" ShowOfflinePawn=1 alt="Presence bubble">[USERNAME]</span>

http://stackoverflow.com/questions/637915/adding-presence-indicator-to-a-custom-web-part

Check for Attachment Missing in a list form using Javascript


Add below javascript in a content editor. While clicking 'Save' button PreSaveAction will be called automatically.

<script language="javascript" type="text/javascript">
function PreSaveAction()
{
var elm = document.getElementById("idAttachmentsTable");
if (elm == null || elm.rows.length == 0)
{
alert('Attachement missing');
return false;
}
return true;
}</script>

Dynamically show/hide fields in sharepoint edit form


<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script><script type="text/javascript">





$(document).ready(function()
{
$("nobr:contains('Issue Status')").parent('h3').parent('td').parent('tr').toggle();

$("#ctl00_m_g_db968dcc_025b_47ca_8ad4_577d24fe6874_ff17_1_ctl00_ctl00").click(function() {


 $("nobr:contains('Issue Status')").parent('h3').parent('td').parent('tr').slideDown('fast');

});

$("#ctl00_m_g_db968dcc_025b_47ca_8ad4_577d24fe6874_ff17_1_ctl00_ctl01").click(function() {


 $("nobr:contains('Issue Status')").parent('h3').parent('td').parent('tr').slideUp('fast');

});

$("#ctl00_m_g_db968dcc_025b_47ca_8ad4_577d24fe6874_ff17_1_ctl00_ctl02").click(function() {


 $("nobr:contains('Issue Status')").parent('h3').parent('td').parent('tr').slideUp('fast');

});


});</script>

properties.ListItem in ItemAdded is NULL


This is a known issue and will be addressed in future. However it is very common that one need ListItem object in ItemAdded event. Workaround is to get the Listitem using ListItemId and spList.GetItemById. here is code snippet

   SPWeb oSPWeb = properties.OpenWeb();
   SPListItem oListItem = oSPWeb.Lists[properties.ListId].GetItemById(properties.ListItemId);

Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web server administrator.


http://thechriskent.com/2012/06/18/intermittent-unable-to-display-this-web-part-messages/

$myfarm = Get-SPFarm
$myfarm.XsltTransformTimeOut

If you’re experiencing the above problem, you probably got a 1 back from the above command indicating that the timeout is currently set to 1 second. To set it to a more reasonable value (we choose the original 5 seconds) just do this (assuming you set the $myfarm object using the above powershell):



$myfarm.XsltTransformTimeOut = 5
$myfarm.Update()

Sharepoint Error Logging in Event Handler and webparts


using Microsoft.Office.Server;
try
{
 //Code goes here
}
catch (Exception ex)
{
properties.Cancel = true;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Error in cash advacne item added: {0} || Source:{1} || StackTrace:{2}", ex.Message, ex.Source,ex.StackTrace);
});
throw new SPException("Unable to Create request");
}
finally
{
     if (web != null)
     {
      web.AllowUnsafeUpdates = false;
      web.Dispose();
      }
 }

SPQueryThrottleException - ContentIterator


SharePoint Server 2010 provides a new class named ContentIterator that you can use to query lists without hitting throttle limits and hence can avoid receiving an SPQueryThrottleException. You should consider using ContentIterator if you need to run a query that will return more than 5,000 rows of data.

The ContentIterator object divides the list items into chunks and runs the query against one chunk of list data at a time. Each list item is processed asynchronously by a callback method until the query is complete.

The following  example demonstrates usage of the ContentIterator class.

    static int noOfErrors = 0;
    static int noOfItemsProcessed = 0;

    string camlQuery = @"<View><Query><Where>             
                    <IsNotNull>
                        <FieldRef Name='Title' />                      
                    </IsNotNull>              
                   </Where></Query></View>";

    ContentIterator iterator = new ContentIterator();
    SPQuery listQuery = new SPQuery();
    listQuery.Query = query1;
    SPList list = SPContext.Current.Web.Lists["Tasks"];
    iterator.ProcessListItems(list,
        listQuery,
        ProcessItem,
        ProcessError
    );
}

public  bool ProcessError(SPListItem item, Exception e)
{
    // process the error
    noOfErorrs++;
    return true;
}
public void ProcessItem(SPListItem item)
{
    noOfItemsProcessed++;
    //process the item.
}


http://extreme-sharepoint.com/2012/07/17/data-access-via-caml-queries/

Event Handler - Showing a different web than the current web


Instead of properties.web, use properties.openweb()

String was not recognized as a valid Boolean - People Editor


IF are using a people editor control on your custom web part and is pre loaded with a value, there is a chance that the page throws an "String was not recognized as a valid Boolean" error on page postbacks.

The workaround for this is

if (IsPostBack)
    {
        yourPeopleEditor.Validate();
    }