Sunday, August 31, 2014

How to use log4net in SharePoint based Applications

How to use log4net in SharePoint based Applications


In my current project the requirement is to use log4net as the main logging mechanism to log the errors and exceptions generating from SharePoint based applications. Before this we have used log4net in many .Net based applications and that is pretty much simple to configure and to use. Unfortunately when we implemented log4net the same way in our SharePoint based projects, it failed miserably. So, we started googling and found this is a known issue but we are unable to find out a proper step by step solution to resolve the issue. Fortunately we find out some interesting facts and mechanism to overcome this issue in Mike Knowles bloghttp://mikeknowles.com/blog/2009/02/17/ConfiguringLog4netForSharePointWindowsAuthentication.aspx. So, we thought to collect all the information’s in a single place and to share with you guys. So, let’s start:

Step I

Create your own web app -> Site Collection -> Site.

Step II

Deploy the log4net DLL to the GAC.

Step III

Open your Site’s Web.Config file from Inetpub -> wwwroot -> wss -> virtual directories -> port-no -> web.config
Now, add an entry to the Web.config configSections to register the new configuration block:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />

Next, create a folder named ‘App_Data’ inside ‘Inetpub -> wwwroot -> wss -> virtual directories -> port-no’ folder. Inside App_Data create another folder named ‘Logs’ and inside ‘Logs’, create a text file named ‘RollingFileLog.txt’. Give full Control permission to these 3 file/ folders.
Now add the log4net configuration section to Web.config just prior to the system.web section.
<log4net debug="true">
    <appender name="GeneralLog" type="log4net.Appender.RollingFileAppender">
      <file value="App_Data\\Logs\\RollingFileLog.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value="yyyyMMdd" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d{dd MMM yyyy HH:mm:ss} [%p] %c - %m%n" />
      </layout>
      <securityContext type="log4net.Util.WindowsSecurityContext">
        <credentials value="Process" />
      </securityContext>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="GeneralLog" />
    </root>
  </log4net>

Now add log4net assembly information in the ‘SafeControl’ section:
<SafeControl Assembly="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" Namespace="log4net" TypeName="*" Safe="True" />

Step IV


Now open your Visual Studio solution. Right Click on the Solution Node and add a new project of type Class Library. Give it a proper name like ‘log4netModule’ as we are actually in a process of creating one HTTP Module. Add reference to log4net dll. Add a strong key into the project.
Add a class file or use the default one. Place the following code inside that file:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using log4net;
using log4net.Config;
using log4net.Util;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace XXX.log4netModule
{
    public class Initlog4netModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            XmlConfigurator.Configure();
        }

        public void Dispose()
        {            
        }        
    }
}

Compile it and copy the error free assembly from the source location.

Step V


Place assembly copied in the last step, inside the ‘bin’ folder present inside the ‘Inetpub -> wwwroot -> wss -> virtual directories -> port-no’ folder. And deploy the same copied assembly into the GAC.
Now, again we need to update the web.config file. Place the following line inside the ‘<httpModules>’ section present inside the ‘<system.web>’ section and modify it as per the name you have given to your project.
<clear />
<add name="Initlog4netModule" type="AZL.log4netModule.Initlog4netModule, AZL.log4netModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4f97192e309c5502" />

Step VI


Open the IIS7 Administration tool via the Start menu, typing in inetmgr.exe in the start/search box and pressing Enter. In the tool, double-click on your server node in the left-hand treeview, then expand the “Sites” node, and double-click on the site or application to which you would like to add your module and handler.
Select the “Modules” feature icon, then click the “Add Managed Module …” action, and in the resulting dialog box type in the module name (arbitrary) and then select the type in the dropdown box, as the tool will automatically load your assembly in bin and discover types that implement the IHttpModule interface. Press OK to add the module.
clip_image001[4]
Reset IIS.

Step VII


Now, open up your original solution in visual studio. In the desired page add a reference to the log4net assembly.
using log4net;

Next, to test if at all log4net is working or not, place the following lines inside your page load event:


ILog log = LogManager.GetLogger("TestLogger");
log.Debug("Error logged");

Save and compile and run the solution.
If you have followed all the steps perfectly, then the log file present inside the Logs folder should have the following entry:

“<Date Time>  [DEBUG] TestLogger - Error logged”

GAC add dll and add reference in ur application

In VS2010, from the Add Rerences window you can click 'Browse' and navigate to C:\Windows\Assembly and add references to the assemblies that you want. Please note that the files may be grouped under different folders like GAC, GAC_32, GAC_64, GAC_MSIL etc.

Friday, August 22, 2014

Add multiple Office templates to a document library

Create a content type for a document template
  1. Go to the top level of the site collection and select Site Settings from the Site Actions menu.
  1. Under the Galleries section of the Site Settings page, click Site content types.
  1. Click Create at the top of the Site Content Type settings page.
  1. On the New Site Content Type page, do the following:
  • Type “PowerPoint” in the Name field.
  • Type “Create new presentation in this library” in the Description field.
  • Select Document Content Types from the Select parent content type from drop down list.
  • Select Document from the Parent Content Type drop-down list.
  • Click OK.
  1. On the Site Content Types > PowerPoint page, under Settings, click Advanced Settings.
  1. In the Document Template section, select Upload a new document template, click Browse, and then double-click a PowerPoint slide or template that you want to use.
  1. Click OK.
