Abin Jaik Antony

its all about my work & life….

Custom XML mapping of content control in a SharePoint Document Library Template

Posted by Abin Jaik Antony on May 3, 2012

Hi Developers,

After a long time ( was in a busy schedule of establishing family after my marriage :) ) I thought I will post this article for setting the XML mapping  of content control  in a Word document template  for SharePoint Document Library. To be frank, in most of the cases we are / will be  using QuickParts Add-in to add the content controls  which are already mapped with SharePoint ContentType fields. But in this article I will be explaining how to set up a document template for a document library without touching the QuickParts Add- in. Sometimes this will be helpful to the developers who are programmatic-ally/dynamically  creating  document templates or content controls to document templates.  To make this article in one line, its about setting XPath, Prefix Mapping for content controls using SetMapping function of XMLMapping property of content control, like contentControl.XMLMapping.SetMapping(Xpath,PrefixMapping).

These are things that  you should have handy with you before starting this exercise.

  1. A  Document Content Type with some site columns referred inside – Say, we will name it as “ExpenseContentType” that have  2 site columns (SC_ExpenseName, SC_ExpenseCount )
  2. A Document Library created which have content type that is mentioned on the above step( Step 1) – Say , ExpenseDocumentLibrary.
  3. Word Content Control Tool Kit – Download this tool kit.  This is just for the analysis purpose of the template or to understand what is happening behind the scene.
  4. Visual Studio – Just in case if  you need to code the logic for XML mapping. (Code is embedded on the bottom of the post)

So, Lets start from the document library (ExpenseDocumentLibrary)

Step 1 . Go the document library setting –> ContentType (ExpenseContentType) –> Advanced Settings

Here on the Advanced setting page of the Document library Content Type, Click on the Edit Template link(see image below) . This will open a blank document template on the MS Word . Save this locally on your machine with any user friendly name , Say ExpenseTemplate.docx

Edit Template from the Document ContentType of the document library

Step 2. For analysis, open the locally saved blank template using the Word Content Control toolkit. We can see the content type fields on the custom XML parts of the document. This means the ContentType related data like Fields etc are there in this document in XML(XSD) format.  Since its a blank document , there is no matter in the Content Controls section.

Blank document

Step 3. Let us add some content controls to this document template. For that, Open the word document using MS Word and from Developer tab add 1 or 2 plain text content controls to the document as if  it resemble a template. (See image below). Name the content controls exactly as the Site Columns name in ContentType. Means, name Expense Name content control as “SC_ExpenseName”.

Save this document after the adding the controls.

Step 4 . Re-Open the document in the Word Content Control Tool Kit. Now we can observe that on the content controls section it showing the control entries without having its XPath set with ContentType Fields inside the file. (See the Image below). Basically XPath and Prefix mapping of the Custom XML parts shown on the right pane for the each field need to be mapped with content control.

Step 5. In this step we will set the mapping between the content controls and ContentType fields. Actually we can set mapping using Word Content Control Tool kit itself , but it will become a manual process. Better we will do it “programmatic-ally”  :) .

For doing this, I am creating  a Word Add-In project  in Visual Studio . So open a Visual Studio Instance –> New Project –> Word Add – In (see image below).

Give any user friendly name to the project.  After that , Add a “Ribbon” into this  Add- in project (Right Click on Project –> Add –>  New Item –> Ribbon (see image below))

Again, give a user friendly name to the ribbon. On the visual designer of the ribbon add a button(label it as “Set Mapping”) and on the click event of  button , we will write some code as shown below .

      ///
<summary> /// Click event of the Set Mapping button
 /// </summary>
        ///
        ///
        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            //Accessing the active document
            Document document = Globals.ThisAddIn.Application.ActiveDocument;
            string nsURI = string.Empty;

            //retreving the content control collection of the active document.
            ContentControls contentControls = document.ContentControls;

            //Looping through the content Control collection.
            foreach (ContentControl cntntCtrl in contentControls)
            {

                var ctrlTitle = cntntCtrl.Title;
                //Setting the XPath for each control. this is under a condition that name of the Content type site column /field
                // and content control name & tag is exactly same.
                string xpath = "/ns0:properties[1]/documentManagement[1]/ns1:" + ctrlTitle + "[1]";

                //Private function to get the NameSpace URI of the content type field
                nsURI = GetXSDNameSpaceURI(document, cntntCtrl);

                //Mapping the content control.
                bool isMapped = cntntCtrl.XMLMapping.SetMapping("/ns0:properties[1]/documentManagement[1]/ns1:" + ctrlTitle + "[1]", "xmlns:ns0='http://schemas.microsoft.com/office/2006/metadata/properties' xmlns:ns1='" + nsURI + "'", null);

                if (isMapped == true)
                { MessageBox.Show("Mapping successfully done...!"); }
                else
                { MessageBox.Show("Error in XML Mapping"); }

            }

        }

        ///
