Friday, 7 September 2012

Banding data form sharepoint list and library with using Group and fields into drop down in Infopath 2010

Please see the code


sing Microsoft.Office.InfoPath;
using System;
using System.Xml;
using System.Xml.XPath;
using Microsoft.SharePoint;

namespace SetValueToDropdownListInfoPathFromChoiceField
{
    public partial class FormCode
    {
        // NOTE: The following procedure is required by Microsoft InfoPath.
        // It can be modified using Microsoft InfoPath.
        public void InternalStartup()
        {
            EventManager.FormEvents.Loading += new LoadingEventHandler(FormEvents_Loading);
        }

        public void FormEvents_Loading(object sender, LoadingEventArgs e)
        {
            AddStatus();
        }

        public void AddStatus()
        {
            try
            {
                SPSite site = new SPSite("http://win-67038mbkel7");
                SPWeb web = site.OpenWeb();
                SPList list = web.Lists["Tasks"];
                SPFieldMultiChoice spFieldMultiChoice = (SPFieldMultiChoice)list.Fields["Status"];
                XPathNavigator nav = this.CreateNavigator().SelectSingleNode("/my:myFields/my:GroupStatus",
                    this.NamespaceManager);
                for (int item = 0; item < spFieldMultiChoice.Choices.Count; item++)
                {
                    XPathNavigator newNode = null;
                    newNode = nav.Clone();
                    newNode.SelectSingleNode("/my:myFields/my:GroupStatus/my:Displayname",
                        this.NamespaceManager).
                        SetValue(spFieldMultiChoice.Choices[item].ToString());
                    newNode.SelectSingleNode("/my:myFields/my:GroupStatus/my:Value",
                        this.NamespaceManager).
                        SetValue(spFieldMultiChoice.Choices[item].ToString());
                    nav.InsertAfter(newNode);
                    newNode = null;
                }
                nav.DeleteSelf();
                nav = null;
            }
            catch
            {

            }
        }
    }
}

Tuesday, 4 September 2012

Change View in InfoPath 2010 on Form load event using code

Following code is using infopath 2010 code behind.

public void FormEvents_Loading(object sender, LoadingEventArgs e)
{
    try
    {
        string view = "";
        if (e.InputParameters.ContainsKey("View"))
        {
            view = e.InputParameters["View"];
            e.SetDefaultView(view);
        }
    }
    catch (Exception ex)
    {
        SetValue("/my:myFields/my:FormSettings/my:ErrorLog", ex.Message + ex.StackTrace);
    }
}

Submit InfoPath 2010 Form without validation using code

Following code is using infopath 2010 code behind.

if (this.Errors.Count > 0)
DataConnection dcSave = this.DataConnections["SaveAsTemplate"];
this.Errors.DeleteAll(); 
dcSave.Execute();

Upload files using attachment control in infopath 2010 and file are saved in SharePoint 2010 Document Library using code -Submit Form using code

Following code is using infopath 2010 code behind.


  XPathNavigator attachmentNav = MainDataSource.CreateNavigator();
            // Get the base64 encoded attachment
            string attachedFile = attachmentNav.SelectSingleNode("/my:myFields/my:attachment", NamespaceManager).Value;
            attachmentNav = attachmentNav.SelectSingleNode("/my:myFields/my:attachment", NamespaceManager);
            // Delete the encoded file form XML form
            attachmentNav.InnerXml = string.Empty;
            // Get the value of "Title" field
            string reference = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txttitle", NamespaceManager).Value;
            // Convert the base64 encoded string into a byte array
            InfoPathAttachmentDecoder decoder = new InfoPathAttachmentDecoder(attachedFile);
            byte[] attachment = decoder.DecodedAttachment;
            string fileName = decoder.Filename;
            // Add the file as an attachment to the SharePoint list item
            using (SPSite site = SPContext.Current.Site)
            {
                if (site != null)
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        // Turn on AllowUnsafeUpdates on the site
                        web.AllowUnsafeUpdates = true;
                        // Add the attached document to "Documents" library
                        // and set the value of "Reference" column to
                        // "Title" filed of the InfoPath form
                        SPFolder lib = web.GetFolder("TestAttachmentdoc");
                        SPFile file = lib.Files.Add(fileName, attachment, true);
                        file.Item["Reference"] = reference;
                        file.Item["Title"] = fileName;
                        file.Item.Update();
                        file.Update();
                        // Add attachment file url to "Url" field in the form
                        // by adding extra "my:group4" element in the form
                        XmlDocument xdoc = new XmlDocument();
                        xdoc.LoadXml(MainDataSource.CreateNavigator().OuterXml);
                        Uri url = new Uri(new Uri(web.Url), file.Url);
                        XmlNode grp4 = xdoc.SelectSingleNode("/my:myFields/my:group1/my:group2", NamespaceManager);
                        XmlNode clonedNode = grp4.CloneNode(true);
                        clonedNode.SelectSingleNode("/my:myFields/my:group1/my:group2/my:url", NamespaceManager).InnerText = url.AbsoluteUri;
                        grp4.ParentNode.InsertAfter(clonedNode, grp4);
                        string formXml = xdoc.OuterXml;
                        // Add the form to "MyForms" library
                        SPFolder formlib = web.GetFolder("MyForms");
                        string formName = string.Format("Request {0}.xml", reference);
                        SPFile form = formlib.Files.Add(formName, Encoding.UTF8.GetBytes(formXml), true);
                        form.Item["Title"] = reference;
                        form.Item.Update();
                        form.Update();
                        // Turn off AllowUnsafeUpdates on the site
                        web.AllowUnsafeUpdates = false;
                        // Close the connection to the site
                        web.Close();
                    }
                    // Close the connection to the site collection
                    site.Close();
                }

