Friday, May 9, 2014

Search SharePoint List items using jQuery/JavaScript and Web Service

You can use jquery/javascript to search items from a SharePoint list. You can define you CAML query and based on that result will be displayed. Lists.asmx web service is used in this case. You can use this to search items both on SharePoint online or on-premises versions.

List.asmx service is called and post method is called provided with soap envelope and in return we get the list items in from of xml. You can also highlight the searched keyword in the result.

Tuesday, March 25, 2014

How to create folder and sub folders inside Document Library using web service in SharePoint

In this post i will explain how we can use the UpdateListItems method of Lists web service to create folder and sub folder inside a document library. I will give you the code snippet and using this you can create folders and sub folders inside document library.

Here is the code snippet

 private void CreateFolder(string listName, string rootSubFolderName, string newFolderName)
        {
       
       
            string rootFolder = rootSubFolderName.Length > 0 ? string.Format("/{0}/{1}", listName, rootSubFolderName) : listName;
       
            string xmlCommand = string.Format("<Method ID='1' Cmd='New'><Field Name='FSObjType'>1</Field><Field Name='BaseName'>{1}</Field></Method>", rootFolder, newFolderName);
         
            XmlDocument doc = new XmlDocument();
            System.Xml.XmlElement batchNode = doc.CreateElement("Batch");
            batchNode.SetAttribute("OnError", "Continue");
            //Insert / to front as it is required by web service.
            if  (!rootFolder.StartsWith("/"))
                rootFolder = string.Format("/{0}",rootFolder);
//if you are having different site collection use  rootFolder = string.Format("/sites/sitename/{0}",rootFolder);

            if(rootSubFolderName.Length>0)
                rootFolder = string.Format("/{0}", rootFolder);
//if sub folder is to be created inside a folder

            batchNode.SetAttribute("RootFolder", rootFolder);
            batchNode.InnerXml = xmlCommand;
            XmlNode resultNode =listsservice.UpdateListItems(listName, batchNode);

            if ((resultNode != null) && (resultNode.FirstChild.FirstChild.InnerText == FOLDER_EXISTS) || (resultNode.FirstChild.FirstChild.InnerText == SUCCESS))
            {
                // success
            }
            else
            {
                //failure
                throw new Exception("Create new folder failed for: " + newFolderName + ". Error Details: " + resultNode.OuterXml);
            }
        }

Usage: You can call this function to create folders and sub folders as described below:

1)  CreateFolder("Your Document Library Title", "","Folder Name");
 This will create the folder inside "Your Document Library Title" with the Name "Folder Name" as no rootSub folder name parameter is specified.
 2)  CreateFolder("Your Document Library Title", "RootFolder","Folder Name");
 This will create the sub folder inside "Your Document Library Title", inside "RootFolder"
In this case hierarchy of the folders will be:Your Document Library Title/RootFolder/Folder Name

Tuesday, June 11, 2013

Get Current User's Regional Settings and Locale

SharePoint has a feature where user can set his/her own Regional settings and locale. In this post I will tell you how to get these settings using Object Model and show the date format according to the user's Locale.

To set your Regional settings

Select Welcome Control-> Select My Settings -> Select My Regional Settings

You have to uncheck the "Always follow web settings" option and then set your Locale.

In the code file, use this code

Get the current user's Regional settings by SPRegional Settings class

 SPRegionalSettings rgnUser = SPContext.Current.Web.CurrentUser.RegionalSettings;
             
I have created a property to get the date format you can use the same

public static string format
        {
            get
            {
                SPRegionalSettings rgnUser = SPContext.Current.Web.CurrentUser.RegionalSettings;
                if(rgnUser!=null)
             
                return "{0:" + System.Globalization.CultureInfo.GetCultureInfo(Convert.ToInt32(rgnUser.LocaleId)).DateTimeFormat.ShortDatePattern + "}";

                else

                    return "{0:" + System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern + "}";
            }
        }
If user has set his/her Regional Settings then it will show the date format according to the set locale otherwise it will show the current culture's date format.

Thursday, November 22, 2012

GAC deployment but code does not update

Recently i faced a strange issue and i want to share that with you guys, when deploying the application pages and dll in to GAC. The issue was when i change the html and code and deploy to my sever it was working fine but when i installed the same solution on production environment only the html was showing updates but not the code .i.e changes made to the code files were not reflecting on the production environment. I used the gac utility to uninstall and install but no effect on the code, i was shocked with this strange issue html is reflecting changes but not the code.