<summary> /// private function to get the namespace URI of the content type.
 /// </summary>
        ///
        ///
        ///
        private string GetXSDNameSpaceURI(Document document, ContentControl control)
        {
            string nsURI = string.Empty;
            CustomXMLParts xmlParts = document.CustomXMLParts.SelectByNamespace("http://schemas.microsoft.com/office/2006/metadata/properties");
            foreach (CustomXMLPart xmlPart in xmlParts)
            {
                XmlDocument XDoc = new XmlDocument();
                XDoc.LoadXml(xmlPart.XML);
                XmlNodeList result = XDoc.GetElementsByTagName(control.Title);
                nsURI = result[0].NamespaceURI;
                break;
            }

            return nsURI;
        }

Build the project and press F5. This will open a default word document. Close that document and open our document library template where we have add content control. Find the ribbon that we have created on the opened document and press the button “Set mapping”. This will set the XPath mapping for each content control and throw a message box saying “Mapping successfully done…!”.(see image below)

Now I will explain what actually the above code does. Basically it iterates through the content controls collection and by using each content control’s title its creating an “XPath” string and “Prefix mapping” using the content type namespace URI . The key player is SetMapping Function of the content control’s XMLMapping property. This function is used to set the mapping for the content control. The SetMapping function can be called on the event after the control adding to make it more clean. But since this is a POC we will use iteration logic. The entire article is based on the SetMapping function to make link between content control and content type.

Now just open the document in the Word Content Control toolkit and see the XPath set against each content control. (see image below)

This is the time to upload this document template back into Sharepoint. Go to the Advanced settings of the Document library content type and upload the template using “upload a new document template”. After the uploading is over try adding document files which have data inserted. You can see content control data getting binded with content type columns within the document library.

I hope you enjoyed/ understood this article. Thanks for readings. Comments are invited.

Posted in Sharepoint, Technical Posts | Tagged: , , , , , | 6 Comments »

When or How to Use Run With Elevated Privileges (RWEP) in SharePoint

Posted by Abin Jaik Antony on August 7, 2011

The scope of this article is to explain the usage of RunWithElevatedPrivileges() [RWEP] – a method for security elevation for custom SharePoint components.

“The RWEP method enables you to supply a delegate that runs a subset of code in the context of an account with higher privileges than the current user”, this is the definition from Microsoft MSDN. Basically the code executed inside this method has “System Account” privileges in addition to the current user privileges or in a better way – we can tell that this method runs under the Application Pool identity, which has site collection administrator privileges on all site collections hosted by that application pool.

For a detailed explanation please go through my article published on www.mssharepoints.com or Click here

Posted in Sharepoint, Technical Posts | Tagged: , , , | Leave a Comment »

Multiple listing controls with a single datasource – InfoPath

Posted by Abin Jaik Antony on June 8, 2011

The scope of this article is to explain how to populate multiple InfoPath listing controls like a Drop-Down List and a List Box with only one datasource. The scenario can be like this:

Assume we have 2 to 3 SharePoint lists with data on our SharePoint site and we have some listing controls on our InfoPath form. The aim is to populate all these listing controls using only a single InfoPath datasource.

Solution

By default we do have four “Receive Data” options for InfoPath datasource like an XML document, DataBase,Web Service, and SharePoint Lists & Libraries. As mentioned in the “Problem”, our aim is to populate data from different SharePoint lists to different listing controls on an InfoPath form. Usually, everyone will create different datasources from SharePoint lists for each listing control, but we can utilize the “Web service” option for populating many listing controls with a single datasource. Click here for the entire article that i have published on www.mssharepointtips.com

Posted in Sharepoint, Technical Posts | 1 Comment »

Html Editor Control for SharePoint Web parts

Posted by Abin Jaik Antony on October 10, 2010

Hello SharePoint Developers,

This time i have a simple stuff on SharePoint , it is regarding the rich text editor control on SharePoint.  During our custom webpart developement if we want a HTML Editor/rich text editor on our webpart, we can utilize InputFormTextBox Class of the SharePoint Object Model.

Please read my article regarding InputFormTextBox on the MSSHAREPOINTTIPS.COM

Posted in Sharepoint, Technical Posts | Tagged: , | Leave a Comment »

HTML5 <video> tag and my concept of Video mailing.

Posted by Abin Jaik Antony on July 30, 2010

