Tuesday, November 26, 2013

Lync presence indicator in SharePoint webpart

Recently I have searched alot almost nearly 3 hours to work around to "Show Lync presence" in my SharePoint webPart or Application page.

Out of this search,quickly I come up with simple yet more robust way of binding the Lync indicator.

There will not be mess javascript or wiring up the server object model code the html markup.

Simply I retrieved the collection of SPUser object and bind them to entity class and then to Gridview.

Snippet


 <asp:TemplateField HeaderText="User Name">
                        <ItemTemplate>
                            <img alt="presence status" border="0" height="15" width="15" src="/_layouts/images/imnhdr.gif" onload="IMNRC('<%#Eval("EmailId") %>')" ShowOfflinePawn="1" id="<%#Eval("SysId") %>"  />
                            <asp:Label runat="server" id="lableUser" Text='<%#Eval("UserName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>


Code behind to retrieve the SPUser from the SPGroup


   private List<Users> GetAllUsersFromGroup()
        {
            SPSite site = null;
            SPWeb web = null;
            var list = new List<Users>();
            Users objName = null;
            try
            {
 
 
                site = new SPSite(SPContext.Current.Site.Url);
                string w = SPContext.Current.Web.ServerRelativeUrl;
                web = site.AllWebs[w.ToString()];
                list.AddRange(from SPGroup @group in web.Groups
                              let currentUserRole = web.RoleAssignments.GetAssignmentByPrincipal(@group)
                              from SPRoleDefinition role in currentUserRole.RoleDefinitionBindings
                              from SPUser user in @group.Users
                              select new Users
                              {
                                  UserName = user.Name,
                                  UserLogin = user.LoginName,
                                  PermissionType = role.Name,
                                  SysId = user.Sid,
                                  EmailId = user.Email,
                                  GroupName = currentUserRole.Member.Name,
 
                              });
 
            }
            catch (Exception exception)
            {
                throw new SPException(exception.Message.ToString());
            }
            return list;
        }

Thursday, November 21, 2013

Farm PropertyBag in SharePoint

Creating and Configuring the Farm level property enable the Farm administrator to control the configuration settings on Site / Web level. He can expose the some of the general values such as variable,connection strings and etc..to all the server available in Farm. To use SPFarm class include the "SharePoint.Administration" namespace in your code. SPFarm class will not work unless you connected to at least one Physical server. In the VM which is cloned or mimic from the actual server,you cannot execute this class based code in your solution. Secondly,your current application pool account and Farm account must be same otherwise you'll get the "Access Denied or Unauthorized exception even though you used "RunWithElevated Privilege" delegation. You can identify what account being used by your Farm,by navigating to your "Central Administration Page",->Security header under,Click on "Configure Service Account". Select the "Farm account from the drop down list->It will shows the account which is used by your Farm.
 protected void Page_Load(object sender, EventArgs e)
        {
            SPSecurity.CodeToRunElevated code = new SPSecurity.CodeToRunElevated(UpdateMyKey);
            code.Invoke();
            
        }
        public void UpdateMyKey()
        {
            SPWeb web = SPContext.Current.Web;
            web.AllowUnsafeUpdates = true;
            SPFarm farm = SPFarm.Local;
            farm.Properties.Add("MyKey1", "MyValue");
            farm.Update();
            web.AllowUnsafeUpdates = false;
        }

//Retrieve the Farm Value in your Site/Sub Site Level.
        public void GetValue(Object sender,EventArgs e)
        {
            SPFarm farm = SPFarm.Local;
            String propertyValue = farm.Properties["MyKey1"].ToString();
            Response.Write(propertyValue);

        }

Friday, November 15, 2013

Reading File contents in SharePoint programmatically

Line of code to perform reading the XML contents from the SharePoint file and converting the XML String to DataSet.
SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                   SPSite site = null;
                   SPWeb web = null;
                    site = new SPSite((SPContext.Current.Site.Url));
                   web = site.OpenWeb();
                   var file = web.GetFile("Shared%20Documents/temp.xml");
                  string fileUrl = SPContext.Current.Web.Url + "/Shared%20Documents/temp.xml";
                  byte[] binFile = file.OpenBinary();
                  Stream stream = new MemoryStream(binFile);
                  DataSet ds = new DataSet();
                  ds.ReadXml(stream);
                   spItems.DataSource = ds.Tables[0];
                   spItems.DataBind();
                });

Saturday, October 12, 2013

List Item Attachments in Gridview

