Pages

Wednesday 19 February 2014

Creating Error-log in C# to write errors in Event Viewer as well in directory.

ErrorLog.CS

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Application1
{
    public class ErrorLog
    {
        public class ErrorLog
        {
            /// <summary>
            /// WriteToEventLog
            /// </summary>
            /// <param name="message"></param>
            /// <param name="sourcename"></param>
            /// <param name="logName"></param>

            #region WriteToEventLog
            public void WriteToEventLog(string message, string sourcename, string logName, EventLogEntryType ErrorType)
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        EventLog elog = new EventLog();
                        if (!EventLog.SourceExists(sourcename))
                        {
                            EventLog.CreateEventSource(sourcename, logName);
                        }
                        elog.Source = sourcename;
                        elog.Log = logName;
                        elog.EnableRaisingEvents = true;
                        elog.WriteEntry(message, ErrorType);
                    });
                }

                catch (Exception ex)
                {
                    writeErrors(ex.ToString());
                }
            }
            #endregion

            /// <summary>
            /// writeErrors
            /// </summary>
            /// <param name="msg"></param>

            #region writeErrors
            public void writeErrors(string msg)
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        string dir = @"c:\\ Error LOG";
                        Directory.CreateDirectory(dir);
                        TextWriter tw = new StreamWriter(@"c:\\ Error LOG\Error.txt", true);
                        tw.WriteLine(System.DateTime.Now.ToString() + "  Error : " + msg);
                        tw.Close();
                    });
                }
                catch (Exception ex)
                {
                    //writeErrors(ex.ToString());

                }
            }
            #endregion
        }
    }
}

 

Application1.cs 

Creating Error Log  variables 
      #region ErrorLog Variables
        public string sourceName = "Application1";
        public string logName = "Application";
        ErrorLog el = new ErrorLog();
        #endregion

Writing ErrorLog method
 /// <summary> ErrorLogMethod
        /// ErrorLogMethod
        /// </summary>
        /// <param name="ex"></param>

        private void ErrorLogMethod(Exception ex)
        {
            //Catching error in Event viewer
            el.writeErrors(ex.ToString());
            el.WriteToEventLog(ex.ToString(), sourceName, logName, EventLogEntryType.Error);
            //Displaying the Error Message   
             lblerror.Text = ex.Message;
         }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
            }
           catch (Exception ex)
            {
                ErrorLogMethod(ex);
            }
        }

Tuesday 18 February 2014

WebPart appears to be causing a problem. Cannot use a leading... to exit above the directory.

Sharepoint WebPart appears to be causing a problem. Cannot use a leading... to exit above the directory.

Reason :
 You have given your image path as ... /_layouts/15/images/Solution1/error.png with dots. It has to be removed.
Correct Format : /_layouts/15/images/Solution1/error.png - remove the dots before the _layouts extension. Now the problem has been solved.... I hope it works....

Friday 14 February 2014

Register an assembly as a safe control in the Web.config file

In order for you to use your own custom assembly with your web parts and other little bits, you will need to add your safe control to the web.config file.  However, you need to think "WEB FARM" with many servers hosting the web application so I will show you a couple ways to do this.

The entry in the web.config

You need to place a SaveControl element entry into the web.config file of the web application.  The entry looks like the following:
   1: <configuration>
   2:   <SharePoint>
   3:     <SafeControls>
   4:       <SafeControl Assembly="[Assembly Name]" Namespace="[Namespace]" TypeName="*" Safe="True" />
   5:     </SafeControls>
   6:   </SharePoint>
   7: </configuration>
Assembly The name of your assembly needs to added to this section. Although you can simply type the name of the DLL hosting the control into the Assembly element, it is important to not that this is not the recommended practice.  Rather, use a full four part name; i.e. [assembly], version=[version], culture=[culture], publickeytoken=[publickeytoken]Namespace The namespace that your web controls are in.  If you have your controls in multiple namespaces, you will need to add one <SafeContol ...> element for each control.TypeName The name of the web control which is allowed to be executed with the SharePoint web application.  Should your namespace have multiple web controls, you do not need to register each control.  You can simply use * (asterisk) to indicate the dll.Safe A boolean flag, indicating whether the control is treated as safe (true) or unsafe (false). AllowRemoteDesignerA boolean flag, indicating whether the control can be loaded by a remote designer, such as SharePoint Designer.
Sample
   1: <SafeControl Assembly="Brett.DemoParts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f03e5f7a44d50a3a" 
   2:              Namespace="Brett.SharePoint.WebParts" 
   3:              TypeName="*" 
   4:              Safe="True" 
   5:              AllowRemoteDesigner="True" />

