Search This Blog

Thursday, March 19, 2015

Writing Errors to Sharepoint Logs/Download WSP Solution from SharePoint/Sharepoint Access Denied Page


Sharepoint 2010 has provided us with an API for writing to the default ULS log file in which Sharepoint writes its logs. To do this you can make use of the SPDiagnosticsService which is available in 
Microsoft.SharePoint.Administration namespace.


try
   {
    //execute your code
   }
   catch (Exception ex)
   {
    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("YourCustomKey",TraceSeverity.Medium, EventSeverity.Error), TraceSeverity.Monitorable, ex.Message, ex.StackTrace);
    }
}


Download WSP Solution from SharePoint


Once a solution has been added to SharePoint, then there's no way to download it. Using the SharePoint object model we can easily download a WSP using the 'SaveAs' method. 
The C# code below illustrates how to download all of the solutions in the farm with just a few lines.

private void DownLoadAllSolutions()
       {
            SPSolutionCollection wspSolutions = SPFarm.Local.Solutions;
            foreach (SPSolution solution in wspSolutions)
            {
SPPersistedFile wspFile = solution.SolutionFile;
DownLoadWSP(wspFile);
            }
        }
        private void DownLoadWSP(SPPersistedFile wspFile)
{
    if (wspFile != null)
    {
string wspFileName = Path.Combine(@"c:\temp",wspFile.Name);
                if(File.Exists(wspFileName))
{
File.Delete(wspFileName);
}
wspFile.SaveAs(wspFileName);
}
}

Sharepoint Access Denied Page

Sometimes in your web part pages you may want to show the same "Access Denied" screen to the user that SharePoint provides by default when user has no access to any resource or page.
This can be easily achieved by making use of SPUtility Class of sharepoint as:
            try             {                //your custom code                SPUtility.HandleAccessDenied(new Exception("not authorized"));             }             catch (Exception Ex)             {             }

No comments:

Post a Comment