Tuesday, November 26, 2013

Code to check provided SharePoint list existed or not

use below code to check provided list existed or not

SPList list = currWeb.Lists.TryGetList("SampleList");
if(list!=null)
{
//some code
}

Monday, November 25, 2013

Add Farm Solution in Sharepoint

//Main

 FileStream stream = null;

       
            string UploadFileName = @"C:\sample.wsp";


            FileInfo fileInfo = new FileInfo(UploadFileName);

            //Verifying the condition whether that file is existed (or) not
            if (!fileInfo.Exists) { throw new InvalidOperationException("The file does not exist."); }

            byte[] bytes = System.IO.File.ReadAllBytes(fileInfo.Name);

            //If file existed converting it in to the stream to transfer
            stream = File.OpenRead(UploadFileName);
            stream.Position = 0;


//usage

AddSolutionWorker("sample.wsp",bytes)


//Method
  public void AddSolutionWorker(string wspName, byte[] wspcontents)
  {
   string tdir = Path.GetDirectoryName(Path.GetTempFileName());
   string wsppath = string.Format(@"{0}\{1}", tdir, wspName);

   if (File.Exists(wsppath))
    File.Delete(wsppath);

   File.WriteAllBytes(wsppath, wspcontents);

   SPFarm.Local.Solutions.Add(wsppath);

   File.Delete(wsppath);
  }

List Of Solutions(.wsp) Present in SharePoint Farm (method will return an List)

public List<Solution> GetSolutions()
  {
   List<Solution> solutions = new List<Solution>();
   foreach (SPSolution sol in SPFarm.Local.Solutions)
   {
    Solution s = new Solution();
    s.Name = sol.Name;
    s.Deployed = sol.Deployed;
    solutions.Add(s);
   }
   return solutions ;
  }

Get all site collections in the WebApplication using a Object Model SharePoint

  public void GetAllSiteCollections(string url)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPWebApplication webApplication = SPWebApplication.Lookup(new Uri(url));
                foreach (SPSite site in webApplication.Sites)
                {
                  //do your action
                }
            });
        }

To View SharePoint Site in Mobile View

We can look SharePoint Site "Mobile View" by just appending an ?mobile=1 to the URL

Sample :http://localhost:port

Mobile View :http://localhost:port?mobile=1

soon ill post on the SharePoint Mobile WebPart Development.. :)

