Friday 7 September 2012

Exporting Site Permissions Programmatically (C#.NET) - MOSS 2007

While working on permission i got  a requirement to export site permissions an write to a text file separated by pipe line..

Please find the codes below


  private void ExportPermissions()
    {
        StringBuilder strBuilderLogger_public = new StringBuilder();
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite mySite = new SPSite("SITE URL"))
            {
                using (SPWeb myWeb = mySite.OpenWeb("WEB NAME"))
                {

                    if (myWeb != null)
                    {
                        //Logging
                        strBuilderLogger_public.AppendLine("Site Name|List Name|List Item Name|Current Permissons|Parent Permissions|Has Unique Permissions");

                        string strSiteCurrentRoleDefinitions_public = GetRoleAssignmentsByObject(myWeb, null, null).ToString();
                        //Roles Logging
                        strBuilderLogger_public.AppendLine(myWeb.Title + "|||" + strSiteCurrentRoleDefinitions_public + "|" + "|TRUE");

                        foreach (SPList myList in myWeb.Lists)
                        {
                            if (!myList.Hidden)
                            {

                                string strListCurrentRoleDefinitions_public = GetRoleAssignmentsByObject(null, myList, null).ToString();
                                if (!myList.HasUniqueRoleAssignments)
                                {

                                    strBuilderLogger_public.AppendLine(myWeb.Title + "|" + myList.ToString() + "||" + strListCurrentRoleDefinitions_public + "|" + strSiteCurrentRoleDefinitions_public + "|TRUE");

                                }
                                else
                                {

                                    strBuilderLogger_public.AppendLine(myWeb.Title + "|" + myList.ToString() + "||" + strListCurrentRoleDefinitions_public + "|" + strSiteCurrentRoleDefinitions_public + "|FALSE");
                                }


                                SPQuery mySpQuery = new SPQuery();
                                mySpQuery.ViewAttributes = "Scope=\"RecursiveAll\"";
                                SPListItemCollection mySPListItemCollection = myList.GetItems(mySpQuery);

                                strBuilderLogger_public.AppendLine("Site Name|List Name|List Item Name|Current Permissons|Parent Permissions|Has Unique Permissions");
                                string strMyFileName = string.Empty;

                                foreach (SPListItem mySPListItem in mySPListItemCollection)
                                {
                                    string strListItemName_public = string.Empty;
                                    if (mySPListItem["Name"].ToString().ToUpper() != mySPListItem.DisplayName.ToUpper())
                                    {
                                        strListItemName_public = mySPListItem["Name"].ToString() + "_" + mySPListItem.DisplayName;
                                    }
                                    else
                                    {
                                        strListItemName_public = mySPListItem["Name"].ToString();
                                    }

                                    string strItemCurrentRoleDefinitions_public = string.Empty;
                                    strItemCurrentRoleDefinitions_public = GetRoleAssignmentsByObject(null, null, mySPListItem).ToString();

                                    //Checking Item Unique Permission
                                    if (!mySPListItem.HasUniqueRoleAssignments)
                                    {

                                        strBuilderLogger_public.AppendLine(myWeb.Title + "|" + myList.ToString() + "|" + strListItemName_public + "|" + strItemCurrentRoleDefinitions_public + "|" + strListCurrentRoleDefinitions_public + "|TRUE");
                                    }
                                    else
                                    {

                                        strBuilderLogger_public.AppendLine(myWeb.Title + "|" + myList.ToString() + "|" + strListItemName_public + "|" + strItemCurrentRoleDefinitions_public + "|" + strListCurrentRoleDefinitions_public + "|FALSE");
                                    }
                                }
                            }
                        }
                        //Logging
                        WriteLogEntry(strLoggerFileName_public, "Site Level Broken Permission Exported List", strBuilderLogger_public.ToString());
                    }
                }
            }


        });
    }

    public void WriteLogEntry(string loggerFileName, string strTitle, string strMessage)
    {
        try
        {

            //Create Logger Folder if not exists
            if (!System.IO.Directory.Exists(@"C:\logs\"))
            {
                System.IO.Directory.CreateDirectory(@"C:\logs\");
            }

            string strFileLoc = loggerFileName;
            StreamWriter writer = new StreamWriter(strFileLoc, true);
            writer.WriteLine(DateTime.Now.ToString() + " :- " + strTitle + System.Environment.NewLine + strMessage + System.Environment.NewLine + "");
            writer.Close();
        }
        catch { }
    }

    private StringBuilder GetRoleAssignmentsByObject(SPWeb myWeb, SPList myList, SPListItem myListItem)
    {
        StringBuilder strBuilderLogger = new StringBuilder();
        SPRoleAssignmentCollection myRoleAssignmentCollection;
        if (myWeb != null)
        {
            myRoleAssignmentCollection = myWeb.RoleAssignments;
        }
        else if (myList != null)
        {
            myRoleAssignmentCollection = myList.RoleAssignments;
        }
        else
        {
            myRoleAssignmentCollection = myListItem.RoleAssignments;
        }

        foreach (SPRoleAssignment myRoleAssignment in myRoleAssignmentCollection)
        {
            SPPrincipal myPrincipal = myRoleAssignment.Member;
            string strPrincipalNameAndRoleDefinition = myPrincipal.Name;
            SPRoleDefinitionBindingCollection myRoleDefinitionBindingCollection = myRoleAssignment.RoleDefinitionBindings;
            bool flag = false;
            foreach (SPRoleDefinition myRoleDefinition in myRoleDefinitionBindingCollection)
            {
                if (myRoleDefinition.Name.ToUpper() != "Limited Access".ToUpper())
                {
                    strPrincipalNameAndRoleDefinition += "-" + myRoleDefinition.Name;
                    flag = true;
                }

            }
            //Logging
            if (flag)
            {
                strBuilderLogger.Append(strPrincipalNameAndRoleDefinition + ",");
            }

        }

        if (!string.IsNullOrEmpty(strBuilderLogger.ToString()))
        {

            string strBeforeFormat = string.Empty;
            strBeforeFormat = strBuilderLogger.ToString();
            strBeforeFormat = strBeforeFormat.Substring(0, strBeforeFormat.Length - 1);
            strBuilderLogger = new StringBuilder();
            strBuilderLogger.Append(strBeforeFormat);
        }

        return strBuilderLogger;
    }


Tuesday 10 July 2012

WCF TraceListener


WCF exception messages are very generic and tough to decode.

WCF default TraceListener Objects for core WCF Objects. I have mentioned below details description for some important objects.

Assembly Name
Description
System.ServiceModel
Logs the following
Message Process
Reading of Configuaration information
Transport-level action
Security request.
System.Runtime.Serialization
Emits the information when objects are serialized or deserialized. WCF always serializes and de- serializes information during the request so it is good event to see the content of the request.
System.ServiceModel.IdentityModel
Generates trace data for authentication and authorization.


The tracing information of these objects help you to find out any exception details easily.

You can enable tracing by adding below code in web.config file.

<system.diagnostics>
    <trace autoflush="true" />
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true">
        <listeners>
          <add name="wcfTraceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="D:\logs\WcfTrace.svclog" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>

After adding the above code in web.config file, WCF trace file will be created in the given location when you run WCFservice.

To view the file you need SvcTraceViewer.exe, which will be present in “C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin folder.” Or else you can referrer to the below link to get tool.


Monday 2 April 2012

How to get detailed error description in SharePoint


By default SharePoint will display basic message to users this is useless when we are doing any trouble shooting to display complete error description and stack trace of the error you need to modify the web.config for the WebApplication.

We can achieve this by following below steps.

1)     Disable Custom Errors: Set the customErrors mode to "Off"

Find:

<system.web>
<customErrors mode="On" />

Change To:

<system.web>
<customErrors mode="Off" />


2)    Enable the Call Stack Trace: Set the CallStack value of the SafeMode element to "true"

Find:

<SharePoint>

<SafeMode ... CallStack="false" ... >

</SharePoint>


Change To:

<SharePoint>

<SafeMode ... CallStack="true" ... >

</SharePoint>


3)    Enable Debugging Mode: Set batch and debug to "true"