Methods of updating the web.config file

There are three ways you can update the web.config file,
  • Manually adding the SafeControl to the web.config
  • Adding the SafeControl to the web.config with code
  • Deploy the assembly using a solution package

Manually editing the web.config (bad)

This approach may sound the easiest and quickest way as you simply open up your favourite xml editor, find the <SafeControls> element and add your own control into it.
WARNING! If you do it this way, you are looking for trouble in a farm as you will need to remember to change the web.config modification for all your servers in the farm as well as all the web applications on the farm that use the custom control.  So should you have a really awsome web part that is used within 5 web applications hosted on your farm of 3 servers, you will need to make the modification to 15 web.config's .. have fun.
Also should you add a new server to your farm, please remember to add the entry the web.config.
Bottom line, this is the worst possible way you can do it  and stay away from doing it this way

Adding the SafeControl to the web.config with code (good)

SharePoint provides a class called SPWebConfigModification which has a set of modification commands in a collection.  These modification commands are applied to the default web.config of the Web Application.  These configuration modification commands will also be added and applied to all servers in a farm.   Finally, should a new server be added to the farm, these modifications will also be applied.
The following code could be added to the FeatureActivated override method in your feature that deploys the web part.
   1: public override void FeatureActivated(SPFeatureReceiverProperties properties) 
   2: {
   3:     // A reference to the features Site Collection
   4:     SPSite site = null;
   5:  
   6:     // Get a reference to the Site Collection of the feature
   7:     if (properties.Feature is SPWeb)
   8:     { site = ((SPWeb)properties.Feature.Parent).Site; }
   9:     else if (properties.Feature.Parent is SPSite)
  10:     { site = properties.Feature.Parent as SPSite; }
  11:  
  12:     if (site != null)
  13:     {
  14:         SPWebApplication webApp = site.WebApplication;
  15:  
  16:         // Create a modification
  17:         SPWebConfigModification mod = new SPWebConfigModification(
  18:             "SafeControl[@Assembly=\"MyAssembly\"][@Namespace=\"My.Namespace\"]"
  19:                 + "[@TypeName=\"*\"][@Safe=\"True\"][@AllowRemoteDesigner=\"True\"]"
  20:             , "/configuration/SharePoint/SafeControls"
  21:             );
  22:  
  23:         // Add the modification to the collection of modifications
  24:         webApp.WebConfigModifications.Add(mod);
  25:  
  26:         // Apply the modification
  27:         webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
  28:     }
  29: }

Deploy the assembly using a solution package (best)

The preferred way to provision your features, web parts and assemblies is by creating a Solution Package (.wsp file).  You will add add your assembly, the manifest.xml file and all your other components and resources into the cabinet.
You will need to add the following entry into the manifest.xml
   1: <Solution SolutionId="{1E0FDA58-6611-423a-92EC-8E7355810CEE}"
   2:           xmlns="http://schemas.microsoft.com/sharepoint/">
   3:   <FeatureManifests  />
   4:   <ApplicationResourceFiles />
   5:   <CodeAccessSecurity />
   6:   <DwpFiles />
   7:   <Resources />
   8:   <RootFiles />
   9:   <SiteDefinitionManifests />
  10:   <TemplateFiles />
  11:   
  12:    <Assemblies>
  13:       <Assembly DeploymentTarget="WebApplication" Location="Brett.DemoParts.dll">
  14:          <SafeControls>
  15:             <SafeControl Assembly="Brett.DemoParts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f03e5f7a44d50a3a"
  16:                          Namespace="LitwareWebParts" 
  17:                          TypeName="*" 
  18:                          Safe="True"                         
  19:                          />
  20:          </SafeControls>
  21:       </Assembly>
  22:    </Assemblies>
  23: </Solution>
  24:  