This code snippet for showing the SharePoint List Item's attachment collection in a ASP.NET. Build your ASP.NET grid view with columns and a Link to delete the selected rows value. Here I am listing out the few files and wanted to allow the user to delete the file by clicking the link. Here is code to retrieve the selected row index and its cell value.
 public void LinkAction(object sender, EventArgs e)
        {


            LinkButton lnkbtn = sender as LinkButton;
            GridViewRow selectedRow = lnkbtn.NamingContainer as GridViewRow;

            int a = selectedRow.RowIndex;
            string txt = selectedRow.Cells[2].Text.ToString();
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    var list = web.Lists["Region"];
                    web.AllowUnsafeUpdates = true;
                    SPFolder folder = web.Folders["Lists"].SubFolders[list.Title].SubFolders["Attachments"].SubFolders["5"];
                    SPFile file = web.GetFile(web.Url +"/"+folder+"/" + txt);
                    file.Delete();
                    web.Update();
                    web.AllowUnsafeUpdates = false;
                }

            }
  
Grid View Markup










Binding the Grid view with List Item's attachments.
    public List GetAttachments()
        {
            List fNAme = new List();
            
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        string sp = string.Empty;
                        var list = web.Lists["Region"];
                        SPListItem item = list.GetItemById(5);
                        SPAttachmentCollection cols = item.Attachments;
                        SPFolder folder = web.Folders["Lists"].SubFolders[list.Title].SubFolders["Attachments"].SubFolders[item.ID.ToString()];
                        FileDetails f = null;
                        foreach (SPFile file in folder.Files)
                        {
                            f = new FileDetails();
                            f.fName = file.Name;
                            f.fUrl = web.Url + "/" + folder.ToString() + "/" + file.Name;
                            fNAme.Add(f);

                        }

                    }

                }
            
            return fNAme;
        }
For Getter and Setter and FileDetails Class code available on my previous post.

Tuesday, October 08, 2013

How to differentiate User and Group in People Editor Control

Here is an simple workaround on " How to differentiate the SPUser and SPGroup from the People Editor Control selection " in SharePoint.


public void ParseUserAndGroup(object sender, EventArgs e)
        {
            List userList = new List();
            List groupList = new List();

            string value = myppl.CommaSeparatedAccounts;
            string[] values = value.Split(',');

            foreach (string s in values)
            {
               if(SPUtility.IsLoginValid(SPContext.Current.Site,s))
               {
                    SPUser user = SPContext.Current.Web.EnsureUser(s);
                    userList.Add(user);
               }
               else
               {
                    SPGroup oGroup = SPContext.Current.Web.SiteGroups[s];
                   groupList.Add(oGroup);
               }

              }

                grdGroup.DataSource = groupList;
                grdGroup.DataBind();
                grdUser.DataSource = userList;
                grdUser.DataBind();
            }

        }

Monday, October 07, 2013

Item Level Permission in SharePoint

Item level permission will be set after that item has been created or updated. When you set item level permission on updating the item you need to remove all the permission and then update the custom permission on the clean slate. Its always best to wire up the permission on the item on "List Item Event Receiver". Code snippet for adding new item level permission
                    var list = webSite.Lists["Region"];
                    SPListItem item = list.Items.GetItemById(4);
                    webSite.AllowUnsafeUpdates = true;
                    SPUser user = webSite.EnsureUser(@"Global\dhanyata");
                    item.BreakRoleInheritance(false);
                    SPRoleDefinitionCollection roleDef = webSite.RoleDefinitions;
                    SPRoleAssignment roleAssignment= new SPRoleAssignment(user);
                    roleAssignment.RoleDefinitionBindings.Add(roleDef["MyCustomPermission"]);
                    item.RoleAssignments.Add(roleAssignment);
                    item.Update();   
            
I have created the custom permission level to be set on item. IF you want to create this programmatically,you can choose to work SPBasePermission class and then assigning to your user or group.

Tuesday, September 17, 2013

Retrieving attachments in SharePoint list Item

Retrieving the SharePoint List Item through OM model requires little tweaked. So you will get the meta data of your attached files in the specific Item. Code goes here.I am trying to retrieve the attached files from the First Item in the List.
public List GetAttachments(int itemId)
        {
            List fNAme = new List();
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    string sp = string.Empty;
                    var list = web.Lists["Case List"];
                    SPListItem item = list.GetItemById(1);
                    SPAttachmentCollection cols = item.Attachments;
                    SPFolder folder = web.Folders["Lists"].SubFolders[list.Title].SubFolders["Attachments"].SubFolders[item.ID.ToString()];
                    FileDetails f = null;
                    foreach (SPFile file in folder.Files)
                    {
                        f = new FileDetails();
                        f.FileName = file.Name;
                        f.FUrl = web.Url + file.ServerRelativeUrl;
                        SPUser user = file.ModifiedBy;
                        f.ModifiedBy = user.Name;
                        f.FVersion = file.MajorVersion.ToString();
                        f.fIcon = file.IconUrl;
                        fNAme.Add(f);
                    }

                }

            }
            return fNAme;
        }
       
