Wednesday, December 18, 2013

Check if the User has permission on the document (ViewPermission) ClientContext

 /// <summary>
        /// Check if the User has permission on the document (ViewPermission)
        /// </summary>
        /// <returns></returns>
        public bool DoesUserCanRead(string userLogin, string listId, string itemId, string siteUrl, string webId)
        {
            Logger.writeToLogFile(Constants.MSearch, "DoesUserCanRead Start", Logger.LogLevel.LOG);
            bool CheckPermission = false;
            try
            {
                Guid Listitemid = new Guid(listId);

                Guid WebId = new Guid(webId);

                int ITEMID = Convert.ToInt32(itemId);


                ClientContext clientContext = new ClientContext(siteUrl);
                Microsoft.SharePoint.Client.ListItem item = clientContext.Site.OpenWebById(WebId).Lists.GetById(Listitemid).GetItemById(ITEMID);
                clientContext.Load(item);
                clientContext.ExecuteQuery();

                User usr = clientContext.Web.EnsureUser(userLogin);
                clientContext.Load(usr);
                clientContext.ExecuteQuery();

                ClientResult<BasePermissions> result = item.GetUserEffectivePermissions(usr.LoginName);
                clientContext.ExecuteQuery();

                CheckPermission = result.Value.Has(PermissionKind.ViewListItems);
            }
            catch (Exception ex)
            {
                Logger.writeToLogFile("MSearch", ex.Message.ToString(), "DoesUserCanRead", userLogin, Logger.LogLevel.ERROR);

                Response.Redirect("~/CGIError.aspx", true);
            }
         

            return CheckPermission;
        }

Monday, December 16, 2013

DoesUserCanRead find using ClientContext From ListItemID

private static bool DoesUserCanRead(string userLogin, string listId, string itemId, string siteUrl,string webId)
        {

                bool result = true;
           
                Guid Listitemid = new Guid(listId);

                Guid WebId = new Guid(webId);

                int ITEMID = Convert.ToInt32(itemId);


                ClientContext clientContext = new ClientContext(siteUrl);
           
                Microsoft.SharePoint.Client.ListItem item = clientContext.Site.OpenWebById(WebId).Lists.GetById(Listitemid).GetItemById(ITEMID);
                item.GetUserEffectivePermissions(userLogin);
                result=item.GetUserEffectivePermissions(userLogin).ToString().Contains(SPBasePermissions.EmptyMask.ToString());
                clientContext.Load(item);
                clientContext.ExecuteQuery();

                return result;
        }


http://books.google.co.in/books?id=4lKnn9ZzG1AC&pg=PA148&lpg=PA148&dq=item.GetUserEffectivePermissions+Check+permissions&source=bl&ots=LR7vIxmRAr&sig=HvoK4rl5hp7m_jqAlSOBA9D7sb0&hl=en&sa=X&ei=c_CuUoj0Ouqd2QWi7IHQCQ&ved=0CGkQ6AEwCQ#v=onepage&q=item.GetUserEffectivePermissions%20Check%20permissions&f=false


Thursday, December 12, 2013

Check if the User have permission to site

  public bool UserPermission(string Site, string userID)
        {
            bool retValue=false;

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (var site = new SPSite(Site))
                {
                    using (var web = site.OpenWeb())
                    {
                        retValue = web.DoesUserHavePermissions(userID, SPBasePermissions.Open);
                    }
                }
            });
            return retValue;
        }

Monday, December 9, 2013

"Using" Statement vs Dispose in C# (.NET: Using using blocks vs. calling .Dispose() )

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

This is described here: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Sunday, December 8, 2013

KQL Query Limitation SharePoint

Based on Microsoft documentation the following are the limits for KQL statements:


The length limit of a KQL query varies depending on how you create it. If you create the KQL query by using the default SharePoint search front end, the length limit is 2,048 characters. However, KQL queries you create programmatically by using the Query object model have a default length limit of 4,096 characters. You can increase this limit up to 20,480 characters by using the MaxKeywordQueryTextLength property or the DiscoveryMaxKeywordQueryTextLengthproperty (for eDiscovery). 

Soon ill post how to use this using C#

Friday, December 6, 2013

Check if the Site Column Exits in SiteCollection

    /// <summary>
        /// Ensures that the site column exists.
        /// </summary>
        /// <param name="web">Rootweb container of site columns</param>
        /// <param name="fieldname">Name of the site column</param>
        /// <param name="showInNewAndEditForm">Boolean determines whether to field exits</param>
        /// <returns></returns>
        public bool EnsureSiteColumn(string spsite, string fieldname)
        {
         
            bool FieldExits=false;
            using (SPSite site = new SPSite(spsite))
            {
                using (SPWeb web = site.RootWeb)
                {
                    try
                    {
                        web.AllowUnsafeUpdates = true;

                        SPField fieldExists = null;
                        if (web.Fields.ContainsField(fieldname))
                            fieldExists = web.Fields[fieldname];

                        if (fieldExists == null)
                        {
                            FieldExits = false;
                            //Site Column Not Found
                        }
                        else
                        {
                            FieldExits = true;
                            //Site Column Found
                        }
                    }
                    catch(Exception ex)
                    {
                       throw ex;
                    }
                    finally
                    {
                        web.AllowUnsafeUpdates = false;
                    }
                }
            }


            return FieldExits;
        }


            return FieldExits;
        }

Thursday, December 5, 2013

SharePoint Search Managed Properties & Crawled Properties