For the last couple of weeks I am surfing a lot for HTML5 features and whatever new features it have is really amazing. You can also find many articles on web related to the HTML5. I found this article as the best describer , html5demos. When you check new elements that added on this new HTML version , you can find the tag “video” .

The purpose of this media element/tag is to play videos or movies. Currently we use third party plug ins of Quick Time, Flash , Real Player etc to view videos on our web page.
But now with HTML5 we can directly embed videos on the web page using . This element do have “src” attribute just as in <img> tag where we can give url of the video. Currently only web browsers such as Fire Fox 3.5+ , Chrome, Safari 3+ , Opera supports the video tag. For IE users its not currently available, but soon it will get supported from IE9 .

Here, the idea that I want to express is something related to Video Mailing. This means that every email provider can give video messaging service too , when HTML5 become popular. My idea can be more elaborated like this , there will be a “Create a video mail” link on our email account page . When clicking on this link, cam and mic on the client machine will get activated[same as in the FaceBook's “Create Video” option.] .The video will be saved on the server and intimation will be send to the receiver’s inbox after clicking on the send button. When receiver clicks on the video message, it will start rendering as the video on the page. The purpose is to convey the messages with emotions , gestures, actions etc. I feel there are some advantages and disadvantages for this approach.

  Advantages

  • Conveying messages with expressions, emotions etc
  • Authentication of the sender can be 100% assured, since it is a video email.
  • No need to go for big big email drafting to convey a small message.
  • Clarity of message will be more in Video Mail.

  Disadvantages

  • More server space will be utilized than the regular text messages
  • Instant messaging need hardwares like camera ,mic on the sender’s machine.
  • More bandwidth is required for receiving video mail than the text emails 

Kindly comment on my idea of Video mailing and lets have discussion on the same . Thanks

Posted in HTML /HTML5, Technical Posts | Tagged: , , , | Leave a Comment »

Lets move to C# 4.0

Posted by Abin Jaik Antony on June 29, 2010

Some features like Dynamic programming,Optional arguments,Named arguments

Dynamic Programming :

This is the major feature of C# 4.0. In the first look it looks something like our previous “var” type of C#3.0 or regular object type that we have with C#,root Type of .NET . But its not like that. Actually when you assigns a variable of Type “dynamic” and use its properties/methods ,compiler doesn’t mind it at compile time. Means, no method/property resolution takes part in compile time and it will take care all of those things at run time. By these words dont think “dynamic” is dynamic type ,its a static type only.

The below mentioned code is a small example for the dynamic programming.

using System;
using System.Text;

namespace DynamicType
{
	class Program
	{
		static void Main(string[] args)
		{

			Mathematics objmathematics = new Mathematics();
			dynamic objdynamic = objmathematics;

			
			double resAdd= objdynamic.add(3,2);
			Console.WriteLine(resAdd.ToString());

			//The method "subtract" is not present in the Class Mathematics.
			double resSub = objdynamic.subtract(3, 2);
			Console.WriteLine(resSub.ToString());

			Console.ReadLine();
		}
	}

	class Mathematics
	{ 
	
		public Mathematics()	{}


		public double add(double a, double b)
		{
			return a + b;		
		}
	}
}

On compiling the above code, the build will succeed with a smile. But at run time it will break at code line number 18. Because the function “subtract” that is trying to resolve is not present in the Mathematics Class and method “add” will pass through because it is available.

The DLR, Dynamic Language Runtime is responsible for this dynamic programming capability . Basically its built on the top of the CLR to make the dynamic languages such as IronPython, IronRuby etc to get supported. To know more about DLR please go to this link

The main use of this dynamic programming is to support the compilation during interfacing of our managed code with COM , Javascript DOM or any dynamic languages.


Optional and Named arguments:

Now we can have optional values for the C# methods . We can set default values for the arguments and can pass the values during the method call according to our need.Also we can call each parameter by its name , not by its position as earlier. This is called Named argument

It will be like this :

public double GetPNRValue(double a=1,double b=0,double c=1)
		{
			return (a * b / c);
		}

And when we call this method, we can pass arguments like this

double resPNR = objdynamic.GetPNRValue(2,c:0);			

It says that “a” is 2, “b” can be the optional argument and “c” be zero . Here “c” is the Named argument.

Posted in C# 4.0, Technical Posts | Tagged: , , , , , | 2 Comments »

Cascading dropdowns in InfoPath from SharePoint.

Posted by Abin Jaik Antony on May 26, 2010

It is very common for every developer to have a situation to  develop cascading dropdowns during their development life. It can be Category –Product scenario, Country-State scenario etc.  Here the case is something different; cascading is not on regular ASP.NET Page or not a simple web part. But it’s on a InfoPath form…..!  You will ask, what makes the difference?  I say, if the InfoPath is browser enabled, the filter option of the InfoPath won’t work or it won’t support.  Any how we developers have to accomplish this cascading task. Below, i have a scenario and its solution step by step.

Scenario:  I have two SharePoint lists “Categories “and “Products”. “Categories” SharePoint list have a column named “Category” and “Product” SharePoint list have 2 columns – Product and Category, out of which Category is a look up column from “Categories” SharePoint List. Now we have to develop a InfoPath form with 2 dropdowns, Categories and Products and we need to make it work in a cascading style. Means when the user selects a particular category on the Categories dropdown, related set of products should be populated on the Products dropdown. This is the scenario.

Solution: Follow the simple steps to accomplish this task.

  1. Open Microsoft InfoPath 2007 from Start à All Programs à Microsoft Office.
  2. Create a blank InfoPath form template using the option “Design a Form Template”. Don’t forget to check the option “Enable Browser Compatible Features” while creating the blank template.
  3. Now we have a blank InfoPath form in front of us. Drag and Drop two dropdowns from the toolbox and name them as Categories and Products.
  4. After step 3 , we need to populate the dropdowns with data. For that we need to create data connections with in the InfoPath form. “Categories” dropdown can be populated directly from the “Categories” SharePoint list. But Products dropdown can’t be populated from products SharePoint list, because its need to populated according to the selected category. In the next 2 steps we will create data connections for the dropdowns.
  5. In this step we will create data connection for the Categories dropdown. Select “Dataconnections… ” option from the “Tools” menu [menu available on the top portion] of the InfoPath form. From the “Dataconnections” window click add and on the DataConnection wizard select “Create new dataconnection” option with “Receive Data” Selection. On the “select the source of your data” step ,  go with the option “Sharepoint Library or List”. The coming steps of the wizard are self informative and proceed with selection of our Categories SharePoint List. Once we finish with the DataConnection wizard steps, Bind the created Categories dataconnection  with “Categories” Dropdown by right clicking on the control and from “Dropdown  list properties”  , select “Look up values from the external datasources” option. Now there will be a selection  with available dataconnections. Select our categories dataconnection and select category field  for  “Entries” option. Check on the InfoPath preview, whether data is populated correctly or not. So population of the  Categories dropdown is over.
  1. In this step we will create dataconnection for the Products dropdown. Here  we have to do some more work to create Products dataconnection. This is the portion we have to look on. Before going to create dataconnection for Products, we have to create a webservice that have function which return set  of  products according to the category passed. So, Create a WSPBuilder project and  add a Webservice item to the project  from WSPBuilder project templates or you can go with other webservice creation techniques and deploy it to the sharepoint site. Usually I create SharePoint components with the WSPBuilder . If it is with WSPBuilder, packaging and deployment is quite easy.

Give a user-friendly name to the webservice and in the code behind of the Webservice file add the following piece of code.

[WebMethod]
        public DataSet GetProducts(string Category)
        {

            DataSet dsProducts = new DataSet();
            DataTable dtProducts = new DataTable();
            DataColumn dcCategory = new DataColumn("Category");
            DataColumn dcProduct = new DataColumn("Product");
            dtProducts.Columns.Add(dcCategory);
            dtProducts.Columns.Add(dcProduct);

            SPSite site = SPContext.Current.Site;
            SPList list = site.OpenWeb().Lists["Products"];
            SPQuery query = new SPQuery();
            query.Query = @"<Where>
      <Eq>
         <FieldRef Name='Category' />
         <Value Type='Lookup'>"+ Category  +@"</Value>
      </Eq>
   </Where>";
            SPListItemCollection itemCol = list.GetItems(query);

            DataRow drCategory;
            foreach (SPListItem item in itemCol)
            {
                drCategory = dtProducts.NewRow();
                drCategory[dcCategory] = Convert.ToString(item["Category"]);
                drCategory[dcProduct] = Convert.ToString(item["Product"]);
                dtProducts.Rows.Add(drCategory);
            }

            dsProducts.Tables.Add(dtProducts);
            return dsProducts;
  }

This webservice method will return set of products for the given category. Build this project, build the WSP and deploy to the sharepoint site. After the deployment of the WSP , we can find the webservice in the _layouts virtual directory of the sharepoint site on the IIS. It will look like this http://localhost:5050/_layouts/CascadingDDLService.asmx .   Browse that .asmx  file and check whether  the “GetProducts” webservice method  is working on invoking. If it is working, we can proceed with it during the creation of “Products” dataconnection.

Now we can start creating dataconnection for Products. Follow the procedures mentioned on the step 5,till you reach “select the source of your data” step on the dataconnection wizard. On this step you have to select “Web service” option rather than “Sharepoint Library or List” option that we have taken on the step 5. After selecting  “Web Service” option , on this next step it will ask us to provide the webservice URL. Provide our webservice url that we have deployed before, it will give set of web- methods in the web service, in our case it will be only method ,“GetProducts”. Click next , it will ask for the  default parameter values and go on with the steps with clicking Next. But on the last step we have to consider one important thing , uncheck the option “Automatically retreive data when form is opened.” and click Finish to end dataconnection wizard.Now the Products dataconnection is created and we can bind this dataconnection to the Product dropdown list. Follow the same procedures mentioned on the step 5 to bind the dataconnection on the dropdown.

  1. Next step is to create the “Rules” for the Categories Dropdown. This step is very important for the cascading to work.
    • Right click on the Categories dropdown, select “Rules” option. From the rules window, click “Add” button to add a rule for the categories dropdown.
    • On the click of the “Add” button, you will see a window like this

Name the rule with a user-friendly name. Click on the “Set Condition” button and set a condition as per the below mentioned image.


We need to set the condition that Rule need to shoot when Categories is not blank.

    • After setting the Condition we can set the “Actions” for that rule.Here we need to set 3 actions. Click on the “Add Action” button to set an action.
    • In first action we will set the Products Field previously set value to Null. Select “Set a field’s value” from the action’s dropdown.For that select Products Field from main datasource and click OK without setting the value.

    • On the second action we need to set the Category parameter for the “GetProducts”  dataconnection, which is a secondary datasource. Select “Set a field’s value” from the action’s dropdown. In the Field section select Category parameter

and set its value to the Main datasource Category Field.

    • In the third action we will populate the “GetProducts” datasource . For that Select “Query using a dataconnection” from action’s dropdown and select “GetProducts” dataconnection from Data connection’s dropdown.

Finally the Rule window will be like this

Now save InfoPath Form and publish to any SharePoint site. Browse the InfoPath form from any of your browser, cascading of dropdown will work with charm…. :)