Get and Set class for the File Details
public class FileDetails
    {
       public string FileName { get; set; }
       public string ModifiedBy { get; set; }
       public string FUrl { get; set; }
       public string FVersion { get; set; }
       public string fIcon { get; set; }
    }

Tuesday, September 10, 2013

DataTable to CSV generator

This code will generate the .csv (Comma separator file) from the Data source like DataTable or XML strings.
    protected void CreateCSV(object sender,EventArgs e)
        {
            MemoryStream ms = new MemoryStream();
            DataSet ds = new DataSet();
            ds.ReadXml(@"d:\students.xml");
            if (ds.Tables[0].Rows.Count > 0)
            {
                StreamWriter writer = new StreamWriter(ms);
                writer.AutoFlush = true;

                foreach (DataColumn column in ds.Tables[0].Columns)
                {
                    writer.Write(column.ColumnName.ToString() + ",");
                }
                writer.WriteLine();

                foreach (DataRow drow in ds.Tables[0].Rows)
                {
                      writer.Write(drow["Name"].ToString() + "," + Convert.ToDateTime(drow["DOJ"]).ToShortDateString().ToString() + "," + drow["Height"].ToString() + ",");
                      writer.WriteLine();
                }
            }
            using (FileStream file = new FileStream("D:\\file5.csv", FileMode.Create, FileAccess.Write))
            {
                
                ms.WriteTo(file);
            }
        }
Sample XML file to work on the above solution.


Murugesan
12/12/2013
155.57845645


Murugesan
12/12/2013
155.57845645


Amit Ingle
05/04/2013
155.57845645


Monday, September 02, 2013

Removing SPWeb Property Value

Removing the Property Bag in the SharePoint 2010 is just little bit tricky.When I started to update the SPWeb object's property's properties.Remove and Update won't work. You need to set your Property Bag's value null before remove and update method called. Another important point is you have to call the remove method of AllProperties collection of SPWeb Object in SharePoint Object Model. It was different when I tested it with Power Shell Script in there I don't want to set the value null. Adding value to Property bag
web.Properties.Add("SomeValue", "900");
web.Properties.Update();
web.Update();
Removing the value and PropertyBag from the SPWeb's PropertyCollection.
web.Properties["SomeValue"] = null; // This is mandatory
web.Properties.Update();
web.AllProperties.Remove("SomeValue");
web.Properties.Update();
Its something like we can't remove the directory from the DOS command until we delete all of its files.

Monday, August 12, 2013

Moving the Files in SharePoint

I am trying to achieve the file or files from the Shared Document library to one of my target list item's folder.
You can use this code where you want to attach the files to List Item on run time.

Get the Item's ID by passing into GetItemById method of the Items collection to get the specific Item and its attachment folder then execute the

The below code is just a rough workaround.You need to check the Item's existence before execute code on it.


SPListItem mYItem = list.Items.GetItemById(aB);
 SPFile file = mYItem.File;
var exactUrl = mYItem.Attachments.UrlPrefix;
 file.MoveTo(exactUrl + file.Name, SPMoveOperations.Overwrite, false);


       

         

Friday, August 09, 2013

Multiple document upload link not visible

Recently I have updated my Windows 2008 R2 SP1 from Windows 2008 R2 for reinstall the SharePoint 2013 on my computer.

I have installed all the trial office products except Microsoft Office.When I am trying to work on Shared Document library,I have noticed the strange in "Multiple File Upload" application page.

Updated my IE 8 to IE 10.I didn't find the link but this time I have notice that link in blink mode and then Off.
Then I tested the same page in "Chrome" still there is no link visible for multiple file upload.

Then Installed Office,I tried to open the Shared Document library this time,my Internet Explorer pop up the window to add "Office Document Cache Handler".I added this "Add-On".
Now I am able to see the "Multiple File Upload & Drag and Drop" window in Shared Document library.



Thursday, August 08, 2013

Finding ListItem Id in ItemAdding event

Recently I wanted to work on the scenario where I wanted to find the "ListItem" Id in SharePoint list while "ItemAdding" event.

Its something like generating the auto Id or unique list Item id to be used in the custom application page.(.ASPX)
I googled and binged and I was informed  the stories which telling me "You can't be get ListItem Id on synchronous event,other message goes like "You can get null value or index value 0.

So my tendency is not allowing me the things goes off just like that . I spent few minutes to get the logic involved in the situation  to find the answer on my own.

In an half hour of time spent on this , I came up with the solution which will work on to finding the "ListItem Id" in ItemAdding event as well as when you delete the record from the List,
still you'll get the unique list Item id.

Simple thoughts on it,

