Wednesday, December 26, 2012

Simple binding in Silverlight datagrid

Here I created a class name "Friends" and initialize its objects in declarative manner with generic class to bind the Silverlight datacontrol datagrid. public class Friends
    {
 
        public string FirstName{get;set;}
        public string City {get;set;}
    }


in MainPage.xaml file drag and drop the "DataGrid" control in canvas area and now code looks like below



In MainPage.xaml.cs copy the code



  List list = new List()
            {
                new Friends{FirstName="Murugesan",City="NewYork"},
                new Friends{FirstName="NagaJothy",City="Kovil Patti"},
                new Friends{FirstName="TPK Senthilan",City="Chennai"}
             
            };
            dataGrid1.ItemsSource = list;

Tuesday, December 04, 2012

SharePoint 2013 - Hello World

SharePoint 2013 Now allows the developer to develop Visual WebPart as "Sandbox Solution" and Visual Studio 2012 help the beginner to identify the Sandbox and Farm solution artifacts.
Here is my first WebPart in SharePoint 2013.

When you installed the Visual Studio 2012,By default it doesn't have "SharePoint 2013 Project templates".
You need to run Web Installer to download the SharePoint 2013 developer tools from the MSDN.

Thursday, November 29, 2012

Windows Server 2012 - Domain controller

Today after many attempts yet tired less spirit  to make my Windows Server 2012 Server as "Domain Controller" for getting some experience in SharePoint 2013 , I made it. and it works like charm.



Tuesday, November 06, 2012

Gridview with checkbox

This code snippet will be used to find out the checked box's row  in ASP.NET GridView.



  for(int i = 0;i < grid.Rows.Count;i++)
            {
            CheckBox cb = (CheckBox)grd.Rows[i].FindControl("chkName");
if (cb.Checked)
{


                    b.Append(grid.Rows[i].Cells[1].Text.ToString()+",");
}
}
            Response.Write(b.ToString());

Friday, October 26, 2012

ADO.NET Entity Framework in WCF

Recently I have got an idea to implement the ADO.NET Entity Framework in SharePoint environment.
I need to workaround the thousand hundred of records to be searched,filtered and sorted.
Gone through the best practices and planning for dealing with huge data in MSDN and googled. Learner so many characteristics of  BCS and Excel Services in SharePoint.
But none of these approaches were not fit into my requirement. I decided to go with my own idea and implementation.
Frankly speaking, combining the WCF,ADO.NET EF and Hosting the WCF with ADO.NET EF in SharePoint is not simple things as I thought in ASP.NET and the guidelines for the same also verily limited in forums.

Most probably, My blog will be the first one to talk[with code implementation] about all technologies said above.

Soon I update the code snippets here..

Tuesday, October 09, 2012

SharePoint Client Side Object Model

Retrieving the SharePoint List Items through Client Side Object Model(CSOM).
Below link highlights the advantages of using the client side object model in SharePoint.
http://msdn.microsoft.com/en-us/library/ff798473.aspx

Simple start up :)
add references of these two assembly files to your SharePoint project

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll

both available on ISAPI folder of the 14 Hive.

3 columns in the SharePoint List has been mapped with one generic class.


namespace CSCOM
{
   public class ListClass
    {
       public string _id;
       public string _title;
       public DateTime _publishedDate;
       public string NewsID
       {
           set { _id= value; }
           get { return _id; }
     
       }
       public DateTime PublishedDate
       {
           set { _publishedDate = value; }
           get { return _publishedDate; }

       }
       public string NewsTitle
       {
           set {  _title = value ; }
           get { return _title; }
       }
       public ListClass()
       { }
       public ListClass(string _strId, DateTime _dtPublished, string _strNewTitle)
       {
         
            NewsID= _strId;
            NewsTitle = _strNewTitle;
            PublishedDate = _dtPublished;

       }
    }
}

Retrieving the ListItem via client side object model. You need to load the list and list collection object and execute the whole context.



 List cl = new List();
            ClientContext context = new ClientContext(Web.Url);
            List list = context.Web.Lists.GetByTitle("Your List Name");
             CamlQuery q = new CamlQuery();
            q.ViewXml="";
            Microsoft.SharePoint.Client.ListItemCollection cols = list.GetItems(q);
            context.Load(list);
            context.Load(cols);
            context.ExecuteQuery();
            DataTable table = new DataTable();
            table.Columns.Add("Id");
            table.Columns.Add("Title");
            table.Columns.Add("Date Published");
            foreach (Microsoft.SharePoint.Client.ListItem item in cols)
            {
           
                ListClass obj = new ListClass();
                obj.NewsID = item["ID"].ToString();
                obj.NewsTitle = item["Title"].ToString();
                obj.PublishedDate = Convert.ToDateTime(item["Date_x0020_Published"].ToString());
                cl.Add(obj);
            }
            GridView1.DataSource = cl;
            GridView1.DataBind();
         


          

Saturday, September 22, 2012

SharePoint 2010 Upgrade approach

I gathered notes from various resources and MSDN to understand better,learn and apply my knowledge on this topic.Here I placed very short description. My intention is this blog entry will help someone to spark the idea for their task.

