Top Menu

Wednesday, July 28, 2010

Update a List Column using JQuery with SharePoint WebServices


Scenario: Click on the image in data View to update the Status on an item.
PreReq: A list with choice column Status (0,1,2).
0 represents Not started,
1 represents In Progress and
2 represents Completed.

You need two libraries:
1. JQuery (jquery-1.4.2.js)
2. SPServices (jquery.SPServices-0.5.6.min.js)

Add following code in your page in the head, or where ever you want to:

<script type="text/javascript" src="Scripts/jquery-1.4.2.js"></script>  
<script type="text/javascript" src="Scripts/jquery.SPServices-0.5.6.min.js"></script>  
  
<script type="text/javascript">  
  
function UpdateStatusCode(divId, waitMessage, ID, StatusCode)  
  {  
    
   //alert(divId +" "+ waitMessage +" "+ ID + " " + StatusCode);  
   if (confirm ("Are you sure you want to update the status of the selected event?"))  
   {  
    StatusCode = StatusCode + 1;  
      
    if (StatusCode < 3)  
    {  
     $(divId).html(waitMessage).SPServices({  
     operation: "UpdateListItems",  
     listName: 'Events',  
     ID: ID,  
     valuepairs: [["Status", StatusCode]],  
     completefunc: function (xData, Status) {  
      var out = $().SPServices.SPDebugXMLHttpResult({  
       node: xData.responseXML,  
       outputId: divId  
      });  
        
      window.location = RefreshPageURL('Default.aspx');  
  
      }  
     });  
    }  
    else  
    {  
     alert('This event is already completed.');  
    }  
   }  
  }  
</script>  

Place the following div where you want to display the status column in the DataView Webpart. XSL in the <div> will display the relevant image and click event on the div will call the UpdateStatusCode() function to update the value on StatusCode column via JQuery and then page will get refreshed to show the right image based on the updated value.

<div id="div+{@ID}" onclick="UpdateStatusCode('div'+{@ID}, 'Updating', {@ID}, {@Status});">  
<xsl:if test="@Status = '0'"><img src="images/NotStarted.png"></xsl:if>  
<xsl:if test="@Status = '1'"><img src="images/InProgress.jpg"></xsl:if>  
<xsl:if test="@Status = '2'"><img src="images/Completed.jpg"></xsl:if>  
</div>  



JQuery makes life easy :o).

Thursday, July 8, 2010

SharePoint WebPart Custom Properties



Add the following piece of code (to create the custom property Password for your custom WebPart) in your WebPart class. Now the property will get displayed under Parameters section in the Property panel of the WebPart as displayed in the screenshot below.


private string _strPassword;


[Browsable(true),
Category("Parameters"),
DefaultValue(""),
WebBrowsable(true),
Personalizable(PersonalizationScope.Shared),
WebDisplayName("Password"),
Description("Network Password")]
public string strPassword
{
    get
    {
        return _strPassword;
    }
    set
    {
        _strPassword = value;
    }
}

Now Access strPassword anywhere in the code to access the value provided by the user.



Friday, June 4, 2010

SharePoint 2007 Web Service: Get Items

Use lists.asmx to get the items through a desktop application

Below is the C# function to call the lists.asmx MOSS Web Service to get list items from a list/document library.
Add reference to lists.asmx to your project and use the following code:


private void GetItems(string strListName)
{

try
{
    #region Connect to URL

    this.m_objWSSListService.Url = this.cmbURL.Text.Trim('/') + "/_vti_bin/lists.asmx";

    string sDomain = string.Empty;
    string sUserName = this.txtLogin.Text.Trim();
    if (sUserName.IndexOf("\\") > 0)
    {
        sDomain = sUserName.Split("\\".ToCharArray())[0];
        sUserName = sUserName.Split("\\".ToCharArray())[1];
    }

    this.m_objWSSListService.Credentials = new System.Net.NetworkCredential(sUserName, this.txtPassword.Text.Trim(), sDomain);

    #endregion

    string sListName = strListName;
    string SourceDocumentURL = "";
    string strTempLocation = "C:\\Temp\\";
    string strFileName = "";

    System.Xml.XmlNode xnListSchema = m_objWSSListService.GetList(sListName);

    //get the Data from the List
    System.Xml.XmlDocument xdListData = new System.Xml.XmlDocument();
    System.Xml.XmlNode xnQuery = xdListData.CreateElement("Query");
    System.Xml.XmlNode xnViewFields = xdListData.CreateElement("ViewFields");
    System.Xml.XmlNode xnQueryOptions = xdListData.CreateElement("QueryOptions");

    System.Xml.XmlNode xnListData = m_objWSSListService.GetListItems(sListName, null, xnQuery, xnViewFields, null, xnQueryOptions);


    if (!Directory.Exists(strTempLocation))
    {
        Directory.CreateDirectory(strTempLocation);
    }

    foreach (XmlNode outerNode in xnListData.ChildNodes)
    {
        if (outerNode.NodeType.Equals(System.Xml.XmlNodeType.Element))
        {
            foreach (XmlNode node in outerNode.ChildNodes)
            {
                if (node.NodeType.Equals(System.Xml.XmlNodeType.Element))
                {
                    MessageBox.Show(node.Attributes.GetNamedItem("ows_Title").InnerText);
                }
            }
        }
    }

}
catch (System.Exception ex)
{

    this.WriteLog(ex.ToString());
}

}

