Showing posts with label SharePoint Server. Show all posts
Showing posts with label SharePoint Server. Show all posts

Wednesday, July 30, 2014

Handling SharePoint exception in ULS log and SharePoint List

Adding log to ULS and also adding to sharepoint list

// adding log to ULS log
public class ULSLogService : SPDiagnosticsServiceBase
    {
        private static string PRODUCT_NAME = "Biraj_Blog";

        private ULSLogService() : base("Biraj Logging Service", SPFarm.Local) { }
        private static ULSLogService logSerivce;
        public static ULSLogService LogSerivce
        {
            get
            {
                if (logSerivce == null)
                {
                    logSerivce = new ULSLogService();
                }
                return logSerivce;
            }
        }

        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>{
             new SPDiagnosticsArea(PRODUCT_NAME, new List<SPDiagnosticsCategory>{
                 new SPDiagnosticsCategory("Biraj_Info", TraceSeverity.Verbose, EventSeverity.Information),
                 new SPDiagnosticsCategory("Biraj_Error", TraceSeverity.Unexpected, EventSeverity.Warning),
             })
             };
            return areas;
        }

        public static void DisplayInfo(string ClassMethodName, Exception ex)
        {
            SPDiagnosticsCategory category = ULSLogService.LogSerivce.Areas[PRODUCT_NAME].Categories["Biraj_Info"];
            ULSLogService.LogSerivce.WriteTrace(0, category, TraceSeverity.Verbose, ClassMethodName + " \n-- " + ex.TargetSite + " \n-- " + ex.Message + " \n-- " + ex.StackTrace + " \n-- " + ex.Source + " \n-- " + ex.Data);
            Logs.AddIntoList("Info", ClassMethodName, ex);
        }

        public static void DisplayError(string ClassMethodName, Exception ex)
        {
            SPDiagnosticsCategory category = ULSLogService.LogSerivce.Areas[PRODUCT_NAME].Categories["Biraj_Error"];
            ULSLogService.LogSerivce.WriteTrace(0, category, TraceSeverity.Unexpected, ClassMethodName + " \n-- " + ex.TargetSite + " \n-- " + ex.Message + " \n-- " + ex.StackTrace + " \n-- " + ex.Source + " \n-- " + ex.Data);
            Logs.AddIntoList("Error", ClassMethodName, ex);
        }

    }


// adding log to SharePoint List
public static void AddIntoList(string Title, string ClassMethodName, Exception exception)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb spWeb = spSite.OpenWeb())
                        {                           
                            try
                            {
                                spWeb.AllowUnsafeUpdates = true;
                                SPList logsList = spWeb.Lists.TryGetList("Logs");
                                SPListItem newItem = logsList.Items.Add();
                                newItem["Title"] = Title;
                                newItem["MethodName"] = ClassMethodName;
                                newItem["TargetSite"] = exception.TargetSite;
                                newItem["Message"] = exception.Message;
                                newItem["Source"] = exception.Source;
                                newItem["StackTrace"] = exception.StackTrace;
                                newItem["Data"] = exception.Data;   
                                
                                newItem.Update();
                                spWeb.AllowUnsafeUpdates = false;
                            }
                            catch(Exception ex)
                            {
                                
                            }                           
                        }
                    }
                });
            }
            catch (Exception ex)
            {
               
               
            }
        }

Monday, January 27, 2014

Programmatically create folder if not exists and resize and upload image into sharepoint document library

SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite sysSite = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (SPSite oSite = new SPSite(SPContext.Current.Site.Url, sysSite.SystemAccount.UserToken))
                        {
                            using (SPWeb oWeb = oSite.OpenWeb())
                            {

                                oWeb.AllowUnsafeUpdates = true;
                                if (radAsyncUpload1.UploadedFiles.Count > 0)
                                {
                                    string sFolderName = "MatrimonialThumbnail";
                                    sFileName = Convert.ToString(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")).Replace("/", "").Replace(" ", "").Replace(":", "") + "_EIcon" +  radAsyncUpload.UploadedFiles[0].GetExtension();
                                    byte[] m_byt = new byte[radAsyncUpload1.UploadedFiles[0].ContentLength + 1];

                                    using (System.IO.FileStream fStream = (System.IO.FileStream)radAsyncUpload1.UploadedFiles[0].InputStream)
                                    {
                                        byte[] contents = new byte[fStream.Length];
                                        fStream.Read(contents, 0, (int)fStream.Length);
                                        SPList lstPublicImage = oWeb.Lists["Public"];
                                        SPFolder subFolder = null; //oWeb.Lists["Public Images"].RootFolder;

                                        bool folderExists = false;
                                        // Check to see if folder already exists, if not create it
                                        for (int i = 0; i < lstPublicImage.Folders.Count; i++)
                                        {
                                            if (string.Compare(lstPublicImage.Folders[i].Folder.Name.ToLower(), sFolderName.ToLower()
                                                , true) == 0)
                                            {
                                                subFolder = lstPublicImage.Folders[i].Folder;
                                                folderExists = true;
                                            }
                                        }
                                        if (!folderExists)
                                        {
                                            SPFolderCollection _folders = lstPublicImage.RootFolder.SubFolders;
                                            _folders.Add(oWeb.Lists["Public"].RootFolder.Url + "/" + sFolderName);
                                            lstPublicImage.Update();

                                            subFolder = lstPublicImage.Folders[lstPublicImage.Folders.Count - 1].Folder;
                                        }
                                        SPFile sps = null;
                                        // resize image
                                        System.Drawing.Image originalImage = null;
                                        originalImage = System.Drawing.Image.FromStream(fStream);
                                        if (originalImage.Width > 24 || originalImage.Height > 24)
                                        {
                                            System.Drawing.Image thumbnail = null;                                                                    
                                            MemoryStream msOut = new MemoryStream();
                                            thumbnail = originalImage.GetThumbnailImage(22, 22, null, IntPtr.Zero);
                                            thumbnail.Save(msOut, System.Drawing.Imaging.ImageFormat.Png);
                                            sps = subFolder.Files.Add(sFileName, msOut, true);
                                        }
                                        else
                                        {
                                            sps = subFolder.Files.Add(sFileName, fStream, true);
                                        }
                                        //                                       
                                        sps.Update();

                                    }
                                }
                                oWeb.AllowUnsafeUpdates = false;
                            }
                        }
                    }

                });

Tuesday, June 11, 2013

CreateChildControls EnsureChildControls RenderControl

CreateChildControls intended to build control – receives and process their events and go through page life cycle.

The EnsureChildControls method ensures that the CreateChildControls method has finished executing. If not, it waits for that method to complete. this.EnsureChildControls();

RenderControl method should only render final html. RenderControl - Outputs server control content and stores tracing information about the control if tracing is enabled.
Do NOT use Render method as it will break sharepoint DOM (break webpart html rendering table)

Thursday, May 30, 2013

SharePoint + Asp.Net Concept - Session State - Catching





Three kinds of session state information: (1) sensitive (2) non-sensitive (3) cached

Several strategies can be used to manage session state data, but each has limitations: in-process state management, synchronized state management, and leveraging the state management possible on the client.

in-process state management that ASP.NET provides. This approach performs well if there is only one server in the farm. However, this issue can be mitigated if the load balance is set for sticky sessions. A sticky session setting keeps users on one server, reducing the probability that a user will transition from one server to another and not have their state information available. The main concern with the approach of keeping the session data in in-process memory is that transitioning to another state management approach is difficult because every other form of session management requires that the object be realizable.

synchronized state management, all session information is stored and retrieved from a centralized
location. This solves the potential problem of having out-of-sync information across servers. There are two approaches to a synchronized, or centralized, state management. The first approach to synchronized state management is to use an in-memory cache, but the problem with it is that at some point the server managing the information must be rebooted. The second approach is to use a database for synchronization, but the database induces delay and its own performance problems.

server-client, you transmit the state back to the client. The challenges with this strategy are that sensitive information must be encrypted (adding overhead), and that the link speed between the server and client is typically the slowest part of the system.

SharePoint and Memory






Every SPSite or SPWeb object is approximately 2MB in size.

SharePoint can implement two key types of in-memory cache: (1) output caching (2) object caching.

Output caching is an ASP.NET feature that can be configured in SharePoint to provide caching of the
output of Web pages. In this process, the page is processed only once and returned so that second user to access a page receives a copy of what executed when the first user came to the page. Output caching is appropriate for anonymous sites but not appropriate when the page has personalized content. In addition to returning the pages to the user more quickly for the second and subsequent requests, output caching reduces the CPU and database load on the farm because the requests aren’t being processed repeatedly.
However, this comes at the expense of a greater amount of memory being required on the server to
support the additional caching.

Object caching operates at a data level and is designed to improve performance of data operations. The object level cache can be a substantial improvement in scalability and performance. However, just like the output cache, the object cache consumes memory—memory that might be necessary for other operations.

From a session state perspective, SharePoint Server creates and configures a shared SQL session state
database, providing for synchronized session state. Because of this, an additional SQL Server load is placed for each object added to the user’s session state. SharePoint Foundation will, by default, not use session state.