Posted in CodeProject, Sharepoint | Tagged: , , , , , , | 1 Comment »

Asynchronous Sharepoint List Insert / Update.

Posted by Abin Jaik Antony on April 25, 2010

Hello SharePoint developers… This time I have a new stuff to a share with you all. Two weeks back I met with one of my friends, who is also working as Software developer in SharePoint Technology. In between our talks he explained about a technical issue that he is facing in his project. The issue was regarding the use of AJAX in MOSS 2007. Actually his requirement is to update a SharePoint List asynchronously through a web part and he was using ASP.NET AJAX ScriptManager, UpdatePanel to accomplish this task. But it gives some cross browser issues, JavaScript issues like “ScriptResource.axd” file issue etc. I have also read that there are some issues of ASP.NET AJAX with MOSS 2007. Any how that night I also sat down along with him to find a solution. After a few trouble shooting and “googling” we come to a conclusion that it can’t be done with a small span of time. We started thinking for a new solution and into my mind it came like shooting star. “ICallbackEventHandler”…….. Yes, we started creating a new web part that implements the interface ICallbackEventHandler.

Here we can look into some small piece of code that explains “How to update a SharePoint List asynchronously using ICallbackEventHandler?”. This post assumes that readers have idea regarding the SharePoint Web Part development. Please go through the following steps to know how things are done.