Compare the QueryString Value with Upper/lower case asp.net

  if (Querysting.IndexOf("TEXT", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
                        {
                            //do action
                        }

Search the SQL Stored Procedure Name with ('%Partial Name as Input%')

Select name from sysobjects where name like '%OS%' and type='P'

Change the existing content type of the List (or) SharePoint Library using ClientContext

 private void ChangeContentTypeOrder(ClientContext ctx, List list, string contentTypeName)
        {
            Microsoft.SharePoint.Client.ContentTypeCollection currentCTOrder = list.ContentTypes;
            ctx.Load(currentCTOrder);
            ctx.ExecuteQuery();

            IList<Microsoft.SharePoint.Client.ContentTypeId> reverceOrder = new List<Microsoft.SharePoint.Client.ContentTypeId>();
            foreach (Microsoft.SharePoint.Client.ContentType ct in currentCTOrder)
            {
                if (ct.Name.Equals(contentTypeName))
                {
                    reverceOrder.Add(ct.Id);
                }

            }
            list.RootFolder.UniqueContentTypeOrder = reverceOrder;
            list.RootFolder.Update();
            list.Update();
            ctx.ExecuteQuery();
        }

Check if SharePoint List already Exists using ClientContext

 private bool ValdiateList(ClientContext clientContext, string listName, out List existingList)
        {

            Web web = clientContext.Web;

            existingList = null;

            ListCollection lists = web.Lists;

            IEnumerable<List> existingLists = clientContext.LoadQuery(lists.Where(list => list.Title == listName));

            clientContext.ExecuteQuery();

            existingList = existingLists.FirstOrDefault();

            if (existingList != null)

                return true;

            else

                return false;

        }

SharePoint Get all Content Types from ClientContext

public static void getallcontenttypes()
        {
            string siteUrl = "http://localhost/";

            ClientContext clientContext = new ClientContext(siteUrl);
            Web web = clientContext.Web;
            List list = web.Lists.GetByTitle("CustomList");
            ContentTypeCollection contentTypeColl = list.ContentTypes;
            clientContext.Load(contentTypeColl);
            clientContext.ExecuteQuery();
            Console.WriteLine("List Content types:");
            Console.WriteLine("################################");
            foreach (ContentType contentType in contentTypeColl)
            {
                Console.WriteLine("Name: " + contentType.Name + " Id: " + contentType.Id);
            }
            Console.ReadLine();
        }

Get SharePoint GetListItemByID from signature (string url, string listName, int id)

     public ListItem GetListItemByID(string url, string listName, int id)
        {
            using (ClientContext context = new ClientContext("http://sampleurl:port/"))
            {
                Web web = context.Web;
                List list = web.Lists.GetByTitle(listName);
                ListItem item = list.GetItemById(id);

                context.Load(item);
                context.ExecuteQuery();

                return item;
            }
        }

SharePoint Formula for calculated column : No of Days excluding Saturdays and sundays SharePoint

=(DATEDIF(StartDate,EndDate,"d"))-INT(DATEDIF(StartDate,EndDate,"d")/7)*2-IF((WEEKDAY(EndDate)-WEEKDAY(StartDate))>0,2,0)+1

Sunday, November 24, 2013

How to Use Sandbox Solution Code which is given in my BLOG

Usage  ex :-

FileStream stream = null;

            string sitecollectionUrl = "http://samplesitecollection:port";
            string UploadFileName = @"C:\HelloWorldSolution.wsp";


            FileInfo fileInfo = new FileInfo(UploadFileName);

            //Verifying the condition whether that file is existed (or) not
            if (!fileInfo.Exists) { throw new InvalidOperationException("The file does not exist."); }

            byte[] bytes = System.IO.File.ReadAllBytes(fileInfo.Name);

            //If file existed converting it in to the stream to transfer
            stream = File.OpenRead(UploadFileName);
            stream.Position = 0;


            //checking if the solution is uploaded in sitecollection solution gallery
            bool SolutionExits = CheckSolutionExits(sitecollectionUrl, fileInfo.Name);

           

            if (SolutionExits != true)
            {
                //add solution & activate
               bool SuccessDeployed = AddActivateSolutionbytes(sitecollectionUrl, fileInfo.Name, bytes);

            }

            if (SolutionExits == true)
            {
                //remove solution
                bool RemoveSuccess = RemoveSolution(sitecollectionUrl, fileInfo.Name);
            }

Remove & Delete Sandbox Solution — will Deactivate and Remove the solution from the sitecollection gallery (Signature : sitecollection url(string),wspname(string))



  public static bool RemoveSolution(string sitecollection, string wspname)
        {
            bool RemoveSuccess = false;
            #region removing Solution

            try
            {

                SPSecurity.RunWithElevatedPrivileges(delegate()
                  {
                      using (SPSite site = new SPSite(sitecollection))
                      {
                          //Code to deactivate solution
                          SPUserSolutionCollection siteSolutions = site.Solutions;

                          foreach (SPUserSolution solution in siteSolutions)
                          {
                              if (solution.Name.Equals(wspname))
                              {
                                  //solution found & remove it
                                  SPUserSolution solutions = site.Solutions.Cast<SPUserSolution>().

                                  Where(s => s.Name == wspname).First();

                                  site.Solutions.Remove(solutions);
                                  break;

                              }


                          }
                          // Code to Delete solution
                          SPList solGallery = site.GetCatalog(SPListTemplateType.SolutionCatalog);
                          foreach (SPListItem item in solGallery.Items)
                          {
                              if (item.File.Name.Equals(wspname))
                              {
                                  solGallery.Items.DeleteItemById(item.ID);
                                  RemoveSuccess = true;
                                  break;
                                 
                              }
                          }

                      }
                  });
            }

            catch (Exception ex)
            {
                RemoveSuccess = false;
               // string exception = ex.Message.ToString();
            }
            return RemoveSuccess;
            #endregion
        }

AddActivateSolutionbytes -“Upload and Activate the sandbox solution of a site collection gallery” (Signature : sitecollection url(string),wspname(string),bytes(byte[]))


Add and ActivateSoltution:


  public static bool  AddActivateSolutionbytes(string sitecollection, string WSPfilename, byte[] bytes)
        {
            bool Success = false;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite site = new SPSite(sitecollection))
                    {


                        //Get the Solution Gallery for the SPSite
                        SPDocumentLibrary gallery = (SPDocumentLibrary)site.GetCatalog(SPListTemplateType.SolutionCatalog);



                        //Add the WSP File. I've used a source that is an SPFile, but really it's a string and byte array
                        SPFile file = gallery.RootFolder.Files.Add(WSPfilename, bytes);
                        // Activate Solution 
                        SPUserSolution solution = site.Solutions.Add(file.Item.ID);

                        Success = true;



                    }

                });
               
            }
            catch (Exception ex)
            {

                Success = false;
                //add logger
            }
          
             return Success;
        }

• CheckSolutionExits- “checks if the sandbox solution already exists in the sitecollection solution gallery” (Signature : sitecollection url(string),wspname(string))

CheckSolutionExits:-


    public static bool CheckSolutionExits(string sitecollection, string wspname)
        {
            #region Solution exits
            bool Found = false;
            try
            {

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(sitecollection))
                    {

                        SPList solGallery = site.GetCatalog(SPListTemplateType.SolutionCatalog);
                        foreach (SPListItem item in solGallery.Items)
                        {
                            if (item.File.Name.Equals(wspname))
                            {
                                Found = true;
                                break;

                            }
                        }

                     

                    }

                });

            }

            catch (Exception ex)
            {
               throw ex;
            }

            #endregion
            return Found;
        }