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