Key highlights
DeploymentTarget The depoloyment target is location where the assembly will be copied to and can ether be the bin folder of the WebApplication or it could be the GlobalAssemblyCache (GAC)Location The location of the assembly within the cabinet file. SafeControl A SafeControl element entry as described at the beginning of the post.   
Using this method, your assembly will be correctly deployed the servers in the farm as well as added to the safe controls of the web application.  Again any new server added to the farm will automatically get all the solution packages deployed.
Reference :

Tuesday 11 February 2014

Sign in as Different User and SharePoint 2013



This “Sign in as Different User” menu item is very useful when testing applications, but it can lead to problems especially when opening documents, say in Microsoft Word. So, it may be for these reasons that the option has been removed in SharePoint 2013.
You can add the menu item back in, but I would suggest only doing this on test or development SharePoint servers. To do this, repeat this edit on all servers in your SharePoint farm:
  • Locate the file \15\TEMPLATE\CONTROLTEMPLATES\Welcome.ascx and open in a text editor.
  • Add the following element before the existing element with the id of “ID_RequestAccess”:
<SharePoint:MenuItemTemplate runat="server" ID="ID_LoginAsDifferentUser"
 Text="<%$Resources:wss,personalactions_loginasdifferentuser%>"
 Description="<%$Resources:wss,personalactions_loginasdifferentuserdescription%>"
 MenuGroupId="100"
 Sequence="100"
 UseShortId="true"
 />

  • Save the file.
Now, the menu item shall be displayed:

http://nickgrattan.files.wordpress.com/2012/07/login1.png

Difference Between Classic based Claim based and Form based authentication.

Classic Based Authentication
  • You cannot configure the Forms based authentication if your web application is using Classic Mode Authentication.You can convert a web application from Classic Mode Authentication to Claims Based Authentication. However, that can only be done using PowerShell commands and its an irreversible process.
  • Classic authentication supports authentication types like Kerberos, NTLM,  anonymous.
  • Classic is more commonly seen in 2007 environments.
Claim Based Authentication
  • It enables authentication from windows as well as non-windows based systems. This also provides the capability to have multiple authentication in a single URL.
  • Claims based authentication uses claims identities against a against a trusted identity provider.
  • Claims are the recommended path for new deployments in SharePoint 2010.
Form Based Authentication
  • Forms-based authentication is used when we use Claim based authentication. Forms-based authentication is used to implement customized logic for authenticating users without having to worry about session management using cookie.
  • It gives developer more access to specify which files on the site can be accessed and by whom, and allows identification of a login page.

Monday 10 February 2014

Karu.Karthi: SharePoint 2013:Configure RDLC report with Report ...

Karu.Karthi: SharePoint 2013:Configure RDLC report with Report ...: Here are the steps to configure the SharePoint for report:         First find the following line in AppSettings in your web.config ...

SharePoint 2013:Configure RDLC report with Report Viewer



Here are the steps to configure the SharePoint for report:
        First find the following line in AppSettings in your web.config file and comment it out as shown below:
<!--<add key="ReportViewerMessages" value="Microsoft.SharePoint.Portal.Analytics.UI.ReportViewerMessages, Microsoft.SharePoint.Portal, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />-->


     Enable session at page level by setting the enableSessionState to true of <page…..> tag inside system.web.
<pages enableSessionState="true" enableViewState="true" enableViewStateMac="true" validateRequest="false" ……………………=""


       SharePoint disable the default session module inside the <system. Webserver>\modules tag. To enable the module comment out the following line inside <system. Webserver>\modules as shown below:
<!--<remove name="Session" />-->


Now if you try to put a report viewer control you will find a message like below:


If you find the above error then follow the steps 4, 5 and6:
      Add the following tag inside system.web\httphandlers section
<system.web>
    <httpHandlers>
      <add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
    </httpHandlers>
<customErrors mode="Off" />

     Add the following line in the system. Webserver\handlers
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />

    Comment out the following line in the system. Webserver\httphandlers (If Exists)
      <!--<add name="ReportViewerWebControl" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />-->

And finally it worked………..

     I got an error while viewing the Report in sharepoint Page
                   

Issue: Report execution in the current AppDomain requires Code Access Security policy, which is off by default in .NET 4.0 and later. Enable legacy CAS policy or execute the report in the sandbox AppDomain.



To resolve this issue –

Add the following line to the web.config
...
<trust level="Full" legacyCasModel="true" />
...
</system.web>