Crawled properties are generated from crawling the content in SharePoint. When the Search starts crawling content, the search component can discover new properties in the content. To give an example a site column attached to a document library would be treated as an additional property to the document and will be considered as a crawled property by SharePoint Search.

Though the properties are crawled it doesn't mean that the properties will be available for search. Crawled properties are mapped to managed properties with different attributes. These attributes determine how the contents are shown in search results. Managed property is always mapped to one or several crawled properties, this mapping is sometime done automatically and many times by a search administrator.


Though Managed and crawled properties are not new in SharePoint 2013. In previous versions of SharePoint, whenever a new item was discovered during a crawl, users would have to manually create a new managed property, and map this to the corresponding crawled property. But In SharePoint Server 2013 these are done automatically.

Tuesday, December 3, 2013

How to enable Version to document library Programmatically


 public void CheckVersionEnable(string ListName)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite osite = new SPSite("http://URL/"))
                {
                    using (SPWeb oweb = osite.OpenWeb("http://URL/"))
                    {
                        SPList docs = oweb.Lists[ListName];
                        if (docs.EnableVersioning == false)
                        {
                            docs.EnableVersioning = true;
                            docs.MajorVersionLimit = 10;
                            oweb.AllowUnsafeUpdates = true;
                            docs.Update();
                            oweb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });
        }

Create a DocumentLibrary in Sharepoint using C#

public bool CreateDocumentLibray(string spsite, string DocLibName)
        {
            bool DocumentLibrayExist = false;
            try
            {
                SPSite Site = new SPSite(spsite);
                Site.AllowUnsafeUpdates = true;
                SPWeb web = Site.OpenWeb();
                SPListTemplateType tempType = SPListTemplateType.DocumentLibrary;

                web.Lists.Add(DocLibName, null, tempType);
               DocumentLibrayExist =true;
  Site.AllowUnsafeUpdates = false;
            }
            catch (Exception ex)
            {
             
                throw ex;
            }
            return DocumentLibrayExist;

        }

Check if ContentType Already Exists in SharePoint Site

public bool CheckContentType(string spsite, string contenttypename)
        {
            bool ContentTypeFound = false;
            try
            {
               
                SPSite a = new SPSite(spsite);
                SPWeb web = a.OpenWeb();
                SPContentType myContentType = web.ContentTypes[contenttypename];
                if (myContentType != null)
                {
                    //found
                    ContentTypeFound = true;
                }
                else
                {
                    //Not found
                    ContentTypeFound = false;
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
           
            return ContentTypeFound;
        }

Check if SharePoint Site already exists

public bool SiteExists(string url)
        {
            bool Exists = false;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                       {
                           using (SPSite site = new SPSite(url))
                           {

                               using (SPWeb web = site.OpenWeb(url, true))
                               {
                                   Exists= true;
                               }

                           }
                       });

            }
            catch (FileNotFoundException)
            {
                Exists= false;
            }
            return Exists;
        }

Monday, December 2, 2013

Check if the Retention Policy already exits in SharePoint

                 
SPSite objSite = "";
            SPWeb objWeb = null;
            SPContentType objContentType = objWeb = objSite.OpenWeb();
                 objContentType = objWeb.ContentTypes[strContentType];

                 Policy spPolicy = Policy.GetPolicy(objContentType);
                 if (spPolicy == null)
                 {
                     Policy.CreatePolicy(objContentType, null);
                     spPolicy = Policy.GetPolicy(objContentType);

                }

Attach/Associate Workflow to Content Type SharePoint






  private bool CreateWorkflowAssociation(string strContentTypeName, string strWorkflowName, string strTaskList, string strHistoryList, string strSiteCollection)
        {
            SPSite objSite = null;
            SPWeb objWeb = null;
            SPContentType objContentType = null;
            bool blnReturn = false;

            try
            {
                objSite = new SPSite(strSiteCollection);
                objWeb = objSite.OpenWeb();

                objWeb.AllowUnsafeUpdates = true;
                objWeb.Update();
                objContentType = objWeb.ContentTypes[strContentTypeName];

                // Get the specific template for ReminderWorkflow
                SPWorkflowTemplate workflowTemplate = null;
                foreach (SPWorkflowTemplate template in objWeb.WorkflowTemplates)
                {
                    workflowTemplate = template;
                    if (workflowTemplate.Name == strWorkflowName)
                        break;
                }
                // Create an association.              
                SPWorkflowAssociation workflowAssociation = SPWorkflowAssociation.CreateWebContentTypeAssociation(workflowTemplate, strWorkflowName, strTaskList, strHistoryList);

                if (objContentType.WorkflowAssociations.GetAssociationByName(workflowAssociation.Name, objWeb.Locale) == null)
                    objContentType.WorkflowAssociations.Add(workflowAssociation);
                else
                    objContentType.WorkflowAssociations.Update(workflowAssociation);

                objWeb.Update();
                blnReturn = true;
                LogWindow.Text = "WORKFLOW ASSOCIATION DONE SUCCESSFULLY FOR " + strContentTypeName;
            }
            catch (Exception ex)
            {
                //throw;
                LogWindow.Text = "ERROR DETECTED WHILE WORKFLOW ASSOCIATION FOR " +" " + strContentTypeName +" " + ex.Message.ToString();
            }
            finally
            {
                if (objSite != null) objSite.Close();
                if (objWeb != null) objWeb.Close();
            }
            return (blnReturn);
        }


Usage:-


 bool AssociateWorkflow = CreateWorkflowAssociation(ContentType, "RetentionPolicy", "Tasks", "Workflow History", sitecollectionUrl);

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;
        }