Step 1: ( put logic in synchronous event receiver)

  1. Get the all rows in the SPListItemCollection (Assign to DataTable)
  2. Loop all Rows in the DataTable
  3. Add the rows which sharing the name "ID" into Generic List.
  4. Find the Max value in Generic list
  5.  Save this max value in PropertyBag
  6. Retrieve Property Bag value in your application page.
  7. Last but not least -> Add value +1 to your retrieved PropertyBag Value to predict the new ListItemId.

List arr = new List();
You have to update the PropertyBag in every event of the receiver to get updated value from the SharePoint List.

 public override void ItemAdded(SPItemEventProperties properties)
       {
           SPWeb web = properties.Web;
           SPSecurity.RunWithElevatedPrivileges(delegate()
           {
                
                   SPList list = properties.List;
                   DataTable cols = list.Items.GetDataTable();
                   //int MaxVal =  Convert.ToInt32(cols.Compute("max(ID)", String.Empty));
                   if (cols.Rows.Count > 0)
                   {
                       foreach (DataRow row in cols.Rows)
                       {
                           arr.Add(Convert.ToInt32(row["ID"]));
                       }
                   }
                   var c1 = arr.Max();
                   properties.Web.Properties["UniqueVal"] = c1.ToString();
                   properties.Web.Properties.Update();
                   web.Update();
 
           });
       }
 public override void ItemDeleted(SPItemEventProperties properties)
       {
           int deletedId = properties.ListItemId;
           SPList list = properties.List;
           DataTable cols = list.Items.GetDataTable();
           int MaxVal =  Convert.ToInt32(cols.Compute("max(ID)", String.Empty));

           if (deletedId == MaxVal)
           {
               properties.Web.Properties["UniqueVal"] = Convert.ToInt32(deletedId).ToString();
           }
          

       }       

Monday, July 29, 2013

Not valid state of the object

Error occurred in deployment step 'Activate Features':Operation is not valid due current state of the object.

If you receive this error while developing the "Sandbox" solution in SharePoint 2010 using Visual studio 2010.

The reason will be:
You might have trying to change the Sharepoint's solution type "sandbox to Farm" by setting the attribute in VSS 2010.

or SPUserWorkerProcess not been started on your WFE or error occurred in deployment steps.

To resolve this,

Go to your Solution gallery in the Site collection,if you found the solution deactivate it.

Or
Go back to your Visual studio solution explorer and empty all your features (select all features hit the delete button,it will goes to your right hand side of the feature window.)
Now change the solution type to "Farm or Sandbox". Last but not least, Check your event receiver class and its namespace are correctly referred in "Element.xml".

Or,

trying to call the SPSite/SPWeb class in the feature using SPContext. or trying to access the object thats all ready closed by using "using operator" in feature event receiver.

Sunday, July 21, 2013

Single Key with multiple Values in C#

This a simple assumption work around to find the solution for how to retrieve the multiple values through Single Key. NamedValueCollection class in linq comes in handy for me. Helpful link from MSDN NameValueCollection This was very useful when an Library list having many books authored by different authors Just consider a situation you wanted to send an email notification to each individual authors the ratings received from the readers.For this aggregate all of his book details. You need to group the books by grouping authors.Assumption book details from the MSDN. Download from here Book.xml On click of the Button "ReadXmlRecord" method will be called.Read the XML file as DataTable and iterate all the rows with your entity class to apply NameValueCollection for further sorting and filtering. After grouping the record in SharePoint List.

    public void ReadXmlRecord(object sender, EventArgs e)
        {
            BookWithAuthor objBook = null;
            DataSet ds = new DataSet();
            ds.ReadXml(@"D:\books.xml");
            var BookTab = ds.Tables[0];
            NameValueCollection values = new NameValueCollection();
            foreach (DataRow row in BookTab.Rows)
            {
                objBook  = new BookWithAuthor();
                objBook.Author = row["author"].ToString();
                objBook BookTitle = row["title"].ToString();
                cols.Add(objBook.Author, objBook.BookTitle);
                
            }
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    foreach (String value in values.AllKeys)
                    {
                        SPList list = web.Lists["SiteReminder"];
                        SPListItem item = list.Items.Add();
                        web.AllowUnsafeUpdates = true;
                        item["SiteOwner"] = value;
                        item["SiteDetails"] = values[value];
                        item.Update();
                        web.AllowUnsafeUpdates = true;
                    }
                }
            }
            
        }
Class
public class BookWithAuthor
    {
        public string Author { get; set; }
        public string BookTitle { get; set; }
    }
Before grouping the record in Gridview,

Wednesday, July 10, 2013

Object Instantiation in Javascript

May be its simple post.But its big enough to differentiate the object and variable in javascript.

var someVariable = "Some text";
var someOtherVariable = ["Name1","Name2","Name"];