This is simple example where we will add SP List Item to a SP List asynchronously through a Webpart.

1. Create a SharePoint Custom List having 2 columns [Name, Age] on your SharePoint Site.

2. Create a new SharePoint WSP Project from your Visual Studio IDE. [Please install WSPBuilder from CodePlex, if you don’t have a WSPBuilder Template ].

3. Add a Web Part Feature into the project from the “Add new Item” option on the created project.

4. Switch to the webpart code .cs file . This will be under the WebPartCode folder in the project, if we use the WSPBuilder Template.

5. Utilize the CreateChildControls() Method to develop the UI for the webpart with 2 Textboxes and a button. One textbox is for input value of the “Name” and other for “Age”. The button will be used to Submit the input values.The below mentioned will be the code inside the CreateChildControls() Method.

protected override void CreateChildControls()
        {
                try
                {
                    base.CreateChildControls();

                    txtName = new TextBox();
                    txtName.ID = "txtName";

                    txtAge = new TextBox();
                    txtAge.ID = "txtAge";

                    btnSubmit = new HtmlButton();
                    btnSubmit.ID = "btnSubmit";
                    btnSubmit.InnerText = "Submit";
                    btnSubmit.Attributes.Add("onclick", "javascript:CallServer2();");

                    Table tbl = new Table();
                    TableRow tr1 = new TableRow();
                    TableRow tr2 = new TableRow();
                    TableRow tr3 = new TableRow();

                    TableCell cell11 = new TableCell();
                    TableCell cell12 = new TableCell();
                    TableCell cell21 = new TableCell();
                    TableCell cell22 = new TableCell();
                    TableCell cell31 = new TableCell();
                    TableCell cell32 = new TableCell();

                    tr1.Cells.Add(cell11);
                    tr1.Cells.Add(cell12);
                    tr2.Cells.Add(cell21);
                    tr2.Cells.Add(cell22);
                    tr3.Cells.Add(cell31);
                    tr3.Cells.Add(cell32);

                    cell11.Text = "Name";
                    cell12.Controls.Add(txtName);

                    cell21.Text = "Age";
                    cell22.Controls.Add(txtAge);

                    cell32.Controls.Add(btnSubmit);

                    tbl.Rows.Add(tr1);
                    tbl.Rows.Add(tr2);
                    tbl.Rows.Add(tr3);

                    this.Controls.Add(tbl);

                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }

        }