There are two types of Upgrade approach from SharePoint 2007 to SharePoint 2010.



  • In-Place upgrade and
  • Content Database attach method

  • Consider this scenario,



  • Your SharePoint 2007 server or farm is a 32 bit based environment.
  • Your operation system Windows server 2000 or 2003 and SQLServer 2000 based 32 bit. based.


  • In these situation you cannot use the In-Place upgrade approach.

    So you need to upgrade your server or farm to support the 64 bit application then migrate your 32 bit SP 2007 to 64 bit application.

    Then you can start the actual In-Place upgrade. It requires lot of efforts and time consuming and costly process in term of upgrading the hardware and software.

    Simple approach for the above scenario is "Content Database attach" method. Before this your SQL Server meet the following requirement. It must be updated to SQL Server 2005 SP3 and the n Upgrade to SharePoint 2010 and move your content database to this new set up and connect this server to your SharePoint 2010 Farm.

    Tuesday, September 04, 2012

    Adding SPUser programmatically

    This few lines of code will be helpful for adding the SharePoint User or SharePoint Group through code. The string value for user id was given in excel format.My workaround was parsing the string in to token and identifying the user's windows log in id. Then inserting this value into people picker and updating the respective item. I have only one user to be added.If you have collection of users then you need to split the strings in comma delimiter and use the SPFieldUserValueCollection class.
     using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPUser userObj = SPContext.Current.Web.EnsureUser("Murugesan");
                        SPFieldUserValue userValue = new SPFieldUserValue(SPContext.Current.Web, userObj.LoginName);
                        SPList list = web.Lists["Project"];
                        SPListItem item = list.Items.Add();
                        item["Title"] = "Project-2";
                        item["Manager"] = userValue;
                        item.Update();
                    }
                }
    

    Sunday, September 02, 2012

    Split with multiple delimiter character

    Recently I have received an excel file in which one column formatted the AD users in "ID:FirstName,LastName". I need to split the string ID only from the above string.I spent couple of hours to do it generic collection / LinQ based.But finally I end up with the classic way of splitting the string. Here is my workaround.
    List list = new List();
    List list2 = new List();
    string input="MBUPN1:Murugesan,Pandian,MBUPN2:Murugesan,Pandian,MBUPN3:Murugesan,Pandian";
    string[] parts1 = input.Split(',');
    for (int str = 0; str < parts1.Length; str++)
    {
    if (parts1[str].Contains(":"))
    {
    list.Add(parts1[str]);
    }
    }
    foreach (string zz in list)
    {
    string[] len = zz.Split(':');
    list2.Add(len[0].ToString());
    }
    foreach (string K in list2)
    {
     Response.Write(K);
    }
        
    

    Thursday, August 16, 2012

    CustomAction Menu for Full Control permission

    This code snippet to helps you to understand "How to hide the Custom Action menu which placed under location of SharePoint Site Action menu". I have found so many workaround for this issue on forums but all dealing with Javascript to hide menu. Later I checked the MSDN notes on CustomAction feature,I came to know the attribute"Rights". This will check the currently logged in user's permission level on the site or list/document library accordingly it will display the menu. So I wanted to show the custom action menu only for those having "Full Control" access permission on the site or web.
    
    
      
        
      
    
    
    Again,I just redirect to application page from this custom action menu.On my page loading checking the user's permission on the site using below code.
    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            if (!web.DoesUserHavePermissions(web.CurrentUser.LoginName.ToString(), SPBasePermissions.FullMask))
                            {
                                lblPermissionLevel.Text = "You do not have permission to view this content";
    //WebPart's unique Id                            
    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            if (!web.DoesUserHavePermissions(web.CurrentUser.LoginName.ToString(), SPBasePermissions.FullMask))
                            {
                                lblPermissionLevel.Text = "You do not have permission to view this content";
    //WebPart's guid                            
    g_0114039b_aaed_49ae_bc9f_479a130c68dc.Visible = false;
                                g_9c0f6d83_fbb9_441d_a0fd_43a266e68657.Visible = false;
    
                            }
                        }
                    }
                            }
                        }
                    }
    
    Both codes are equivalent to each other both inheriting the SPBasePermission class.

    Tuesday, August 14, 2012

    Custom Approval Workflow in SharePoint

    Download code from here

    This workflow was created for beginner those wanted to learn the custom workflow in SharePoint from very scratch level.

    Even I have created many complex workflows for my work in the past,I feel its time to introspect my knowledge on this simple workflow.

    As I follow the many instruction those available in forums and blogs,I end up with confusion and if I wanted to apply my own business requirement out of this instruction,it was very tedious.

    So here is the simplified version of my "Custom Approval Workflow in SharePoint using Visual Studio 2010".

    Debugging is always enlighten you to apply and learn the secret of the workflow engine. Create a blank SharePoint project and add the new item from project template "Sequential Workflow".

    On this design surface add the activities just like you seen here.

    The workflow engine manage the following activities such as "Creating task and assigning to someone,after the task has been assigned to someone monitoring the status of Tasks(approved or rejected) and completing the task. Many times I was confused and identified the reason for it,assigning the correlation and Task Properties and Task id via "Property Window". Of course this will be useful for advanced developer[I personally feel those knows all properties of the task and workflow and how to apply these to their business requirement]. For simplicity I am going to create all properties behind the code and assigning to design surface. Required properties here I have created so far globally.
            public Guid TaskID = Guid.NewGuid();
            public SPWorkflowTaskProperties taskProp = new SPWorkflowTaskProperties();
            public SPWorkflowTaskProperties afterProp = new SPWorkflowTaskProperties();
            public SPWorkflowTaskProperties beforeProp = new SPWorkflowTaskProperties();
            public bool isComplete = false;
    // This is nothing but "Task ContentType's" field "Status" GUID.
    //You can find it by debugging the code line,You can find all field's guid and its value.
    //HashTable tbl = afterProp.ExtendedProperites;
            public Guid idStatus = new Guid("c15b34c3-ce7d-490a-b133-3f4de8801b76");
    
    
    Now we need to assign these properties to design workface.Once you created all these properties on code behind,you can see like this
    Important tips to remember: Correlation token for task activities must be same throughout the workflow. So I am renaming the correlation token for my "CreateTask1" as taskToken. Assigning the Owner Activity to "Workflow1" just like below screenshot.
    follow the same to all activities "OnTaskChanged1" and "CompleteTask". Secondly,We need to assign the unique GUID for task this one also common for all activities. Right click on CreateTask1 activities -> Properties and choose the "Task Id" click on the button and choose our own created "TaskID" for the task id. like shown here. And do the same for "Task Properties" too.
    Here I am creating a method called "createTaskAndAssign".
    private void createTaskAndAssign(object sender, EventArgs e)
            {
    
                taskProp.Title = "Type the title";
    //Later you can try the dynamic title text may be workflow item's title using workflowproperties.
                taskProp.AssignedTo = "local\\administrator";
                taskProp.Description = "Please review";
                taskProp.DueDate = DateTime.Now.AddDays(2);
    
            }
    
    Assign the above method to "MethodInvoking" properties of the "Create Task1" activity. For whileActivity you can manage your condition using "Code Declaration" or "Declarative Rule Condition. I have used "Code condition" you just need to assign the method name[CheckTaskStatus]to "Code Condition properties of "While Activity".
    private void CheckTaskStatus(object sender, ConditionalEventArgs e)
            {
                e.Result = !isComplete; //When true - workflow ends up.
            }
    
    
    Created a method for "OnTaskChange1" activity and assigned the same as did for while activity. This method will check the task content type's task status field value by using the task class's "ExtendedProperties".
     private void onTaskChangedInvoked(object sender, ExternalDataEventArgs e)
            {
                string tbl = afterProp.ExtendedProperties[idStatus].ToString();
                if (tbl.Equals("Completed"))
                {
                    isComplete = true;
                }
                else
                {
                    isComplete = false;
                }
    
            }
    
    As soon as the boolean value set to true,the workflow calls the "Complete Task" activity and ends up its cycle. To test this demonstration on your development server,create two user for your sharepoint site and assign the task for them. And log in as different user by using new user check the "Task" list on their log do approve or reject and see the workflow status.

    Friday, July 13, 2012

    Visual Studi0 2012-RC - SharePoint

    My first experience with Visual Studio 2012 RC.I found interesting changes for SharePoint Development project types which will helpful for freshers to differentiate the Farm/Sandbox solution and stuffs.

    Wednesday, July 04, 2012

    WebPart in Application page

    I spent couple of hours to learn how to place the visual webpart in an application page(layout) in sharepoint 2010. Initially I thought it would be very simple like placing the asp.net user control in a webpage.But its not after many attempts made,I learned and would like to share step by step. Step:1 Register the assembly which had reference of namespace and webpart's class below to your page directive.
    
    <%@ Register TagPrefix="MyControl" Namespace="SP.Murugesan.AutoCleanupExtender" Assembly="SP.Murugesan, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bc4aab377305c5bf"%>
    
    
    Next step is the real sharepoint approach to place the webpart in application page. You must reference the GUID of your webpart using "__WebPartId" attribute. I used the SharePoint Designer to get the WebPart's GUID.I created on webpart page via SPD 2010 and scan the code view to find my webpart's reference. Step:2
    
    
    
    

    Friday, June 29, 2012

    Workflow Association Auto cleanup

    Recently I have a requirement to keep the workflow history details. First I had doubt to use the "AutoCleanUp" properties of the "WorkflowAssociations" class.Because the document library was attached to an out of box workflow - SharePoint Approval Workflow."

    To confirm this doubt I have created the new document library and attached to out of box workflow.My workflow's unique name was "DemoWF". Couple of year before I have done this to my custom workflow which was created through Visual Studio.

    After this workaround,I made sure it can be work for OOTB workflow too.

    Created a visual webpart to get all the workflow association to this document library.I am able to get my workflow's by default auto clean up days 60.

    Now I set the "AutoCleanup" value as per my desire.

    On my page,I have created UI to load all List type templates to see the workflow association associated in them.
    if (!Page.IsPostBack)
                {
                    SPSite site = SPContext.Current.Site;
                    SPWeb web = SPContext.Current.Web;
                    SPListCollection collection = web.Lists;
    
                    foreach (SPList list in collection)
                    {
                        if (list.BaseType == SPBaseType.DocumentLibrary)
                        {
                            SPDocumentLibrary docLib = (SPDocumentLibrary)list;
    
                            if (!docLib.IsCatalog && docLib.BaseTemplate != SPListTemplateType.XMLForm)
                            {
                                ddlList.Items.Add(docLib.Title.ToString());
                            }
                        }
    
    
                    }
                }
    
    On selected Index change value of my loaded lists/document library,wire up with events to know the specific workflows for the list or document library,
     protected void ddlList_SelectedIndexChanged1(object sender, EventArgs e)
            {
                ListBox1.Items.Clear();
                ListBox1.Items.Insert(0, "--Select--");
                SPSite site = SPContext.Current.Site;
                SPWeb web = SPContext.Current.Web;
                SPList docLib = (SPDocumentLibrary)web.Lists[ddlList.SelectedItem.Text];
    
                SPWorkflowAssociationCollection cols = docLib.WorkflowAssociations;
                if (cols.Count > 0)
                {
                    foreach (SPWorkflowAssociation wfa in docLib.WorkflowAssociations)
                    {
                        ListBox1.Items.Add(wfa.Name);
                       //Loads the worflow names in the given list box.  
                                        
                       
                    }
    
                }
                
            }
    
    when you select the specific workflow name from the list box,It will shows you the default or extended auto clean up day in the literal control.
     protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
                SPSite site = SPContext.Current.Site;
                SPWeb web = SPContext.Current.Web;
                SPList docLib = (SPDocumentLibrary)web.Lists[ddlList.SelectedItem.Text];
                string workflowName = String.Empty;
                SPWorkflowAssociationCollection cols = docLib.WorkflowAssociations;
                foreach (SPWorkflowAssociation wfa in docLib.WorkflowAssociations)
                {
                    if (wfa.Name.Equals(ListBox1.SelectedItem.Text))
                    {
                        Literal1.Text = "AutoCleanup for this workflow : " + wfa.AutoCleanupDays.ToString();
                    }
                }
            }
    
    OnClick event of the button will simply extend the AutoCleanUp duration of the specific workflow's association. So the Workflow History and Task history will be longer as you extended here.
    protected void btnExtend_Click(object sender, EventArgs e)
            {
                SPSite site = SPContext.Current.Site;
                SPWeb web = SPContext.Current.Web;
                
                SPList docLib = (SPDocumentLibrary)web.Lists[ddlList.SelectedItem.Text];
                string workflowName = String.Empty;
          
                    foreach (SPWorkflowAssociation wfa in docLib.WorkflowAssociations)
                    {
                        workflowName = wfa.Name;
                        
                        if (workflowName ==ListBox1.SelectedItem.Text)
                        {
                         
                        wfa.AutoCleanupDays=Convert.ToInt32(TextBox1.Text.ToString());
                        docLib.WorkflowAssociations.Update(wfa);
                        }
                      
               
                    }
                 
                    
            }
    

    Thursday, May 24, 2012

    Customising exception with SPException class

    I found this approach for handling the excepting in SharePoint 2010 is an elegant way. I simply pass the System Exception to SPException class and retrieved the exception details. Previously I have used the using operator to suppress the exception and clean carbage collection on my coding. But there were plenty of situation to capture the error and log into the database or system file. Here I have used to log the error details with inputs and result in the SharePoint List. I need to check this code and refine using "SPDisposeChecker tool".
    protected void Button1_Click(object sender, EventArgs e)
            {
                if (!String.IsNullOrEmpty(TextBox1.Text) && !String.IsNullOrEmpty(TextBox2.Text))
                {
                    int a = Convert.ToInt32(TextBox1.Text);
                    int b = Convert.ToInt32(TextBox2.Text);
                    SPSite site=null;
                    SPWeb web=null;
                    SPList list=null;
                    SPListItem item=null;
    
                    try
                    {
    
                        site = SPContext.Current.Site;
                        web = site.OpenWeb();
                        list = web.Lists["Calc"];
                        item = list.Items.Add();
                        item["A"] = a;
                        item["B"] = b;
                        Label1.Text = (a / b).ToString();
                        item.Update();
    
                    }
    
                    catch (Exception ex)
                    {
                        SPException ex1 = new SPException(ex.Message, ex);
    
                        item["A"] = a;
                        item["B"] = b;
                        item["Result"] = ex1.Message;
                        item.Update();
                    }
    
                }
            }
    

    Monday, May 21, 2012

    Generating ics file from sharepoint calendar

    This code will generate the outlook's meeting file format.ics file. This codes were written for the scenario where the meeting will be announced in SharePoint Calendar with EventID and the column named Meeting Attendees [People Picker with multiple values] to capture the acknowledgement of the end user. Every time user generate the ics file,their details will be logged into different List. This will also address the how to insert the SPUser value into SPUserFieldValueCollection and SPFieldUserValue programmatically in People Picker control.
     using (SPSite site = SPContext.Current.Site)
                    {
                          StringBuilder sb = new StringBuilder();
            
                        using (SPWeb web = site.OpenWeb())
                        {
    
                            SPList list = web.Lists["Calendar"];
                            string _CamlQuery = "" + Convert.ToInt32(Request.QueryString["EventID"].ToString()) + "";
                            SPQuery query = new SPQuery();
                            query.Query = _CamlQuery;
                            DataTable dt = list.GetItems(query).GetDataTable();
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                lblEventId.Text = dt.Rows[i]["EventID"].ToString();
                                lblTitle.Text = dt.Rows[i]["Title"].ToString();
                                lblDescription.Text = dt.Rows[i]["Description"].ToString();
                                lblStart.Text = dt.Rows[i]["EventDate"].ToString();
                                lblEnd.Text = dt.Rows[i]["EndDate"].ToString();
                                lblLocation.Text = dt.Rows[i]["Location"].ToString();
                            }
    
                            DateTime start = Convert.ToDateTime(lblStart.Text);
                            DateTime end = Convert.ToDateTime(lblEnd.Text);
                            sb.Append("BEGIN:VCALENDAR"); sb.Append(",");
                            sb.Append("PRODID:-");
                            sb.Append("VERSION:1.0"); sb.Append(",");
                            sb.Append("BEGIN:VEVENT"); sb.Append(",");
                            sb.Append(start.ToString("yyyyMMdd\\THHmmss\\Z")); sb.Append(",");
                            sb.Append(end.ToString("yyyyMMdd\\THHmmss\\Z")); sb.Append(",");
                            sb.Append("LOCATION:" + lblLocation.Text); sb.Append(",");
                            sb.Append("CATEGORIES:Meeting"); sb.Append(",");
                            sb.Append("DESCRIPTION:" + lblDescription.Text); sb.Append(",");
                            sb.Append("meeting=0D=0A"); sb.Append(",");
                            sb.Append("SUMMARY:" + lblTitle.Text); sb.Append(",");
                            sb.Append("PRIORITY:3"); sb.Append(",");
                            sb.Append("END:VEVENT"); sb.Append(",");
                            sb.Append("END:VCALENDAR");
                            string[] contents = sb.ToString().Split(',');
                            File.WriteAllLines("C:\\windows\\Temp\\" + lblTitle.Text.ToString() + ".ics", contents);
                        }
    
                    }
    

    Tuesday, May 08, 2012

    Sorting Attached files in SharePoint List Item

    Recently I have a requirement to sort the attached files those attached into SharePoint List Item. I have an application page to retrieve these collection of files by passing the item's id in page "Bulletted List" control has been used and set the property as hyper link.

    Uploading the attachment into this Item also done through SharePoint Object Model.It's simply works fine on retrieving and showing them in ASP.NET's bulleted control.Later out business requirement got changed.They wanted these attached files were sequentially ordered and displayed so.

    I tried many approaches to sort these files using Generic Classes in C# . I found lot of useful methods using LinQ,SortedList,KeyValuePair,Dictionary and SortedDictionary.But I need to implement in ASP.NET 2.0 only.

    Still I found no luck :)- on my sorting tasks on attached files.But the development environment is verily limited to ASP.NET 2.0. Couple of day later,I started to think of actual index in attachment collection in sharepoint list item. When I checked the item and its view mode.I found all of the attached files were randomly ordered still I could not pin point in what basis these were ordered.

    Sorting based on "File Info" ???.

    On Checking on SPAttachmentCollection class I found its just name of the attached files array not even the file object.So I get the URL for each of this files and assigned to SPFile.

    Now I have "TimeCreated" property of this SPFile.I pass these file names and its time of creation into Dictionary class to sorting. Interesting Dictionary class can only sorting the collection of items by "Key" not as value.But I need to sorting by value "TimeCreated". But If I wanted to sorting based on "TimeCreated" property,every time an end user need to create new file and upload.If they upload old files it won't make any sense and won't be end user friendly.

    So I need to check alternate way of sorting this files.May be I need to use ICollection class to sort the attachment collection.

    Anyhow ASP.NET 3.5 enables this task very simple by few lines of code.

     SPSite site = SPContext.Current.Site;
                SPWeb web = site.OpenWeb();
                SPList list = web.Lists["Friends"];
                SPListItem item = list.GetItemById(1);
                Dictionarydictionary = new Dictionary();
                SPAttachmentCollection attachments = item.Attachments;
    
                foreach (string fileName in attachments)
                {
                    SPFile file = web.GetFile(attachments.UrlPrefix + fileName);
                    dictionary.Add(file.Name.ToString(), file.TimeCreated);
                }
                 List> sorted = (from sp in dictionary orderby sp.Value select sp).ToList();
                ListBox1.DataSource = sorted;
                ListBox1.DataBind();
                ListBox1.DataSource = sorted;
                ListBox1.DataBind();
    

    Monday, May 07, 2012

    current user in sharepoint

    Trimmed lines of code to get the currently logged in user details in SharePoint
     public SPUser GetCurrentUser()
            {
                var context = SPContext.Current;
                SPWeb web = context.Web;
                return web.CurrentUser;
            }
    
    
    After you getting the SPUser object you can retrieve the login name,email,first name and last name of this user.

    Thursday, April 19, 2012

    VHD conversion to VMWare Image

    Recently I wanted to install the SharePoint 2010 IW Hyper-V Image.I have downloaded the full software packed vhd format from the Microsoft site to be used on my Windows 2008 R2 trial version installed desktop. I wanted this package on my laptop too.Installed Windows 7 32bit OS. Initially I thought this will be easy to convert the .vhd file into VMWare image file format.vmdk.But later there I need to download the converter tool from VMWare site.It was about 108MB in size.After downloading this file I started to convert. You must have your Virtual Server is ON from this it will created the VMWare supporting format.Even one of my colleague tried to convert the "Remote Server" as vmdk format.It showed the dialog which says this tool must be installed on Remote server too. For security reason,We could not do this. After so long search,I found the simple and powerful tool "WinImage". Learn more about this tool from this link .vhd to vmdk Converter

    Wednesday, April 18, 2012

    Taxonomy Simple talk

    Taxonomy in SharePoint 2010 is a new topic to organize and index the contents based on certain hierarchical group based. Put it in simple word,How the supermarket organizing the products categorically to easy access by the customers. By categorize the products by apartment wise,floor wise and rack wise. In SharePoint provide this logical approach by using the "Managed Metadata Services". SP object model gives the hierarchical view of the terms such as Session,Store,Group,TermSet and Terms. On site capacity plan,Let assume we have a site for Tax Managing department for a corporate.Every time the users from the tax department uploads the document for collaborate and process for taxation,they needed a reliable mechanism to manage them in organized manner. Suppose they wanted to search document,they can easily do it by supplying the keywords like "Sales tax 2011".Search will quickly returns the document. Even though there were types of law related document stored in document library,It simply returns the relevant document. So the term or keyword "Sales tax 2011" will be stored as Term in Managed Metadata service.We consume this from our site by placing the new column type "Managed Metadata". Like taxonomy we have another fancy word folksonomy.This is nothing but user generated keywords when they uploading the document or record to be identified quickly.Example "Tag clouds". Lastly,Taxonomy is nothing but "Classifying the information[contents] through hierarchical based approach".

    Saturday, April 14, 2012

    WCF Hosting in SharePoint environment

    Creating the WCF service and consuming in SharePoint application is now improved.Later version we need to create the WCF service and hosting it in IIS server as stand alone application. From this we need to create the "Proxy Class" using the tool wsdl or svcutility to be used on client application. But this approach will not be so user friendly when it comes to SharePoint. Again the hosting endpoint is the static one. Maintainability and back up of the webapplication or service application in SharePoint is must not be complex. Recent improvement has been done in WCF using Factory method.This will get rid of the static end point problem.It automatically set the dynamic end point in run time. Create the SharePoint empty project. Select the "SharePoint Mapped" folder. Under ISAPI folder you'll the folder.Inside this folder create the "text file or xml file". Copy the below line in to this txt or xml file.
    <%@ServiceHost Language="C#" Debug="true"
        Service="WCFHosting.Layouts.WCFHosting.ListService, $SharePoint.Project.AssemblyFullName$"
        Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressBasicHttpBindingServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    
    Rename this file's extension as .svc Under the same folder create the code file type "Interface" and implement all the methods on the same file. For simplicity I created the below class
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Runtime.Serialization;
    using Microsoft.SharePoint.Client.Services;
    using System.ServiceModel.Activation;
    
    namespace WCFHosting.Layouts.WCFHosting
    {
        [ServiceContract]
        interface ServiceInterface
        {
            [OperationContract]
            List GetAllRecords();
        }
        [BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
        public class ListService:ServiceInterface
        {
            
            public List GetAllRecords()
            {
                List obj = new List();
                SPListRecord record = new SPListRecord();
                record.title = "SP"; record.name = "Pandian"; record.city= "Mumbai";
                obj.Add(record);
                return obj;
               
            }
        }
    }
    public class SPListRecord
    {
        public string title{get;set;}
        public string city {get;set;}
        public string name{get;set;}
    
    }
    
    Now we need to do important step to enable dynamic endpoint by sharepoint. Now right click on your "Project" and choose the "Unload project".Edit the Project file(.csproj). Inside the PropertyGroup place this tag
        svc
    
    Now reload your WCF project,rebuild and deploy it. Now we have the full pledged and SharePoint compatible WCF service and it can be host anywhere in the Farm and it can be consumed in Application Page,Visual WebPart and InfoPath forms.

    Wednesday, April 11, 2012

    REST Web Service in InfoPath 2010

    This blog will be underline the verily basic step needed to consume the REST Web service in Info Path 2010. Here I have created the WCF Service using Factory method.There will not be the endpoint config entries.I just removed all the config entries in this WCF application. On service file(.svc) used the Factory="System.ServiceModel.Activation.WebServiceHostFactory" in the markup view. Download the Microsoft.Http.dll and Microsoft.Http.Extension.dll from the Microsoft site. I have two method to retrieve the single record and one is for multiple records. WCF interface implementation code
    sing System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using Microsoft.Http;
    using System.ServiceModel.Web;
    using System.Text;
    
    namespace RestWCF
    {
       
        [ServiceContract]
        public interface RestWCFInfoPathCalculator
        {
    
           
            [OperationContract(Name = "SomeValue")]
            [WebGet(UriTemplate = "/GetAllDetails")]
            List GetAllDetails();
    
            [OperationContract(Name = "GetBillValueByInv")]
            [WebGet(UriTemplate = "/GetBillValue")]
            BillDetails GetBillValueByInv();
            
        }
        [DataContract]
        public class BillDetails
        {
            [DataMember]
            public string InvoiceNumber;
            [DataMember]
            public double InvoiceAmount;
            [DataMember]
            public DateTime InvoiceDate;
        }
      
    }
    
    Interface code implementation
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    
    namespace RestWCF
    {
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
        public class Service1 : RestWCFInfoPathCalculator
        {
           
           public BillDetails GetBillValueByInv()
            {
               return GetAllDetails().FirstOrDefault(c => c.InvoiceNumber == "2");
          
            }
           public List GetAllDetails()
           {
               List list = new List();
               list.Add(new BillDetails { InvoiceNumber = "2", InvoiceDate = Convert.ToDateTime("12/03/2012"), InvoiceAmount = 34343.45 });
               list.Add(new BillDetails { InvoiceNumber = "3", InvoiceDate = Convert.ToDateTime("08/03/2012"), InvoiceAmount = 6457.7 });
               return list;
               }
        }
    }
    
    
    Host this WCF service in IIS.Video to help you on this [http://www.youtube.com/watch?v=iptFJaeJ-F0] Now open your InfoPath Designer 2010 - > select the "Blank" form template On Ribbon select the "Data" tab and click on "Data Connection" follow the screenshot.
    Infopath Output.

    Monday, April 09, 2012

    Where is the love for InfoPath

    One of the best blog over the Info path and its development aspects,I came across this blog. where-is-the-love-for-infopath It almost speak the real time development issues by most of the MVPs and not just pros and cons some of the blog entry those without going actual experimental. An year ago,I was part of the team to develop the complex custom workflow using visual studio.At initial point we used the merely "approve/reject" option.Later the requirement need to incorporate to capture the "Life Cycle" of multiple workflow those are attached into document library,and wanted to use "Managed Meta Data" on all the user's comment and ratings over the document. we shocked and stalled whether these are possible in Info Path. Moreover,Configuring the info path for client side also is not easiest one.Every time we ended up with strange error. Some point,we could not identify the actual errors on Logs either Windows Event log. Cost issue also raised on that time,Client was very conscious on budget at one point they are not ready to go single license to adopt the Info Path strategy. So we withdrawn the Info Path form development and put placed Custom ASPX form with all requirement that almost replicate the info path's layout/rules/action and enhanced rich features on the "Approval/Reject Form". But I still love the info path where you don't need high complex business logic to be applied and ready to limiting the features to adopt Info Path.

    Sunday, April 08, 2012

    Spicy matter

    Now i am wainting to board spicejet from madurai to mumbai.
    I am very fond of spicy masala from my wife's hometown.Here in Mumbai I used to put the readily available and packaged masala on mutton.I end up unsatisfactory dinner.This time,my wife prepared the handmade and exactly mixature of the masala.Actually i forgot and boarded the bus to airport. when computer scanned my bag,I was told to come otherside to openup the bag.First moment I really shocked and security cop asked me "what  was inside my package". I simply replied
    a couple of SharePoint related books and an book titled Cloud computing on SharePoint.He again insisted me that I had any food items to have on board.I smiled at him and continue my coversion with him in Hindi.
    I remembered after Few minutes thai i had 2 packages of coriander powder and red chilli powder.Despite I aware of these stuffs are not allowed pn board ,i simply forgot.They cancelled my boarding pass and asked me to put my bag in luckage and made new boarding pass.Today this flight was late by one hour.:)-

    Saturday, April 07, 2012

    SharePoint content databases

    configuration db:
    This db contains informations about the sharepoint databases,iis websites and web applications,trusted solutions,web part packages,site templates and farm settings of sharepoint farm settings.This must be reside on where the Central Administration content database residing.This is read-heavy database once production begins.

    Content db:
    this contains all of the site contents like lists,libraries,properties of webparts,audit logs,user names and their rightes on the site.It can contain multiple sites or single site.If single database larger than microsoft recommended limitaion 200GB then storage must be carefully consider.Sql enterprise edition's table partioning could be used.Part of databases can be reside different RAID array.

    Property
    Crawl
    Search Administration
    Web analytics reporting
    Web analytics staging
    Profile
    Synchronization
    Usage
    Business  connectivity Database
    Application Registry
    Subscription settings
    Social tagging
    Secure store
    Word automation services AND performance point.

    Wednesday, April 04, 2012

    Outlook appointment using EWS API

    Recently I developed the small utility to send the outlook based appointment invitation using Exchange Web Service Managed API. You need to download the file "EwsManagedApi.msi"[786KB] from this link EWS Managed API download link Add the Microsoft.Exchange.WebServices.dll to your project and include the namespace Microsoft.Exchange.WebService.Data Always exchange server protected through SSL,you need to validate the certificate for trusted relationship with your client application.
            ExchangeService service = new ExchangeService();
            service.Credentials = new WebCredentials("UserName", "Passw0$rd", "Domain");
            service.Url = new Uri("https://owa.yourDomain/EWS/Exchange.asmx");
    
            System.Net.ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
            //Response.Write(service.RequestedServerVersion);
            Appointment appointment = new Appointment(service);
            appointment.Subject = "EWS Managed API hooked";
            appointment.Body = "Discuss over Exchange Web Service API";
            appointment.Start = new DateTime(2012, 7, 20, 10, 00, 00);
            appointment.End = appointment.Start.AddHours(1);
            appointment.RequiredAttendees.Add("emailID");
          
    
    When I am adding this Web Service URL to my visual studio project,It required my login credentials for this domain.Interesting point I've found on this,my client certificate got expired.To suppress this I simply change boolean value on the CertificateValidationCallback method. First moment I am not aware of my WebService URL.I put the debug mode on Autodiscover method,It listing out my webservice URL for the Exchange Server 2010.
    Validating the X509 certificate
    private static bool CertificateValidationCallBack(
            object sender,
            System.Security.Cryptography.X509Certificates.X509Certificate certificate,
            System.Security.Cryptography.X509Certificates.X509Chain chain,
            System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
            {
                return true;
            }
    
            // If there are errors in the certificate chain, look at each error to determine the cause.
            if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            {
                if (chain != null && chain.ChainStatus != null)
                {
                    foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
                    {
                        if ((certificate.Subject == certificate.Issuer) &&
                           (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
                        {
                            // Self-signed certificates with an untrusted root are valid. 
                            continue;
                        }
                        else
                        {
                            if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                            {
                                // If there are any other errors in the certificate chain, the certificate is invalid,
                                // so the method returns false.
                                return true;
                            }
                        }
                    }
                }
    
                // When processing reaches this line, the only errors in the certificate chain are 
                // untrusted root errors for self-signed certificates. These certificates are valid
                // for default Exchange server installations, so return true.
                return true;
            }
            else
            {
                // In all other cases, return false.
                return false;
            }
        }
    
    Few line of codes really useful for certain situation. The one EmailMessage class is the simplest and hassle free when comparing with System.Net.WebMail and SMTP configuration based email.
       //EmailMessage message = new EmailMessage(service);
            //message.Subject = "EWS Managed API";
            //message.Body = "The proposition has been considered.";
            //message.ToRecipients.Add("email Address");
            //message.SendAndSaveCopy();
    
            //Response.Write("Sent");
    

    Sunday, April 01, 2012

    Nintex First WorkFlow

    To download the Nintex Workflow 2010 you must provide your web email address,they will not accept if you provide any of the public email address such as Yahoo,gmail and hotmail. You will get the download link along with .nlf file which is mandatory to activate the product. After downloading this .msi file and installed,You need to deploy the solutions nintexlivecore.wsp and nintexworkflow2010.wsp through your Central Administration. Apart from these you need to configure the mandatory settings like "Content Database,managed allow path,and webapplication activation. I made it a very simple Approval workflow and found lot of features those are not available in SharePoint 2010 out of box workflow. "Delegating the task to someone" is a really nice feature in Nintex workflow.Later I will explore all the enchanced features in this workflow.
    Leave approval Process workflow.

    Thursday, March 29, 2012

    SharePoint Farm types

    Small Farm : One DB server and WFE and combination of Application Server.WFE and Application services both residing in the same server. Medium Farm : It consists of a DB Server,an WFE and Application Server. Extended Medium : Same as medium farm but with extra one DB server. Large Farm : Atleast 2 DB server and consists of several WFE and Application Servers.

    SSL setting up for sharePoint site

    The best illustrated article over "How to configure the sharepoint site using SSL Certificates"despite How to configure the same,I learned few new things on this topic. Have a look around this link SSL-HTTPS protocol settings for SharePoint Site

    Tuesday, March 20, 2012

    Wednesday, March 14, 2012

    SharePoint 2010 Administration exam guide

    While preparing for the exam 70-668 SharePoint Administration I found these resourceful links from Microsoft. SharePoint Administration exam preparence guide. Getting started with business intelligence in SharePoint Server 2010 Server and server farm administration (SharePoint Server 2010) Security and protection for SharePoint Server 2010 You need to login using hotmail/live id. Almost its covering all the topics.I would suggest to go with your Service application configuration and how its functional architecture.Despite I have passed in Application Development and Configure in sharepoint 2010,I personally feel there are so many things in SharePoint 2010 to learn. I learned lot of useful tips while preparing for this exam.Hopefully I will get good mark in this exam too. But I clearly made my mind not to use anyother source to update my knowledge on Administration exam except the above link.

    Thursday, March 08, 2012

    Installing SharePoint 2010 Windows 7

    Failed to create the configuration database An exception of type System.IO.FileNotFoundException was thrown When you installing the SharePoint 2010 on Windows 7,you might get these error.You need to install the "Windows Identity Foundation" to resolve this problem. Download Link http://support.microsoft.com/kb/974405 After continouing you might get this error to
    To resolve this problem,you need to install the Microsoft Chart Control to support the SP Enterprise edition. Download link http://www.microsoft.com/download/en/details.aspx?id=14422 After you install all these,still if you get error while opening the site in first time ensure your activated the WCF HttpActivation by running the below script.
    start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;^
    IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;^
    IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;^
    IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-HealthAndDiagnostics;^
    IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-ManagementScriptingTools;^
    IIS-Security;IIS-BasicAuthentication;IIS-WindowsAuthentication;IIS-DigestAuthentication;^
    IIS-RequestFiltering;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;^
    IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-IIS6ManagementCompatibility;^
    IIS-Metabase;IIS-WMICompatibility;WAS-WindowsActivationService;WAS-ProcessModel;^
    WAS-NetFxEnvironment;WAS-ConfigurationAPI;WCF-HTTP-Activation;^
    WCF-NonHTTP-Activation
    

    Thursday, March 01, 2012

    Script CSS registration in SharePoint

    Today I spent couple of my valuable hours to get to know more about control and in SharePoint. When you set the "Localize" parameter of the above control "false",you need to keep all your "javascript or CSS files" under 1033 folder of 14 hive.Even I tried my luck on useing $SPUrl on these control and set te value ~SiteCollection. In my sitecollection I put all my css and js file.Still I could not able to get the things works for me. Later,I attach these branding related stuffs in my Custome Solution Package.(.wsp) Then reference the javascript file So I ignore the parameter Localize,otherwise my page will not be used the javascript.Instead it will check files inside 1033.

    Saturday, February 25, 2012

    Corrupted Web Config in Sharepoint 2010

    One of my dearest friend who is working for reputed corporate in Dubai called me this morning in verily panic toned. He narrated the story of how he ended up the whole SharePoint site's web config file got corrupted. He was helpless since 3 days of this incident.While he was working on the Server got power failure. After couple of hours,He checked the SharePoint Site it shows the IIS Error Page.
    Initially I thought some of the .dll files reference must be added into the web config file.Because lot of third party applications were running on his server. I was shocked when he narrated his next explanation.He checked the web.config file on his default site.There were entries like random number as we seen in the movie "Matrix".:)- Quickly I could not think what could be possibilities those made this file corrupted.
    Its really very strange error I encountered in my SharePoint developer career,Even I could not create some key words for search to this scenario. Some times before,I had as usual habit of clean up the temp files in windows,Log files in SP 2010 and .bak files in WebApplication. This time I wanted to check the .bak files those were created by system randomly for each web application in SharePoint on their virtual directories of the site. Again,I admit never tried to see what contents were inside of this .bak file.I disconnected my remote session and check my local computer's .bak file on my specific site. Whoops..! its just replica of your actual web.config of the Site. Logged back to his server.Scrutinize the timestamps of his all .bak file of his corrupted site. Simply opened this latest.bak file and copied its xml entries into new web.config file.Replaced with the corrupted web.config. Site got restored !..

    Friday, February 24, 2012

    Syntax Highlighter for code posting

    $(document).ready(function() {
     alert('I am using Prettify as Syntax Highlighter');
    });
    

    Tuesday, February 21, 2012

    Office Web Apps - Services for SharePoint Farm

    Office Web Apps is an online version of Microsoft Word, Excel, PowerPoint and OneNote allowing users to access these applications and their respective documents from any Internet connection and using all browser.You can deploy Office Web Apps onto your SharePoint farm providing your users with the same functionality as the online version of Office Web Apps. Deploying Office Web Apps on your SharePoint farms will add the following service applications Word Viewing Service Application Excel Calculation Service PowerPoint Service Application

    Thursday, February 16, 2012

    SharePoint Subsite as Template

    You will not find the link to save the site as template(.wsp) for your sub site. To get this done, use this link http://rootsite/subsite/_layouts/savetmpl.aspx You must be the site administrator to do this job.