The above lines are just variable declaration with keyword "var".
In javascript,Object Instantiation also can be done in the same fashion but with curly  open and closed braces {}.

Example:
var mYObject = {
                 Name:"Murugesa Pandian"; 
                 WhoIsHe:function() { return "Working as Programmer";}
                }


Now mYObject is an Object which holds the property or attribute or you may be call "Member" ,Name and method(function) WhoIsHe.

Call it as
document.write(mYObject.Name);
document.write(myObject.WhoIsHe());

Monday, June 03, 2013

Saturday, June 01, 2013

I Try until I Pass

Its unfortunate for me today, I failed in the Microsoft SharePoint Exam 70-576 and reached 639 out of passing score 700.
But I am really happy and satisfied for my devotion and dutiful for the preparation.
Almost I learnt many features of SharePoint 2010 and I will apply the new logic in my new development of SharePoint application and enhancement in existing application.

Next week,I am planing to try my next shot..Hopefully and positively I will pass.

Saturday, April 20, 2013

Adding term in TermSet SharePoint

This code will be useful for understanding on how to add the "Term" into TermSet through programmatically. First create your new Metadata service and associate them in to site collection. This picture will explain the hierarchy of the taxonomy in SharePoint 2010 and SharePoint 2013.
I am trying to add the new term to termset called "Food"

                TaxonomySession session = new TaxonomySession(SPContext.Current.Site);
                TermStore store = session.TermStores[0];
                Group group = store.Groups[0];
                TermSet set = group.TermSets[1];
                set.CreateTerm("Vada Payasam", 1033);
                store.CommitAll();
            

Friday, April 19, 2013

SPFieldUrl adding to contenttype

This code snippet may be simple but I spent couple of hours to get things done.On my searching I learned the difference between SPFieldUrlValue,SPFieldType.URL and SPFieldLink. Simply,I wanted to add the "HyperLink" column to my existing ContentType.
                SPWeb web = SPContext.Current.Web;
                SPContentTypeId cId = new SPContentTypeId("0x0100AF98B284ECB44322916F1A1AD1A9E31C");
                SPContentType cType = new SPContentType(cId, web.ContentTypes, "MurugesanCType");
                web.Fields.Add("T2", SPFieldType.URL, true);
                SPField f = web.Fields["T2"];
                f.Description = "Type your Org NAme";
                web.ContentTypes[cId].FieldLinks.Add(new SPFieldLink(f));
                web.ContentTypes[cId].Update();

Monday, April 15, 2013

Adding Taxonomy Field to Content Type

    
            SPWeb web = SPContext.Current.Web;
            SPContentTypeId cId = new SPContentTypeId("0x0100AF98B284ECB44322916F1A1AD1A9E31C");
            SPContentType cType = new SPContentType(cId, web.ContentTypes, "MurugesanCType");
            web.ContentTypes.Add(cType);
            Guid termSetId;
            TaxonomySession session = new TaxonomySession(SPContext.Current.Site);
            TermStore store = session.TermStores[0];
            Group group = store.Groups[1];
            TermSetCollection tCols = group.TermSets;
            foreach (TermSet set in tCols)
            {
              if(set.Name.ToString().Equals("Role"))
              {
                 termSetId = set.Id;
                 TaxonomyField tField = web.Fields.CreateNewField("TaxonomyFieldType", "Profile Role") as TaxonomyField;
                 tField.SspId = set.TermStore.Id;
                  tField.TermSetId = termSetId;
                  tField.TargetTemplate=string.Empty;
                  tField.AllowMultipleValues=false;
                  tField.CreateValuesInEditForm=true;
                  tField.Open=true;
                  tField.AnchorId=Guid.Empty;
                  tField.Group = "Meta Data - Custom";
                  web.Fields.Add(tField);
                  SPField spField = web.Fields["Profile Role"];
                  web.ContentTypes[cId].FieldLinks.Add(new SPFieldLink(spField));
                  web.ContentTypes[cId].Update();
                
              }
            }
            Web.Update();

Sunday, March 31, 2013

ObservableCollection in ASP.NET

This simple example will help you to understand and how to use the "ObservableCollection" class list and INotifyPropertyChanged interface.Both are playing important role in WPF and Silverlight application implementation and especially on MVVM pattern. Where an entity class updating the IEnumarable and collection list,INotifyPropertyChanged event trigger to update the View Model. Here is straight forward workaround.I have a class with three members like FirstName,LastName and City. As soon as you hit the button save it will bind to the DataGrid control in Silverlight. I did in SharePoint 2013.
       
        public MainPage()
        {
            InitializeComponent();
            List Name = new List();
            Name.Add("Chennai");
            Name.Add("Banglore");
            Name.Add("Mumbai");
            autoCom.ItemsSource = Name;
           
            
        }
        ClientContext context;
        Web web;
        private delegate void UpdateUI();
        
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            context = ClientContext.Current;
             web = context.Web;
             context.Load(web);
             context.ExecuteQueryAsync(Onsuccess, OnFailure);
           
        }
        public void Onsuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            UpdateUI obj = ShowResult;
            this.Dispatcher.BeginInvoke(obj);

        }
        public void OnFailure(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show(e.StackTrace.ToString());
        }
        public void ShowResult()
        {
           
      
            ObservableCollection list = new ObservableCollection();
            list.Add(new observableList(txtFirst.Text, txtLastName.Text,autoCom.Text));
         
            MyGrid.ItemsSource = list;
         
        }