6. Implement the ICallbackEventHandler interface to the webpart class. Implementation of this interface will add functions, 1. RaiseCallbackEvent 2. GetCallbackResult.

RaiseCallbackEvent – This function will be used to write code logic to update/insert the item to the Sharepoint List. This method have a parameter of type string which bring client side input data to the server side.

GetCallBackResult – This function is used to return the server side feedback to the client side as string.

Along with these 2 server side functionalities there are 2 client side JavaScript functions also needed for the orchestra. These Javascript functions are used to Call Server [here we will create JS function CallServer] functionalities from client side and for receiving the server feedback[JS function name will be ReceiveServerdata]. These JS functionalities need to register to Page Client Script block as follows.

protected override void OnLoad(EventArgs e)
        {

                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();

                    ClientScriptManager cm = Page.ClientScript;
                    String cbReference = cm.GetCallbackEventReference(this, "arg",
                        "ReceiveServerData", "");
                    String callbackScript = "function CallServer(arg, context) {" +
                        cbReference + "; }";
                    cm.RegisterClientScriptBlock(this.GetType(),
                        "CallServer", callbackScript, true);

                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }

        }

7. Also we need to write our own JavaScript function [SetInputValues]to create appended a global string variable with all input values delimited by semi colon “;”. This global string variable is passed through the CallServer JS Function to reach the server side.
To accomplish this client side functionalities cleaner we will create a JS Function CallServer2 to call previously mentioned CallServer JS function and SetInputValues JS function. This CallServer2 JS function will be called on the onclick of the submit button.

//global variable
            var inputValues;

            function SetInputValues()
            {

                inputValues='';
                var txtName = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtName');
                var txtAge = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtAge');

                var Name=txtName.value;
                var Age=txtAge.value;

                inputValues=Name+';'+Age;

            }
            function CallServer2()
            {
                SetInputValues();
                CallServer(inputValues,'');

            }

            function ReceiveServerData(arg, context)
            {
                        alert(arg);
            }

All these JS Functions will be written on the code file of the webpart as a string variable and these JS functions are registered to the page on the OnInit event.

private string jsString = @"
            //global variable
            var inputValues;

            function SetInputValues()
            {

                inputValues='';
                var txtName = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtName');
                var txtAge = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtAge');

                var Name=txtName.value;
                var Age=txtAge.value;

                inputValues=Name+';'+Age;

            }
            function CallServer2()
            {
                SetInputValues();
                CallServer(inputValues,'');

            }

            function ReceiveServerData(arg, context)
            {
                        alert(arg);
            }
           ";
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "callback", jsString, true);
        }

8. From the Server side we can take this input string[global variable “inputValues”] values through the previously mentioned RaiseCallbackEvent method’s parameter and we split this string with semicolon to get the array of input values to insert into the SP List.

 public void RaiseCallbackEvent(string eventArgument)
        {

            char[] delimiter = new char[1];
            delimiter[0] = Convert.ToChar(";");
            string[] inputData = new string[2];
            inputData = eventArgument.Split(delimiter);

            string siteUrl = "http://galaxian:5050/default.aspx";
            string libName = "NameList";
            // Open the site
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {

                    SPList list = web.Lists[libName];
                    SPListItem item = list.Items.Add();
                    item["Title"] = inputData[0];
                    item["Age"] = inputData[1];
                    item.Update();

                }
            }
        }

9. After the inserting the item we can intimate the client side using the GetCallbackResult() method