Wednesday, June 2, 2010

SharePoint 2007 Web Service: Create Folder in Document Library

Use lists.asmx to create folder in a document library through a desktop application

Below is the C# function to call the lists.asmx MOSS Web Service to create folders in a document library.
Add reference to lists.asmx to your project and use the following code:



private void CreateFolder(string strPath, string strListName)
{

try
{
#region Connect to URL

this.m_objWSSListService.Url = this.cmbURL.Text.Trim('/') + "/_vti_bin/lists.asmx";

string sDomain = string.Empty;
string sUserName = this.txtLogin.Text.Trim();
if (sUserName.IndexOf("\\") > 0)
{
    sDomain = sUserName.Split("\\".ToCharArray())[0];
    sUserName = sUserName.Split("\\".ToCharArray())[1];
}

this.m_objWSSListService.Credentials = new System.Net.NetworkCredential(sUserName, this.txtPassword.Text.Trim(), sDomain);

#endregion

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlElement Batch = xmlDoc.CreateElement("Batch");

Batch.SetAttribute("OnError", "Continue");
Batch.SetAttribute("ListVersion", "0");
string strBatch = "<method id="1" cmd="New">";
strBatch = strBatch + "<field name="ID">New</field>";
strBatch = strBatch + "<field name="FSObjType">1</field>";
strBatch = strBatch + "<field name="FileRef">" + strPath + "</field></method>";

Batch.InnerXml = strBatch;
XmlNode ndReturn = this.m_objWSSListService.UpdateListItems(strListName, Batch);
if (ndReturn.FirstChild.FirstChild.InnerText != "0x00000000")
{
    this.WriteLog(ndReturn.InnerText);
}

this.WriteLog("Create Operation - List:" + strListName + " - Folder: " + strPath);


}
catch (System.Exception ex)
{
this.WriteLog(ex.ToString());
}

}

SharePoint 2007 Web Service: Download Documents

Use lists.asmx to download the documents from a document library through a desktop application

Below is the C# function to call the lists.asmx MOSS Web Service to download the documents from a document library.
Add reference to lists.asmx to your project and use the following code:


private void DownloadDocumnts(string strListName)
{

try
{
    #region Connect to URL

    this.m_objWSSListService.Url = this.cmbURL.Text.Trim('/') + "/_vti_bin/lists.asmx";

    string sDomain = string.Empty;
    string sUserName = this.txtLogin.Text.Trim();
    if (sUserName.IndexOf("\\") > 0)
    {
        sDomain = sUserName.Split("\\".ToCharArray())[0];
        sUserName = sUserName.Split("\\".ToCharArray())[1];
    }

    this.m_objWSSListService.Credentials = new System.Net.NetworkCredential(sUserName, this.txtPassword.Text.Trim(), sDomain);

    #endregion

    string sListName = strListName;
    string SourceDocumentURL = "";
    string strTempLocation = "C:\\Temp\\";
    string strFileName = "";

    System.Xml.XmlNode xnListSchema = m_objWSSListService.GetList(sListName);

    //get the Data from the List
    System.Xml.XmlDocument xdListData = new System.Xml.XmlDocument();
    System.Xml.XmlNode xnQuery = xdListData.CreateElement("Query");
    System.Xml.XmlNode xnViewFields = xdListData.CreateElement("ViewFields");
    System.Xml.XmlNode xnQueryOptions = xdListData.CreateElement("QueryOptions");

    System.Xml.XmlNode xnListData = m_objWSSListService.GetListItems(sListName, null, xnQuery, xnViewFields, null, xnQueryOptions);


    if (!Directory.Exists(strTempLocation))
    {
        Directory.CreateDirectory(strTempLocation);
    }

    foreach (XmlNode outerNode in xnListData.ChildNodes)
    {
        if (outerNode.NodeType.Equals(System.Xml.XmlNodeType.Element))
        {
            foreach (XmlNode node in outerNode.ChildNodes)
            {
                if (node.NodeType.Equals(System.Xml.XmlNodeType.Element))
                {
                    XmlNode FileNameNode = node.Attributes.GetNamedItem("ows_EncodedAbsUrl");
                    SourceDocumentURL = FileNameNode.InnerText;
                    strFileName = SourceDocumentURL.Substring(SourceDocumentURL.LastIndexOf('/') + 1).Replace("%20", " ");

                    /*
                     * ?noredirect=true 
                     * will not open the file in default program (e.g. XSN for InfoPath), instead it will download the file
                     * 
                     * */

                    System.Net.WebClient objWebClient = new System.Net.WebClient();
                    objWebClient.Credentials = CredentialCache.DefaultCredentials;
                    objWebClient.DownloadFile(SourceDocumentURL + "?noredirect=true" ,strTempLocation + strFileName);

                    this.WriteLog("File Downloaded: " + SourceDocumentURL);
                }
            }
        }
    }

}
catch (System.Exception ex)
{

    this.WriteLog(ex.ToString());
}

}