Create the class and inherit with INotifyPropertyChanged interface.
 public class observableList : INotifyPropertyChanged
    {
        private string fName;
        private string lName;
        private string city;
        public string FirstName
        {
            get { return fName; }
            set { fName = value;
            NotifyPropertyChanged("FirstName");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public string LastName { get { return lName; } set { lName = value; NotifyPropertyChanged("LastName"); } }
        public string City { get { return city; } set { city = value; NotifyPropertyChanged("City"); } }
        public void NotifyPropertyChanged(string param)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(param));
            }
        }
        public observableList(string f,string l,string c)
        {
            this.fName = f;
            this.lName = l;
            this.city = c;
        }


        
    }

Wednesday, March 27, 2013

jQuery integration in SharePoint

This blog may be very simple but it really useful to understand "How to integrate the jQuery  in SharePoint WebPart or SharePoint Application Page"

First approach
You can use the Module to include the jQuery file if you developing the "Sandbox" solution and refer the file path in script tag.

Second approach

In farm solution,you can include the jQuery file in _layout folder and for best practice create the "1033" folder inside the _layouts and refer in script tag.
Here you can use the SharePoint Script Link control also


Instead of using Google or Microsoft hosted CDN you can download the file and host in your local sharepoint server.
 

Sunday, March 24, 2013

SharePoint 2013 – App feature


  • SharePoint 2013 app will runs in isolated app domain.
  • You can create the root level DSN or sub domain to pointing your SharePoint app in SharePoint hosted type app.
  • It will not get deployed under System account when you trying to deploy the app in Visual studio.
  • To run you App you need to create you site based on “Developer Site”.
  • Each app will shares the subsite of your site collection.
  • The subsite created through app deployment will not be visible under “Site Contents”.

HTML Field Security in SharePoint 2013


SharePoint 2013 had new feature called HTML Field Security,It will restrict the user to place any of the websites in the iframe in pages of your site.
You can set the below permissions
  • Do not permit contributors to insert iframes from external domains into pages on this site.
  • Permit contributors to insert iframes from any external domain into pages on this site.
  • Permit contributors to insert iframes from the following list of external domains into pages on this site.
Simply you need to add the site names in the list box to restrict or allow the users to use the iframe.
*This feature will not helpful when user trying to put the iframe in webpart through code.

Community site template in SharePoint 2013


Community Sites are new in SharePoint 2013.
They provide forums for people to ask and answer questions, post information, comment on posts and get rewarded for their efforts in the form of points, earned badges, and gifted badges. Those that are familiar with the Microsoft forums will see a lot of similarities.
Much of the functionality in those forums has been built into the SharePoint Communities Sites. Additional components that are found in social networks such as “liking” a post are also included.
This set of functionality can be extremely powerful in encouraging the sharing of knowledge and contributing of content.
You can create the new site or you can activate the feature in existing site collection to use community site.
Site Settings->Site Action->Manage Site Features – Activate the “Community Site Feature”
if you are not able to see the “Community Site template” first activate the “SharePoint server standard collection feature”.

Tuesday, March 12, 2013

Napa Office 365 Development Tool

The Napa Office 365 Development Tools  which is available only to the site collection which is based on "Developer Site" template.

Because it use the isolated sandbox for development activities.

You can develop the office and sharepoint application in browser itself and doesn't require to install any development tools.
How to activate the "Napa" tool for your Office 365 site.Here I am using SharePoint 2013,if you are using the Office 365,SharePoint 2010 the visual steps may be slightly differ from this.



Napa Office 365 Development tool
 Step 2

Napa Office 365 Development tool




Step 3
Napa Office 365 Development tool

Step 4
Napa Office 365 Development tool
Step 5


Tuesday, March 05, 2013

SharePoint 2013 prerequisites

SharePoint 2013 prerequisites are below:
• Microsoft .NET Framework 4.5
• Windows Management Framework 3.0
• Microsoft SQL Server 2008 R2 SP1 Native Client
• Windows Identity Foundation
• Microsoft Sync Framework Runtime v1.0 SP1 (x64)
• Windows Server AppFabric
• Microsoft Identity Extensions
• Microsoft Information Protection and Control Client
• Microsoft WCF Data Services 5.0 and
• Cumulative Update Package 1 for Microsoft AppFabric 1.1 for Windows Server (KB2671763)

