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


Friday, 30 December 2011

Branding SharePoint 2007


1.     Challenges of Branding SharePoint
         Consistency
         Audience expectations
         Audience needs
         Internal buy-off of SharePoint
         Security; anonymous access vs. forms authorization
         Content Editing experience

2.     Simple and Advanced options
      Simple OOB  customization
      Update Logo
      Apply a Theme
      Adding web parts
      Choose a different OOB Master Page

      More advanced customization
      Master Pages
      Layout pages
      Creating custom themes
      CSS

      Simple OOB customization demonstration

      Update site with logo
      Change site theme
      Choose different Master Page Template
      Other master page templates are available for download
      Views in libraries
      Content editor web part (inline styling)

3.     Page Rendering

4.     Tools
      IE Developer Toolbar (free, from Microsoft)  
      FireFox Firebug (free)
      InstantSource
      SharePoint Designer

5.     Advance Customization: Master Pages
      What is a Master page?
      Navigation
      Logos
      Search box
      Login control
      Editing controls
      CSS References
      Content Regions

6.     Advanced Customization: Working with CSS
      There are 26 style sheets used in SharePoint
      Majority located on server:
      Server Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\STYLES
      Some located in Style Library (accessible via SPD)
      Editing core.css is NOT recommended
      Core.css will load last, unless you specify your custom css in Site Settings, or override the css in the master page


7.     Advance Customization: Custom Theme
      Does NOT require SharePoint Designer
      Themes can be found on the server in:
      Server Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\THEMES\[Theme Name]
      Copy folder, rename
      Rename .INF file, change theme names in .INF file
      Modify theme.css with design changes
      Store preview of theme in TEMPLATE\IMAGES
      Modify TEMPLATE\Layouts\1033\spthemes.xml

8.     Advance Customization: Layout Pages
      What is a Layout Page?
      Template for content
      Based on a content type

      Holds:
      Field controls
      Web Parts
      Web Part Zones
      Custom CSS, in-line styles
      Careful when editing; don’t rely on “Reset to Site Definition”; make a backup first
      Override content placeholders
      Add web part zones
      Configure web part zones
      Add web parts
      Either in or out of web part zones
      Insert content fields
      Configure content fields
      If need more content fields, will need to create a new content type
      Pages based upon a page layout will be able to switch to another page layout that uses the same content type as the original page layout

9.     Advance Customization: Content Editor WP Styles
      If NOT using theme: edit HTML Editor CSS
      Make a copy from the server, save in Style Library
      Add styles (prefix with “.ms-rteCustom-”; e.g., .ms-rteCustom-FabrikamTitle)
      Register css in master page
      New styles will appear in  Content Editor Style dropdown
      If you are using a theme, you can add the styles you like into your theme’s css file.

10. Advance Customization: Search Results
      Create new page
      Use Search Results Page Layout (this page layout can be customized if the layout needs to be changed)
      Or create your own custom search results page
      Customize new page
      Search control
      Search results xslt
      Go to Site Settings, Search Settings and point to this new page

11. Advance Customization: Search Control
      Modify CSS
      Import customized search control from search results page
      On search results page, customize the search control, then export the web part
      Import web part into master page
      More difficult to customize from the master page since it is a web part
      Modify search results control properties
      Copy search control from blueband.master
      Register control
      Modify tag properties of control

12. Customized vs. Uncustomized
      “Ghosted” and “Unghosted pages”
      Performance impact of ~10%