Tuesday, June 1, 2010

SharePoint 2007 Web Service: Create User Group

Use UserGroup.asmx to create User Group through a desktop application

Below is the C# function to call the UserGroup.asmx MOSS Web Service to create Uer Groups.
Add reference to UserGroup.asmx to your project and use the following code:


private void CreateUserGroup(string strGroupName, string strDescription)
{
try
{

    #region Connect to UserGroup.asmx

    this.objUserGroupService.Url = this.cmbURL.Text.Trim('/') + "/_vti_bin/UserGroup.asmx";

    string sDomain = string.Empty;
    string sUserName = this.txtLogin.Text.Trim();
    if (sUserName.IndexOf("\\") > 0)
    {
        sDomain = sUserName.Split("\\".ToCharArray())[0];
        sUserName = sUserName.Split("\\".ToCharArray())[1];
    }

    this.objUserGroupService.Credentials = new System.Net.NetworkCredential(sUserName, this.txtPassword.Text.Trim(), sDomain);

    #endregion

    this.objUserGroupService.AddGroup(strGroupName, this.txtLogin.Text.Trim(), "user", this.txtLogin.Text.Trim(), strDescription);
    this.WriteLog("Created Group: " + strGroupName);


}
catch (System.Exception ex)
{
    
    this.WriteLog(ex.ToString());
}
}

Sunday, May 9, 2010

Developing Custom WebPart using ASP.NET Web User Control


In this post I will explian how to build a custom WebPart for SharePoint 2007 and how to use ASP.NET Web User Control in it. I am using Visual Studio 2008 for the development.

Following are the steps to create a custom webpart and calling/loading Web User Control in it:

Building WebPart and Web User Control project
  1. Craete ASP.NET Web Application Project.

  2. Delete Default.aspx.

  3. Add two new folders: UserControls and WebPart into the solution.

  4. Add new Web User Control in UserControls folder.

  5. Add new CS Class file TrainingWP.cs in WebPart folder.

  6. Add reference to SharePoint.dll (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll)

  7. Add followign code to TrainingWP.cs


  8. namespace Training
    {
    [Guid("2E4AFAAA-AE99-4e15-9972-E6195EFBDD9C")]
    public class TrainingWP : WebPart
    {
    private Control uc = null;
    private string ucPath = "~/UserControls/TrainingUC.ascx";

    protected override void CreateChildControls()
    {
    try
    {
    uc = Page.LoadControl(ucPath);
    this.Controls.Add(uc);
    }
    catch (Exception ex)
    {
    throw ex;
    }
    finally
    {
    base.CreateChildControls();
    }
    }
    }
    }

    We are overriding the CreateChildControls method of the WebPart class in which we will load the Web User Control.
  9. Go to Tools -> Create GUID and copy/paste GUID above the class and add reference using System.Runtime.InteropServices; line.
  10. Open code behind for Web User Control and add using Microsoft.SharePoint; line and in Page_Load function write hello world code and build the solution.


Deploying the WebPart and the Web User Control
  1. In Project Properties -> Build Event tab -> Post-build Event Command add following line:
    "C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\gacutil.exe" /i $(TargetPath)
    This will deploy our webpart dll into GAC after building the solution.

  2. In Project Properties -> Signing tab -> check Sign Assembly -> and give a name.

  3. Build the solution and WebPart should be deployed into GAC (c:\Windows\assembly).

  4. Create DWP File using following XML







  5. Cannot import this Web Part.



    Training Web Part





  6. Upload DWP file to WebPart Gallery. DWP file tells SharePoint to load which library when webpart is called.

  7. Open the root folder of the Web Application and edit Web.config. Under <SafeControls> add following line




  8. Under <assemblies> in Web.config add following line




  9. Copy UserControls folder in to the root folder of the Web Application.(Just copy ASCX)

  10. Do iisreset and add the WebPart on the page through Web UI of the site.


Thats it :o). Happy Programming.

Official SharePoint Documentation

I have recently contributed to the official SharePoint documentation for developement. Check it out here: https://docs.microsoft.com/en-us...