Site Column creating via code

Site columns can be created while site provisioning and later these field can be attached to content type and associating this content type to a specific list. Place below code in "Feature Receiver".
 public string _firstNameText = "";
        public string _secondNameText = "";    

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            
            using (SPSite site = (SPSite)properties.Feature.Parent)
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.Fields.AddFieldAsXml(_firstNameText);
                    web.Fields.AddFieldAsXml(_secondNameText);
                    
                    web.Update();
                }
            }

        }

Sunday, February 24, 2013

Adding Active directory group in SharePoint group

This code will help you to add the Active Directory Group in the Custom SharePoint Group. Consider the situation you need to give the access permission to multiple users on the basis of department wise or any category based which is already created in AD. Now add this group in SharePoint group to simplify the process. This will add the new sharepoint group programmatically and the AD group in to it.

           SPWeb web = SPContext.Current.Web;
            web.AllowUnsafeUpdates = true;
            web.SiteGroups.Add("Champion10", web.CurrentUser, web.CurrentUser, string.Empty);
         
            SPGroup group= web.SiteGroups["Champion10"];
            SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
            SPRoleDefinition roleDefinition = web.RoleDefinitions["Full Control"];
            roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
            web.RoleAssignments.Add(roleAssignment);


            SPUser AdGroup = web.EnsureUser("MurugesanAD");
           //This line will do the trick.You can also ensure by using the  bool isAD=AdGroup.IsDomainGroup

            group.AddUser(g);

       
            web.Update();
            web.AllowUnsafeUpdates = false;
         
            Literal1.Text = "Done";

Sunday, February 17, 2013

Reminder Workflow in SharePoint Designer

For sending the reminder email notifications to the workflow participant,I would prepare to create a separate workflow as I do not want to disturb the business logic in core workflow. In main list,I have associated the core workflow and The secondary workflow for sending the reminder email. When the core workflow sending by default email,I simply capture the some of its columns in another list along with "ReminderCount". In my new list "Reminder",column reminder count will be set to 1 and then some pause until some defined timeline. Activity 2 : [Create Item] It will create a list item in the list "Reminder" as soon as core workflow triggered. In output to variable workflow will create the variable [UpdatedId - I just renamed] which is used to store the item id of the "Reminder" This ID will be used for updating the ReminderCount in this list later. Activity 3: I just logged the message for ensure the newly created item id in the "Reminder" List. Activity 4: Pausing for some time to get response from approver. If approver didn't respond to his task within time. Activity 5 Here I do calculation for reminder count.Just retrieve previous the value of the "Reminder Count" column and adding to 1. For retrieving the previous value of "Reminder Count" I simply used the List ID and its value from the workflow created list item id. Activity 6 : Using the Update List Item,for this I just updating the item [Reminder Count] by passing the workflow created item id (UpdatedId) and its value which is calculated from the previous activity (calc1).

Monday, February 11, 2013

OpenXML-Update excel cell value

Code snippet for helping to update the specific cell in excel using the OpenXML SDK 2.0. When you updates the specific cell make sure to test with isNull or Empty otherwise write some default value in the sell and then use the below code to update. Because OpenXML ignores the empty cell.

 using (SpreadsheetDocument document = SpreadsheetDocument.Open("D:\\template.xlsx", true))
            {
                WorkbookPart wbPart = document.WorkbookPart;
                Sheet theSheet = wbPart.Workbook.Descendants().
                Where(s => s.Name == "Sheet1").FirstOrDefault();
                Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(theSheet.Id))).Worksheet;
                WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id));
                SheetData sheetData = ws.GetFirstChild();
                var theRow = sheetData.Elements(). Where(r => r.RowIndex.Value == 6).FirstOrDefault();
                Cell refCell = theRow.Elements().
                Where(c => c.CellReference == "G6").FirstOrDefault();
                refCell.CellValue = new CellValue("TestComes");
                refCell.DataType = new EnumValue(CellValues.String);
                ws.Save();
           
            }

Thursday, February 07, 2013

FileUpload SharePoint Online

Recently I was asked to workaround for uploading the files to SharePoint list pro-grammatically for SharePoint online. As I can use only sandbox solution,I tried the SPProxyOperation class to upload and save the file. But its very complex process for staging the package and deployment. Later I come up with very simple approach,After adding the items to the list I retrieved the Item ID and ListID and passing these parameters to the file "/_layouts/AttachFile.asp?ListID="{GUID}"&ItemID=itemId&isDlg=1 into SPModal dialog.

Click here to upload file to this item