How to count repeater table row in infopath 2010 using out of box

Following step are using infopath 2010

count(preceding-sibling::my:group10) + 1


- Just add one repeater table in infopath 2010.
- Add two columns  Field 1 and Field 2 in repeater table.
- Click right the field 1 column, then set default value (count(preceding-sibling::my:group10) + 1).
- Just check that and run.

How to insert hyperlink control in repeater table in repeater section in infopath 2010

Following code is using infopath 2010 code behind.


 




            XPathNavigator attachmentNav = MainDataSource.CreateNavigator();
            XPathNodeIterator rows1 = attachmentNav.Select("/my:myFields/my:group8/my:group9/my:group10", NamespaceManager);
            if (rows1.Count != 1)
            {
                string attachedFile = attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9[" + Convert.ToString(rows1.Count) + "]/my:attachment", NamespaceManager).Value;
                if (attachedFile != string.Empty)
                {
                    attachmentNav = attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9[" + Convert.ToString(rows1.Count) + "]/my:attachment", NamespaceManager);
                    // Convert the base64 encoded string into a byte array
                    InfoPathAttachmentDecoder decoder = new InfoPathAttachmentDecoder(attachedFile);
                    byte[] attachment = decoder.DecodedAttachment;
                    string fileName = decoder.Filename;
                    XmlDocument doc = new XmlDocument();
                    XmlNode group = doc.CreateElement("group11", NamespaceManager.LookupNamespace("my"));
                    XmlNode field = doc.CreateElement("url", NamespaceManager.LookupNamespace("my"));
                    XmlNode node = group.AppendChild(field);
                    node.InnerXml = fileName;
                    doc.AppendChild(group);
                    MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:group8/my:group9[" + Convert.ToString(rows1.Count) + "]/my:group10", NamespaceManager).AppendChild(doc.DocumentElement.CreateNavigator());
                    attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9[" + Convert.ToString(rows1.Count) + "]/my:attachment", NamespaceManager).SetValue("");
                }
            }
            else
            {
                string attachedFile = attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9/my:attachment", NamespaceManager).Value;
                if (attachedFile != string.Empty)
                {
                    attachmentNav = attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9/my:attachment", NamespaceManager);
                    // Convert the base64 encoded string into a byte array
                    InfoPathAttachmentDecoder decoder = new InfoPathAttachmentDecoder(attachedFile);
                    byte[] attachment = decoder.DecodedAttachment;
                    string fileName = decoder.Filename;

                    XmlDocument doc = new XmlDocument();
                    XmlNode group = doc.CreateElement("group11", NamespaceManager.LookupNamespace("my"));
                    XmlNode field = doc.CreateElement("url", NamespaceManager.LookupNamespace("my"));
                    XmlNode node = group.AppendChild(field);
                    node.InnerXml = fileName;
                    doc.AppendChild(group);
                    MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:group8/my:group9/my:group10", NamespaceManager).AppendChild(doc.DocumentElement.CreateNavigator());
                    attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9/my:attachment", NamespaceManager).SetValue("");
                }
            }

Monday, 27 August 2012

SharePoint 2010 - Introduction to Client Object Model

SharePoint 2010 - Introduction to Client Object Model


SharePoint 2010 provides a new client object model that enables you to create SharePoint solutions that run remotely from the SharePoint server farm. For example, the client object model enables you to consume and manipulate SharePoint data in Windows Forms applications, Windows Presentation Framework application, console applications, Silverlight applications, and ASP.NET Web applications. 