public string GetCallbackResult()
        {
            return "Data inserted successfully...!";
        }

This message will be displayed as a JS alert after the insertion of the data. This server side feedback will be received by the ReceiveServerData() JS Function as mentioned on the Step 7.

The whole Code file for the webpart will look as below.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;

namespace Asynchronous_SharepointListUpdate
{
    [Guid("6e22a748-4b74-481f-8b08-98106f869cf3")]
    public class Asynchronous_SPWebPart : Microsoft.SharePoint.WebPartPages.WebPart, ICallbackEventHandler
    {
        private bool _error = false;
        private string _myProperty = null;

        public Asynchronous_SPWebPart()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        TextBox txtName;
        TextBox txtAge;
        HtmlButton btnSubmit;

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
                try
                {
                    base.CreateChildControls();

                    txtName = new TextBox();
                    txtName.ID = "txtName";

                    txtAge = new TextBox();
                    txtAge.ID = "txtAge";

                    btnSubmit = new HtmlButton();
                    btnSubmit.ID = "btnSubmit";
                    btnSubmit.InnerText = "Submit";
                    btnSubmit.Attributes.Add("onclick", "javascript:CallServer2();");

                    Table tbl = new Table();
                    TableRow tr1 = new TableRow();
                    TableRow tr2 = new TableRow();
                    TableRow tr3 = new TableRow();

                    TableCell cell11 = new TableCell();
                    TableCell cell12 = new TableCell();
                    TableCell cell21 = new TableCell();
                    TableCell cell22 = new TableCell();
                    TableCell cell31 = new TableCell();
                    TableCell cell32 = new TableCell();

                    tr1.Cells.Add(cell11);
                    tr1.Cells.Add(cell12);
                    tr2.Cells.Add(cell21);
                    tr2.Cells.Add(cell22);
                    tr3.Cells.Add(cell31);
                    tr3.Cells.Add(cell32);

                    cell11.Text = "Name";
                    cell12.Controls.Add(txtName);

                    cell21.Text = "Age";
                    cell22.Controls.Add(txtAge);

                    cell32.Controls.Add(btnSubmit);

                    tbl.Rows.Add(tr1);
                    tbl.Rows.Add(tr2);
                    tbl.Rows.Add(tr3);

                    this.Controls.Add(tbl);

                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }

        }

        private string jsString = @"
            //global variable
            var inputValues;

            function SetInputValues()
            {

                inputValues='';
                var txtName = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtName');
                var txtAge = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtAge');

                var Name=txtName.value;
                var Age=txtAge.value;

                inputValues=Name+';'+Age;

            }
            function CallServer2()
            {
                SetInputValues();
                CallServer(inputValues,'');

            }

            function ReceiveServerData(arg, context)
            {
                        alert(arg);
            }
           ";
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "callback", jsString, true);
        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {

                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();

                    ClientScriptManager cm = Page.ClientScript;
                    String cbReference = cm.GetCallbackEventReference(this, "arg",
                        "ReceiveServerData", "");
                    String callbackScript = "function CallServer(arg, context) {" +
                        cbReference + "; }";
                    cm.RegisterClientScriptBlock(this.GetType(),
                        "CallServer", callbackScript, true);

                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }

        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }

        #region ICallbackEventHandler Members

        public string GetCallbackResult()
        {
            return "Data inserted successfully..!";
        }

        public void RaiseCallbackEvent(string eventArgument)
        {

            char[] delimiter = new char[1];
            delimiter[0] = Convert.ToChar(";");
            string[] inputData = new string[2];
            inputData = eventArgument.Split(delimiter);

            string siteUrl = "http://galaxian:5050/default.aspx";
            string libName = "NameList";
            // Open the site
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {

                    SPList list = web.Lists[libName];
                    SPListItem item = list.Items.Add();
                    item["Title"] = inputData[0];
                    item["Age"] = inputData[1];
                    item.Update();

                }
            }
        }

        #endregion
    }
}

This was the workaround that we have done for the asynchronous insert on the sharepoint list.

Hope you have enjoyed this post…Thanks for reading.

Posted in CodeProject, Sharepoint | Tagged: , , , , | 5 Comments »

GridView Pagination issue when dynamically added….!

Posted by Abin Jaik Antony on March 26, 2010

Hello ASP.NET Developers… Today I came across a small issue which killed large amount of my development time. The issue was a little tricky between the lines of code. I have an ASP.NET gridview which is dynamically (on the fly) created on my page. When I am inserting 2 lines of code  just for allowing the gridview pagination, code breaks at runtime giving  a NullReferenceException .