I googled this issue but not worked for me. Then in one of the post i read that check the dll version and time of installion, then first thing i did is change the dll version from the project properties. Right click on the project, select Assembly Information and then changed the dll and file version, then build the wsp file and installed on the production server. Yes this time it did the trick code changes were reflecting on the application pages on the production site. The only problem was change the dll version and make sure that in the gac it has latest version installed.


Monday, October 15, 2012

Connected Web Parts

SharePoint Object Model provides the functionality where web parts can communicate with each others by sending and getting parameters and this mechanism is called Connected Web Parts. You can create connections between web parts and send/receive information between them.

In this post i am going to explain how you can make connection between web parts pro-grammatically.

The connected web parts is based on the concept of interface.

First of all creates a interface and a property whose value can be send to other web parts. In my case i have created a property to send client info to other web part 

  public interface ClientInterface
    {
        string clientinfo { get; }

    }
Now create a web part from say "SenderSenderWebPart " where you want to send the value to other web part and inherit above interface like

 public class SenderWebPart : WebPart,ClientInterface
    
Now create a property to send the value in this web part

 public string clientinfo
        {

            get
            {
                return "Your Test Value";
            }
        }

and create a connection attribute like below:

[ConnectionProvider("clientinfoprovider")]
        public ClientInterface getclientname()
        {
            return this;
        }

Now create another web part say "Receiver" that will receive this clientinfo from above web part

Create a object of interface in this new web part like   ClientInterface clientinfostring;

Create a connection consumer attribute like 

[ConnectionConsumer("clientinforRightNavigationWebpart", "GetClientInfo")]
        public void ReceiveClientInfo(ClientInterface c)
        {
            clientinfostring = c;
        }

Now you can get the clientinfo in this web part. 

For example 

 protected override void RenderContents(HtmlTextWriter writer)
        {

      
            if (clientinfostring != null)
            {

                 string clientname= clientinfostring.clientinfo;
              
                writer.Write(clientname);
            }

Now build and deploy the web parts. When you place these web parts on page, select edit page, edit sender web part, select connection and make connection to the receiver web part as shown below







Once you create a connection it ask for the confirmation. Now your web parts are connected and can communicate with each other.

Friday, July 20, 2012

InfoPath Form Publishing Error

When you publish  InfoPath  form to the library, then there are chances that you get this error message

"An issue was found with the following variable 'Form.FormCode_variable'. Member variables are not supported. Use the FormState property to store data"

The main cause of this error is that somewhere in the code of form you have declared a variables and you are accessing that variables.

e.g. public string clientname="c1";

and you are using this "clientname" variable through out the form.

To avoid this use property like

public string clientname
{
get;set;
}

and use the FormState property of  InfoPath  form to use this value through out the form.

FormState property is state management technique in InfoPath forms and can be accessed in the form.

Use FormState["client"]=clientname;

and to access this use string clientname=Convert.ToString(FormState["client"]);

With the help of FormState the form will be published without any errors.

Friday, July 13, 2012

SharePoint Rich Text Input Control

SharePoint 2010 has inbuilt text box control that can be used to create rich text strings including images, hyperlinks, can use your own html tags in this.




Let's see how to use this control

The control tag is defined below

 <SharePoint:InputFormTextBox ID="txtmsg" runat="server" Rows="10" TextMode="MultiLine"
                RichText="true" RichTextMode="FullHtml">

There are properties that turns this simple text box to rich text box control and those are "RichTextMode" and "RichText"

Set "RichText" property value to true to and "RichTextMode" to "FullHtml". You can set height and width of this control using the "Columns" and "Rows" properties respectively.

Known Issues

This control does not work with firefox and chrome browsers. Only works with IE.

Sometimes this control does not render properly and only html text is displayed, to overcome this issue use the below function on the html part of page where you are using this control.


This function converts the text area to rich text control using function"RTE_ConvertTextAreaToRichEdit"

that is defined in the "/_layouts/1033/form.js" file.


<script type="text/javascript">

function CreateRichEdit(id) {

if (browseris.ie5up && browseris.win32 && !IsAccessibilityFeatureEnabled()) {

g_aToolBarButtons = null;

g_fRTEFirstTimeGenerateCalled = true;

RTE_ConvertTextAreaToRichEdit(id, true, true, "", "1033", null, null, null, null, null, "Compatible", "\u002f", null, null, null, null);

RTE_TextAreaWindow_OnLoad(id);

}

else {

document.write("&nbsp;<br><SPAN class=ms-formdescription><a href='javascript:HelpWindowKey(\"nsrichtext\")'>Click for help about adding basic HTML formatting.</a></SPAN>&nbsp;<br>");

};

}

    var id = "<%= txtmsg.ClientID %>";


"here use your own rich text control id and call the function like below;

    CreateRichEdit(id);
</script>