Thursday, January 24, 2013

Silverlight Datagrid bind with list items

This will be helpful for the beginners to learn how to bind the silverlight datagrid control with SharePoint List Items in a list. Create the List name called "Friends" and create column FirstName,LastName,Email. Create the the class "MyFriends" and the data members using getter and setter to map with the sharepoint list columns. While retrieving the collection of items we will add the generic class of the "MyFriends" class and subsequently binding them to Silverlight datagrid.
  public class MyFriends
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string EmailID { get; set; }
            public int ItemID { get; set; }
        }

last member ItemID created for retrieving the item id for identify the each individual item from the collection of items for update and delete operation for further work.
        Web web;
        List list;
        ListItem item;
        ListItemCollection cols;
        private delegate void UpdateUI();


 public MainPage()
        {
            InitializeComponent();
            context = ClientContext.Current;
            web = context.Web;
            context.Load(web);
            list = web.Lists.GetByTitle("Friends");
            CamlQuery q = new CamlQuery();
            q.ViewXml = "";
            cols = list.GetItems(q);
            context.Load(cols);
            context.ExecuteQueryAsync(OnItemLoadSuccess, OnItemLoadFailed);
        }
        ClientContext context;
       
        private void OnItemLoadSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            UpdateUI _eventReg = BindItems;
            Dispatcher.BeginInvoke(_eventReg);
        }
        private void OnItemLoadFailed(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show("Error" + e.StackTrace.ToString());
        }
        public void BindItems()
        {
            List obj = new List();
            foreach (ListItem item in cols)
            {
                obj.Add(new MyFriends
                {
                    FirstName = item["First_x0020_Name"].ToString(),
                    LastName = item["First_x0020_Name"].ToString(),
                    EmailID = item["EmailID"].ToString(),
                    ItemID = Convert.ToInt32(item["ID"])
                });
                dataGrid1.ItemsSource = obj;
            }
        }

Tuesday, January 15, 2013

Adding new item silverlight with sharepoint

This code will help you to start the journey on How to develop SilverLight WebPart using SharePoint Client Side Object Model to add new item in SharePoint List.

Add the following sharepoint related assemblies which specifically tailored for the SilverLight and its Client side object model.

Microsoft.SharePoint.Client.SilverLight; Microsoft.SharePoint.Client.SilverLight.Runtime; These assemblies located at

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin
namespace SilverlightApplication7
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private delegate void UpdateUI();
        private ClientContext ctx;
        private Web web;
       
        List list;
     
        ListItem item;

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            ctx = ClientContext.Current;
            web = ctx.Web;
            ctx.Load(web);
            list = web.Lists.GetByTitle("Friends");
            ctx.Load(list);
            ListItemCreationInformation info = new ListItemCreationInformation();
            item = list.AddItem(info);
            item["Title"] = textBox1.Text;
            item["Name"] = textBox2.Text;
          
            item.Update();
            ctx.Load(item);
            ctx.ExecuteQueryAsync(OnOperationSuccess, OnOperationFailure);
           
        }
        public void ShowSuccessMessage()
        {
          
            MessageBox.Show("Added","Silverlight with SharePoint",MessageBoxButton.OK);
            textBox1.Text = "";
            textBox2.Text = "";
        }
        public void OnOperationSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            UpdateUI obj = ShowSuccessMessage;
            this.Dispatcher.BeginInvoke(obj);
        }
        public void OnOperationFailure(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show(e.Message.ToString());
        }
    }
}

Syntax HighLighter test



Murugesa Pandian.MCTS


Saturday, January 12, 2013

SharePoint 2010 Sandbox solution limitation

Below of these artifacts cannot be used in SharePoint 2010-Sandbox solution.

First thing is whatever the code which deals with outside of the server its not possible in Sandbox. Example: SPUtility.SendEmail method It needs to communicate with email server.

System.Net.Mail : This method can be used in classic asp.net web application or Farm solution in SharePoint but not in Sandbox solution. If you trying to send an email using this classes in your sandbox solution,It will compiles successfully but in run time it will throw SecurityException.

If you want to achieve this in sandbox solution then consider the Silverlight webpart with WCF or web service.

Next is the code which is trying to alter or create the pages in the file system in SharePoint Server is not allowed in Sandbox.

  • Application Pages
  • Mobile Pages
  • Site Definition and
  • UserControl(.ascx) - Visual WebPart.
  • Few tools available in CodePlex to create the Sandboxed visual webpart but it comes up with limitation that means some of the server object model and SharePoint controls cannot be used in it.

    Instead of using the visual webpart you can consider the ASP.NET WebPart in Sandbox solution.

    Finally,As soon as you select the solution type in Visual Studio for Sandbox solution VS will add the trimmed the features in Microsoft.SharePoint.dll.