Find: <compilation batch="false" debug="false">
Change To: <compilation batch="true" debug="true">


Enable the ASP.NET tracing feature:
Include the following line in the <system.web> element of the web.config file.


<system.web> ...


<trace enabled="true" pageOutput="true"/>


Saturday 4 February 2012

Applying Conditional Formatting to a Data View

You can use conditional formatting to easily create a Data View that applies specific styles to data values when the data meets the criteria that you specify. You can also set conditions that change the visibility of a data value, so you can show or hide data.

To apply conditional formatting to a Data View
  • Right-click the Data View, and then click Conditional formatting.The Conditional Formatting task pane opens.
  • In the Data View list, click the items in the fields that contain the data you want to format.
  • Click Create, and then click Apply Formatting. The Condition Criteria dialog box opens to enable you to create a condition.
  • In the Condition Criteria dialog box, place your mouse pointer anywhere in the first row, and click.
  • Under Field name, click the arrow, and then click the field that you want to use in the condition.
  • Under Comparison, click the arrow, and then click the operator that you want to use in the condition.
  • Under Value, click the arrow, and then click More Fields.
  • In the More Fields dialog box, click the field that you want to use to complete the condition 
  • Click OK 
  • In the Condition Criteria dialog box, click OK.
  • In the Modify Style dialog box, select the options required to create the style for your conditional formatting.
  • Click OK.


Thursday 5 January 2012

Creating Search Scope in SharePoint 2007


1)     Goto Site Settings >>  Site Collection Administration >> Search Scope


2)     System will redirect to below “View Scopes” page and click on “New Scope”




3)     System takes you to below page, insert all required details Title etc. Click on Ok button, new scope will be created







4)     Adding rules to the scope.




5)     Give “Scope Rule Type” and “Behavior” and click on “Ok”.


6)     System redirect to the below page. And we have completed new scope with rules, this