For working with client object model you need to get two master dlls:

·         Microsoft.SharePoint.Client.dll

·         Microsoft.SharePoint.Client.Runtime.dll



These dlls you can find under following path from machine on which you have installed SharePoint 2010.

Path to get DLL's: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI

The SharePoint Foundation 2010 managed client object model consists of two assemblies that contain five namespaces. If you look at the classes available in those namespaces, you see many classes. Primarily classes that have direct counterparts to some familiar classes in the SharePoint Foundation server object model.
 

1. Code snippets for How to Load List and List items:
public void LoadList()
        {
            using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
            {
                var web = ctx.Web;

               // Let's only work with the specific List object and save resources
                // by not fetching any other objects
                var list = ctx.Web.Lists.GetByTitle("ListName");
 
                // Load only the list variable and execute the query
                ctx.Load(list);
                ctx.ExecuteQuery();
 
                SP.CamlQuery camlQuery = new SP.CamlQuery();
                 camlQuery.ViewXml =
                            @"<View>
                        <Query>
                                  <Where>
                                <Eq>
                                  <FieldRef Name='Name'/>
                                  <Value Type='Text'>Shailesh</Value>
                                </Eq>
                                  </Where>
                        </Query>
                              </View>";
                SP.ListItemCollection listItems = list.GetItems(camlQuery);
                ctx.Load(listItems);
                ctx.ExecuteQuery();
 
                //Now you can iterate listitems collection and can get listitems using foreach loop
 
                foreach (SP.ListItem listItem in listItems)
                {
                            //you can get value of list column from listitem as follow:
                            //listitem["ID"]
                        //listitem["Name"]
                }
            }
        }
  2. Code snippets for How to insert  List items to a List:
public void SaveListItem()
        {
            using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
            {
                var web = ctx.Web;
                var list = ctx.Web.Lists.GetByTitle("ListName");
                ctx.Load(list);
                ctx.ExecuteQuery();
                SP.ListItemCreationInformation itemCreateInfo = new SP.ListItemCreationInformation();
                SP.ListItem listItem = list.AddItem(itemCreateInfo);
                listItem["Name"] = "Shailesh";
                listItem["Surname"] = "Soni";
                listItem.Update();
               ctx.ExecuteQuery();
            }
        }
  3. Code snippets for update List items in List:
Public  void UpdateListItem()
        {
            using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
            {
                var web = ctx.Web;

               // Let's only work with the specific List object and save resources
                // by not fetching any other objects
                var list = ctx.Web.Lists.GetByTitle("ListName");
 
                // Load only the list variable and execute the query
                ctx.Load(list);
                ctx.ExecuteQuery();
 
                SP.CamlQuery camlQuery = new SP.CamlQuery();
                 camlQuery.ViewXml =
                            @"<View>
                        <Query>
                                  <Where>
                                <Eq>
                                  <FieldRef Name='Name'/>
                                  <Value Type='Text'>Shailesh</Value>
                                </Eq>
                                  </Where>
                        </Query>
                              </View>";
                SP.ListItemCollection listItems = list.GetItems(camlQuery);
                ctx.Load(listItems);
                ctx.ExecuteQuery();
 
                //Now you can iterate listitems collection and can get listitems using foreach loop
 
                foreach (SP.ListItem listItem in listItems)
                {
                             listitem["Address"] = “blah blah blah”;
                            listitem.Update();
                }
                ctx.ExecuteQuery();
            }
        }
  4. Code snippets for delete List items in List:
Public  void DeleteListItem()
        {
            using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
            {
                var web = ctx.Web;

               // Let's only work with the specific List object and save resources
                // by not fetching any other objects
                var list = ctx.Web.Lists.GetByTitle("ListName");
 
                // Load only the list variable and execute the query
                ctx.Load(list);
                ctx.ExecuteQuery();
 
                SP.CamlQuery camlQuery = new SP.CamlQuery();
                 camlQuery.ViewXml =
                            @"<View>
                        <Query>
                                  <Where>
                                <Eq>
                                  <FieldRef Name='Name'/>
                                  <Value Type='Text'>Shailesh</Value>
                                </Eq>
                                  </Where>
                        </Query>
                              </View>";
                SP.ListItemCollection listItems = list.GetItems(camlQuery);
                ctx.Load(listItems);
                ctx.ExecuteQuery();
 
                //Now you can iterate listitems collection and can get listitems using foreach loop
                foreach (SP.ListItem listItem in listItems)
                            listItem.DeleteObject();
                ctx.ExecuteQuery();
            }
        }
 Conclusion: The above code snippets and detail description will help you to understand Client Object Model to begin with SharePoint 2010.