Cause of the issue :  i was adding the dynamically created  gridview(object) into page’s control collection after the databinding. This works fine if there is no pagination code added. But if there is code which allows pagination for the dynamically added gridview, this gridview should be added to the page’s control collection before the databinding.

Please see the below mentioned code blocks for the difference.

This piece of code will give the Null Reference Exception:

GridView gvDepartment = new GridView ();
gvDepartment.ID = "gvDepartment";

gvDepartment.AllowPaging = true;
gvDepartment.PageSize = 4;

gvDepartment.DataSource = GetDepartmentRows ();
gvDepartment.DataBind ();

this.form1.Controls.Add ( gvDepartment );

This is the perfect code:

        GridView gvDepartment = new GridView ();
        gvDepartment.ID = "gvDepartment";

        gvDepartment.AllowPaging = true;
        gvDepartment.PageSize = 4;

	/* Need to add gridview into controls collection before databind,if there is pagination */
        this.form1.Controls.Add ( gvDepartment );

        gvDepartment.DataSource = GetDepartmentRows ();
        gvDepartment.DataBind ();

NB: Obviously PageIndexChanging Event handling is needed. But this post is about the exception thrown while dynamically adding gridview. So the readers please keep in mind to add pageindexchanging event should be handled.
I hope this post helped you or given a nice thought. Thanks for reading.Please comment if you feel any issues on the same.

Posted in ASP.NET, CodeProject | Tagged: , , , , , , | 8 Comments »

How to send XML data to a Webpage using “POST” Method.

Posted by Abin Jaik Antony on March 16, 2010

Recently I came across an interesting requirement to send XML data to a particular URL using POST, means i need to post some XML data to a URL. I came to answer within a couple hrs of “googling” and R&D. Below mentioned is the sample code that I have created to explain the technique. Scenario defines here explains data sending between 2 websites, one is requestor website, which send xml POST data and other is responder website, which collect data from requestor website.

The step by step instructions are as follows.

  1. Open a Microsoft Visual Studio instance and from the file menu select the option to create ASP.NET website/web application. Create two websites using this option and name these websites with user-friendly names such as Requestor and Responder. For easier developer view make these websites under a single visual studio solution.
  2. By default there will be a default.aspx page inside each website. Just delete that page, we can create new pages for our sample
  3. Add a new page to the Requestor website. We can name this page as requestor.aspx. Our aim is to post XML data from requestor.aspx to the responder.aspx of the Responder website. Using the responder page we will save that XML data to a text (.txt) file. Add a new page to the Responder website name this page as requestor.aspx.
  4. Host Responder website on your local IIS.
  5. Select the Requestor website. Design the Requestor page as shown on the image below.

Page design of the Requestor page
One main Multiline textbox for XML Data, a Textbox for entering  URL to send the XML data and  a Button

6.Handle the click event of the button, add the following the piece of code to that event.

protected void btnPostXml_Click(object sender, EventArgs e)
{
        System.Net.WebRequest req = null;
        System.Net.WebResponse rsp = null;
        try
        {
            string uri = txtURI.Text;
            req = System.Net.WebRequest.Create ( uri );
            req.Method = "POST";
            req.ContentType = "text/xml";
            System.IO.StreamWriter writer = new System.IO.StreamWriter ( req.GetRequestStream () );
            writer.WriteLine (  txtXMLData.Text );
            writer.Close ();
            rsp = req.GetResponse ();
        }
        catch
        {
            throw;
        }
        finally
        {
            if (req != null) req.GetRequestStream ().Close ();
            if (rsp != null) rsp.GetResponseStream ().Close ();
        }
}

7.Select the Responder website. Take the Page Load event of the Responder.aspx page. Add the following piece of code to the Load event.

protected void Page_Load(object sender, EventArgs e)
    {
        Page.Response.ContentType = "text/xml";
        System.IO.StreamReader reader = new System.IO.StreamReader ( Page.Request.InputStream );
        String xmlData = reader.ReadToEnd ();
        System.IO.StreamWriter SW;
        SW = File.CreateText ( Server.MapPath(".")+@"\"+ Guid.NewGuid () + ".txt" );
        SW.WriteLine ( xmlData );
        SW.Close ();
    }

Here we are reading the stream of data from the page request and writing that data to a text file.
Note: On this sample i have made the ValidateRequest=”false” for the requestor to accept the XML Data on the form post.

This methodology can also be used as a CALLBACK to a URL with some data post.

Take the code sample(VS 2010 needed)

Thanks for reading this post. Please comment if you have any issues/doubt with the code.

Posted in ASP.NET, CodeProject, Technical Posts | Tagged: , , , , , , | 13 Comments »

 
Follow

Get every new post delivered to your Inbox.