Display the new template as a choice when creating new documents
  1. Navigate to the library to which you want to associate the new content types.
  1. On the Library tab of the ribbon, click Library Settings. If you are working with a list, click List Settings.
  1. Under General Settings, click Advanced Settings.
  1. In the Content Types section, click Yes under Allow management of content types, and then click OK.
  1. On the Library Settings page, under Content Types, click Add from existing site content types.
  1. On the Add Content Types page, select All Groups under Select site content types from.
  1. Under Available Site Content Types, look for and select the new content types to associate to this library and click Add.
  1. The next time you click New on the ribbon for the library you want to add items to, the new template content types appears as choices in the drop-down list.
Save your customized library as a template
  1. Go the Document Library that you want to save as a template.
  1. Under Library Tools in the ribbon, click the Library tab.
  1. In the Settings group of the ribbon, click Library Settings.
  1. Under Permissions and Management, click Save document library as template.
  1. Type the file name, the template name and template description in the fields provided.
  1. If you want document libraries created from this new Document library template to include the items already in the document library, select the Include Content checkbox.

 NOTE    You must be a site collection owner to successfully complete this procedure.
  1.  NOTE    Note that, by default, the New Word content type exists under the Group Work Content Types section. This is typically the choice that is available to you when adding a new document to any Document Library.
    1.  NOTE    You must have Microsoft Office installed in order to create Office generated documents.
    1.  NOTE    You can also add a new Excel, OneNote or Word template by repeating the above steps for each file type.
       NOTE    You can create multiple and different templates of the same file type.

    Now that you have created content types for your PowerPoint, OneNote, and Excel templates, you need to add the content types to a Document Library. This step ensures that they will appear as choices from the New Document command on the ribbon.
    1.  NOTE    You can multi-select content types by pressing the <CTRL> key while clicking on several content types in the list.

    Now that you have created content types for your PowerPoint, OneNote, and Excel templates and added them to the Document Library, you can save this library as a template. In this way, you won’t have to repeat the steps above if you want something similar for another Document Library.
     NOTE    You must have Designer permissions to accomplish this task.



    http://www.codeproject.com/Tips/440704/Document-Library-Enable-New-Document-Edit-Document

Wednesday, August 20, 2014

Get List of wsp files deployed in Central Admin

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Diagnostics;
//using ConsoleApplication1.ContactService;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ContactServiceClient serv = new ContactServiceClient();
                Console.WriteLine("started");
                SPSolutionCollection solutions = SPFarm.Local.Solutions;
                Console.WriteLine("1");
                foreach (SPSolution solution in solutions)
                {
                    Console.WriteLine("2");
                    SPPersistedFile wspFile = solution.SolutionFile;
                    wspFile.SaveAs("c:\\Projects\\" + solution.Name);
                    Console.WriteLine(solution.Name);
                }
                log("main", "main method---------" + "hello", "Information");
            }

            catch (Exception ex)
            {
                log("main", "Exception in PopulateForm() ; Exception message : " + ex.Message, "Error");
            }

            Console.ReadLine();
        }


        #region Log info

        public static void log(string IPAddress, string Message, string logType)
        {
            if (logType == "Warning")
            {
                EventLog.WriteEntry(IPAddress, "Message : " + Message, EventLogEntryType.Warning, 233);
            }
            else
                if (logType == "Error")
                {
                    EventLog.WriteEntry(IPAddress, "ExceptionMSG : " + Message, EventLogEntryType.Error, 233);
                }
                else
                    if (logType == "Information")
                    {
                        EventLog.WriteEntry(IPAddress, "ExceptionMSG : " + Message, EventLogEntryType.Information, 233);
                    }
        }


        #endregion
    }
}

how to set read only-properties-to-the-particular-info-path-form-control-based

If you select the field and go to the "Fields" pane, you can add a rule (a Formatting Rule in this case) to do the trick. You have actions to "Hide this control" or "Disable this control" and you can base those actions on conditions (e.g. who is currently logged in).

Tuesday, August 12, 2014

How to find the Config sharepoint DB

How to find the Config DB

Configuration database connection string is stored in Registry key. So sharepoint look for that entry to identify the database.

In Sharepoint 2007 you could see the config DB conection string in Following Registry Key

My Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\12.0\Secure\ConfigDb


In Sharepoint 2010 you could see the config DB conection string in Following Registry Key

My Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0\Secure\ConfigDb




The Next thing you have to find the Content DB attached to Web application.Here you have to remember one thing a web application could hold multiple site collection.So it will have multiple ContentDB


1. Go to Central Admin
2. Go to Application Management
2. Go to Database section and click on Manage Content Database
3. From the list Select your web Application
4.Click on the content DB  it will take to details page.
Content DB details page you could identify the DB Server

Monday, August 11, 2014

How to disable visual “dots” in Visual Studio

Edit -> Advanced -> untick View White Space.

implementing log4net

Here's a short tutorial on how to use log4net in C#

1. Get log4net from the apache website.

2. Open your project with visual studio.

3. Add the reference to your project: You find the reference in the zip that you just downloaded: \bin\net\xxx\release\log4net.dll. xxx is your .net version.

4. Add the Appender section to your app.config/webconfig. The following code uses a file for the logging:

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
  </configSections>
  <log4net>
    <root>
      <level value="DEBUG" />
      <appender-ref ref="LogFileAppender" />
    </root>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
      <param name="File" value="log-file.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>

5. Use the following code to use the configuration you just added to app.config:

static void Main()
{
      log4net.Config.XmlConfigurator.Configure();
...

6. To log use the following code:

using log4net;
...
private static readonly ILog log = LogManager.GetLogger(typeof(Bar));
log.Debug("this is the first log message");
...

7. If Visual studio doesn't recognize log4net. Configure your project like this:

Visual Studio -> project -> project name properties -> target framework -> .net Framework (not client)