Wednesday, August 17, 2011

Grant folder permission(SharePoint) using powershell script

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
 $site = new-object Microsoft.SharePoint.SPSite("http://myserver/")
 $web = $site.OpenWeb()
 function GrantGroupPermission($groupName)
 {
  [Microsoft.SharePoint.SPGroupCollection]$spgroups = $web.SiteGroups
  [Microsoft.SharePoint.SPGroup]$spgroup = $groups[$groupName]
  $sproleass=new-object Microsoft.SharePoint.SPRoleAssignment([Microsoft.SharePoint.SPPrincipal]$spgroup)
  $folder.BreakRoleInheritance("true")
  $sproleass.RoleDefinitionBindings.Add($web.RoleDefinitions["Contribute"])
  $folder.RoleAssignments.Add($sproleass);
  Write-Host "Permission provided for group ", $groupName
 }
 function GrantUserpermission($userName)
 {
  [Microsoft.SharePoint.SPUserCollection]$spusers=[Microsoft.SharePoint.SPUserCollection]$web.SiteUsers
  [Microsoft.SharePoint.SPUser]$spuser=$spusers[$userName]
  $sproleass=new-object Microsoft.SharePoint.SPRoleAssignment([Microsoft.SharePoint.SPPrincipal]$spuser)
  $folder.BreakRoleInheritance("true")
  $sproleass.RoleDefinitionBindings.Add($web.RoleDefinitions["Contribute"])
  $folder.RoleAssignments.Add($sproleass);
  Write-Host "Permission provided for user ", $userName
 }
 $doclib=[Microsoft.SharePoint.SPDocumentLibrary]$web.Lists["Shared Documents"]
 $foldercoll=$doclib.Folders;
 foreach($folder in $foldercoll)
 {
  Write-Host $folder.Name
  if($folder.Name.Equals("f2"))
  {
   GrantUserPermission("raj")
  }
 
 }
 Write-Host "Completed...."
 $web.Close()
 $site.Dispose()

Friday, May 20, 2011

Basic STSADM commands


Add the solution 

stsadm -o addsolution -filename {WSPFILENAME}

Deploy the solution 

stsadm -o deploysolution -name {WSPFILENAME} -url {SITEURL}

Install the feature 

stsadm -o installfeature -filename {FeatureFolder}\feature.xml

Activate the feature 

stsadm -o activatefeature -id {FEATUREID} -url {SITEURL} -force

Deactivate the feature 

Stsadm.exe -o deactivatefeature -filename

Wednesday, May 11, 2011

Auto-Generate number based on location code from another list


public void GenerateInwardNumber(SPItemEventProperties properties)
       {
           try
           {
               int autoid = 101;
               SPWeb oWeb = properties.Web;
               oWeb.AllowUnsafeUpdates = true;
               SPList oList = properties.List;
               SPListItem oItem = properties.ListItem;
               string[] s = Convert.ToString(oItem["Location"]).Split('#');
               string location = s[s.Length - 1];
               SPQuery qry = new SPQuery();
               qry.Query = "<Where><Eq><FieldRef Name='Location1' /><Value Type='Lookup'>" + location + "</Value></Eq></Where><OrderBy><FieldRef Name='Document_x0020_Inward_x0020_Number' Ascending='False' /></OrderBy>";
               SPListItemCollection oItemColl = oList.GetItems(qry);
               string locCode = GetLocationCode(location, properties.Web);
               string oldDIN = Convert.ToString(oItemColl[0]["Document_x0020_Inward_x0020_Number"]);
               string[] str = oldDIN.Split('-');
               if (!string.IsNullOrEmpty(oldDIN))
                   autoid = Convert.ToInt16(str[str.Length - 1]) + 1;
               else
                   autoid = 101;
               SPListItem oCurrItem = properties.ListItem;
               oCurrItem["Document_x0020_Inward_x0020_Number"] = locCode + "-" + autoid;
               this.EventFiringEnabled = false;
               oCurrItem.SystemUpdate(false);
               this.EventFiringEnabled = true;
               oWeb.AllowUnsafeUpdates = false;
           }
           catch (Exception ex)
           {
               properties.ErrorMessage = ex.Message;
           }
       }

       public string GetLocationCode(string location,SPWeb cWeb)
       {
           string locCode="";
           try
           {
               SPQuery locqry = new SPQuery();
               locqry.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + location + "</Value></Eq></Where>";
               SPList locList = cWeb.Lists["Locations"];
               SPListItemCollection oItemColl = locList.GetItems(locqry);
               locCode = Convert.ToString(oItemColl[0]["Location_x0020_Code"]);
           }
           catch (Exception ex)
           {
           }
           return locCode;
       }

Thursday, May 5, 2011

Formatting Date Time in C#



DateTime time = DateTime.Now;
string format = "MMM ddd d HH:mm yyyy";
Console.WriteLine(time.ToString(format));

Tuesday, May 3, 2011

Programmatically getting the metadata information



                SPSite site = new SPSite("http://myserver");
                TaxonomySession txSesssion = new TaxonomySession(site);
                foreach (TermStore store in txSesssion.TermStores)
                {
                    foreach (Group g in store.Groups)
                    {
                        if (g.Name == "GROUP1")
                        {
                            foreach (TermSet tSet in g.TermSets)
                            {
                                if (tSet.Name == "termset1")
                                {
                                    Console.WriteLine("......TermSET : " + tSet.Name);
                                    foreach (Term t in tSet.Terms)
                                    {
                                        Console.WriteLine("TERM :" + t.Name);
                                    }
                                }
                            }
                        }
                    }
                }

Saturday, April 30, 2011

Programmatically adding a document to a document library

  public void AddDoctoLibrary()
        {
            if (FileUpload1.PostedFile != null)
            {
                if (FileUpload1.PostedFile.ContentLength > 0)
                {
                    Stream strm = FileUpload1.PostedFile.InputStream;
                    byte[] byt = new byte[Convert.ToInt32(FileUpload1.PostedFile.ContentLength)];
                    strm.Read(byt, 0, Convert.ToInt32(FileUpload1.PostedFile.ContentLength));
                    strm.Close();
                    // Open site where document library is created.
                    using (SPSite oSite = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb(SPContext.Current.Web.ID))
                        {
                            SPList lstMeetingDocuments = oWeb.Lists["Meeting Documents"];
                            oWeb.AllowUnsafeUpdates = true;
                            SPFile newfile = lstMeetingDocuments.RootFolder.Files.Add(Path.GetFileName(FileUpload1.PostedFile.FileName), byt);
                            SPListItem newItm = lstMeetingDocuments.GetItemById(newfile.Item.ID);
                            newItm["MeetingID"] = lblMID.Text;
                            newItm.Update();
                            lstMeetingDocuments.Update();
                        }
                    }
                }
            }

Thursday, April 28, 2011

Send mail through server object model


public void sendEmail(string mailid)
        {
            try
            {
                SPWeb web = SPContext.Current.Web;
                bool appendHtmlTag = false;
                bool htmlEncode = false;
                string toAddress = mailid;
                string subject = "Comments";
                string message = txtComment.Text;
                bool result = SPUtility.SendEmail(web, appendHtmlTag, htmlEncode, toAddress, subject, message);

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

How to launch a document by clicking a link to the file?

Word: <a href='ms-word:ofe|u|path/to/web/word/document.docx'>Link to document</a> Excel: <a href='ms-excel:o...