Monday, 12 March 2018

Timer Job in SharePoint 2013

What a SharePoint Timer Job is
A Timer Job is a periodically executed task inside SharePoint Server. It can do various tasks within the SharePoint environment on a scheduled time event basis.
Create Timer Job step-by-step
  1. Open the Visual Studio 2012.
  2. Click New Project.
  3. Select the Empty SharePoint Solution Template.


  4. Select Deploy as Farm Solution.


  5. Add a new class to the project and provide the name (TimerJobDemo.cs). 


  6. To do this, right-click on the project name in Solution Explorer, select Add -> New Item. Under the C# category select the Code tab, select Class and provide the class name. TimerJobApplication -> Add -> New Item -> Class.
  7. Derive this TimerJobDemo from the SPJobDefinition class.
  8. You need to add the following statements to do this.
    1. using Microsoft.SharePoint;  
    2. using Microsoft.SharePoint.Administration;  
    3. public class TimerJobDemo:SPJobDefinition  
    4. {  
    5. }  
  9. Add the following three constructors to your class.
    1. public TimerJobDemo():base()  
    2. {   
    3. }  
    4.   
    5. public TimerJobDemo (string jobName, SPService service) : base(jobName, service, null, SPJobLockType.None)  
    6. {  
    7.     this.Title = "Demo Timer Job";  
    8. }  
    9.   
    10.   
    11. public TimerJobDemo(string jobName, SPWebApplication webapp) : base(jobName, webapp, null, SPJobLockType.ContentDatabase)  
    12. {  
    13.     this.Title = "Demo Timer Job";  
    14. }  
  10. Override the Execute() method to do your stuff. Whenever the timer job executes, it will run the code written inside the Execute() method.
    1. SPWebApplication webApp = this.Parent as SPWebApplication;  
    2. SPList taskList = webApp.Sites[0].RootWeb.Lists["TimerLists"];  
    3. SPListItem newTask = taskList.Items.Add();  
    4. newTask["Title"] = "Job runs at " + DateTime.Now.ToString();  
    5. newTask.Update();  
Register the Timer Job Definition
Use the following the procedure to register the Timer Job Definition:
  1. Add a new feature to register our custom timer job.
  2. Right-click on Features inside the project in the Solution Explorer and click "Add Feature".


  3. Rename this feature to TimerJobFeature.
  4. Select the scope of the Timer job as “WebApplication”.


  5. Open the Feature properties and set “Active On Default” to “False”.


  6. Right-click on the “TimerJobFeature” and select “Add Event Receiver”.


  7. Uncomment the FeatureActivated and FeatureDeactivating methods and write the code as in the following.
    1. const string JobName = "Demo Job";  
    2. public override void FeatureActivated(SPFeatureReceiverProperties properties)  
    3. {  
    4.     try  
    5.     {  
    6.         SPSecurity.RunWithElevatedPrivileges(delegate()  
    7.         {  
    8.             SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;                      
    9.             DeleteExistingJob(JobName, parentWebApp);  
    10.             CreateJob(parentWebApp);  
    11.         });  
    12.     }  
    13.     catch (Exception ex)  
    14.     {  
    15.         throw ex;  
    16.     }  
    17. }  
    18. private bool CreateJob(SPWebApplication site)  
    19. {  
    20.     bool jobCreated = false;  
    21.     try  
    22.     {  
    23.         TimerJobDemo job = new TimerJobDemo(JobName, site);  
    24.         SPMinuteSchedule schedule = new SPMinuteSchedule();  
    25.         schedule.BeginSecond = 0;  
    26.         schedule.EndSecond = 59;  
    27.         schedule.Interval = 15;  
    28.         job.Schedule = schedule;  
    29.   
    30.         job.Update();  
    31.     }  
    32.     catch (Exception)  
    33.     {  
    34.         return jobCreated;  
    35.     }  
    36.     return jobCreated;  
    37. }  
    38. public bool DeleteExistingJob(string jobName, SPWebApplication site)  
    39. {  
    40.     bool jobDeleted = false;  
    41.     try  
    42.     {  
    43.         foreach (SPJobDefinition job in site.JobDefinitions)  
    44.         {  
    45.             if (job.Name == jobName)  
    46.             {  
    47.                 job.Delete();  
    48.                 jobDeleted = true;  
    49.             }  
    50.         }  
    51.     }  
    52.     catch (Exception)  
    53.     {  
    54.         return jobDeleted;  
    55.     }  
    56.     return jobDeleted;  
    57. }  
    58.   
    59. public override void FeatureDeactivating(SPFeatureReceiverProperties properties)  
    60. {  
    61.   
    62.     lock (this)  
    63.     {  
    64.         try  
    65.         {  
    66.             SPSecurity.RunWithElevatedPrivileges(delegate()  
    67.             {  
    68.                 SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;  
    69.                 DeleteExistingJob(JobName, parentWebApp);  
    70.             });  
    71.         }  
    72.         catch (Exception ex)  
    73.         {  
    74.             throw ex;  
    75.         }  
    76.     }  
    77. }  
Deployment and Debug
  1. Right-click on the project name in your Solution Explorer and select Deploy.
  2. After successfully deploying it, activate the feature .
  3. Open Central Administration and select Manage Web Application.


  4. Select your web application.
  5. Select the "Manage Feature" tab on the ribbon control.


  6. The pop up window will display all your application scoped features. Find the feature that we have created here and activate it.


  7. After activating the feature, the timer job will be registered. To see a list of all the registered timer jobs, go to Central Administration and select "Monitoring->Review job definitions".


  8. Select the web application and find the job.

Timer Job Debugging
  1. For debugging the Execute() method, press CTRL+ALT+P and select the process "OWSTIMER.EXE" and click Attach.
Note: Whenever you make any code changes and re-deploy the solution, restart the Timer Service too. This will reduce your debugging time with strange issues.

SharePoint Event Receivers

Event Receiver is an important feature of SharePoint. The use of Event Receiver is to handle the events. It is like a method that is triggered when an action occurs on a specified SharePoint object. Triggering actions have some activities including,
  1. Adding
  2. Updating
  3. Deleting
  4. Moving
  5. Checking In
  6. Checking Out.
We may need to perform some actions like notifying the person who created the list item, or deleted it. By using Event Receivers, we can easily maintain the secured data in SharePoint.

Example

There is a Document Library and the full permission has been given to your Manager. So, we need to configure that document library in a manner that if anyone is trying to add a document in a library, your manager will get an alert like "someone is trying to add documents in library. We need you approval. " Once your Manager approves, then only the user can add a document in library.

Once a user has added a document in a library, an auto-generated message will be sent to your manager. At this time, we require Event Receiver to do this thing.

Types of Event Receiver
There are two types of Event Receiver in SharePoint,
  1. Synchronous Event Receiver
  2. Asynchronous Event Receiver
Synchronous Event Receiver or Before Event Receiver
Before events fire before the corresponding event action occurs and before SharePoint has written any data to the content database.

Asynchronous Event Receiver or After Event Receiver
After events fire after the event action has completed and after SharePoint has written to the content database to commit the event action. After events do not support cancelling the event action. A common example is sending out email notifications to let all the members of a site know when a new document has been uploaded.

Classes of SharePoint Event Receiver
  • Base class: Microsoft.SharePoint.SPEventReceiverBase.
  • Base class for List Item: Microsoft.SharePoint.SPItemEventReceiver
  • Base class for SharePoint List: Microsoft.SharePoint.SPListEventReceiver
  • Base class for Email: Microsoft.SharePoint.SPEmailEventReceiver
We can use the event to perform the following activities
  • Validate the Item
  • Log the information
  • Create associated items
Event Receiver Base Classes
  • SPItemEventReceiver
  • SPListEventReceiver
  • SPEmailEventReceiver
  • SPWebEventReceiver
  • SPWorkflowEventReceiver

Sunday, 28 January 2018

OOPS Concepts


Class

 It is a collection of objects.

Object

Objects are the basic run-time entities of an object-oriented system. They may represent a person, a place or any item that the program must handle. 
Encapsulation
·         Wrapping up a data member and a method together into a single unit (in other words class) is called Encapsulation.
·         Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.
·         Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is the property of encapsulating members and functions.
·         Encapsulation is a technique used to protect the information in an object from another object.
Abstraction
·         Abstraction is "To represent the essential feature without representing the background details."
·         Abstraction is a process of hiding the implementation details and displaying the essential features.
·         Abstraction is a mechanism to provide the essential features without describing the background details. Means provide the functions to access the hidden (private) data.
·         The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs.

The Differences between Abstraction and Encapsulation

Abstraction
Encapsulation
1. Abstraction solves the problem at the design level.
1. Encapsulation solves the problem at the implementation level.
2. Abstraction hides unwanted data and provides relevant data.
2. Encapsulation means hiding the code and data into a single unit to protect the data from the outside world.
3. Abstraction lets you focus on what the object does instead of how it does it
3. Encapsulation means hiding the internal details or mechanics of how an object does something.
4. Abstraction: Outer layout, used in terms of design.
For example:
An external of a Mobile Phone, like it has a display screen and keypad buttons to dial a number.
4. Encapsulation- Inner layout, used in terms of implementation.
For example the internal details of a Mobile Phone, how the keypad button and display screen are connected to each other using circuits.


Polymorphism
Polymorphism means one thing in many forms. Basically, polymorphism is a capability of one object to behave in multiple ways. Example: A man role changes at home, college, and outside the home. There are following types of polymorphism:
1.       Static polymorphism (compile time): It is achieved using function overloading and operator overloading.
2.       Dynamic polymorphism (runtime time): It is achieved using function overriding means using the virtual function.
Polymorphism provides following features: 
  • It allows you to invoke methods of the derived class through base class reference during runtime.
  • It has the ability for classes to provide different implementations of methods that are called by the same name.

Polymorphism is of two types: 
  • Compile time polymorphism/Overloading
  • Runtime polymorphism/Overriding

Compile Time Polymorphism 
Compile time polymorphism is a method and operators overloading. It is also called early binding. 
In method overloading method performs the different task at the different input parameters. 

Runtime Time Polymorphism 
Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding. 
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype.

Sealed Class

What is the use of sealed classes in c#? Generally, if we create classes we can inherit the properties of that created class in any class without having any restrictions. In some situation, we will get requirement like we don’t want to give permission for the users to derive the classes from it or don’t allow users to inherit the properties from the particular class in that situations what we can do? 
For that purpose, we have a keyword called “Sealed” in OOPS. When we defined class with keyword “Sealed” then we don’t have a chance to derive that particular class and we don’t have permission to inherit the properties from that particular class.

Method Hiding( new keyword)

Method hiding in C# is similar to the function overriding feature in C++. Functions of the base class are available to the derived class. If the derived class is not happy, one of the functions available to it from the base class can define its own version of the same function with the same function signature, just differing in implementation. This new definition hides the base class definition.

Virtual and Overridden Methods

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
    using System;
    namespace Polymorphism
    {
        class A
        {
            public virtual void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
            public override void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "B::Foo()"
            }
        }

Constructors and Destructors

Constructors

A constructor is a special function that is a member of the Class and has the same name as that of the Class. Every Object created would have a copy of member data which requires initialization before it can be used. This initialization is common in Object-Oriented Language, which allows the object to initialize themselves as and when they created. This automatic initialization is performing through the use of constructor functions. The constructor methods exist to simplify the process of initializing class member variables within a class.

Declaration of Constructors 

public class Car
{
        int start;
        public Car()
        {
               //Add constructor task here
               start = 0;
        }
}
A constructor is optional if no constructors are declared for a class, the compiler invokes a default constructor for you. The default constructor simply sets all the fields in the class to their default values. You can define as many constructors as you want, as long as each constructor has a different parameter list. Also not that constructor functions cannot return values.

Destructors

A destructor is a function that has the same name as that of the class but is prefixed with a ~(tilde). Destructors de-initialize Object when they are destroyed. You can think of destructors as the opposite of constructors: constructors execute when objects are created, and destructors execute when the objects are destroyed by the built-in Garbage Collection facility. This process occurs behind the scenes with no consequence to the programmer.

Declaration of Destructors 

public class Car
{
        int start;
        //constructor
        public Car()
        {
               start = 0;
        }
        //destructor
        ~Car()
        {
               start = 0;
        }
}
Destructors are optional. Destructors cannot return any values; nor can they accept any parameters. Unlike constructors, you cannot have more than one destructor defined for a class.



Tuesday, 25 February 2014

SharePoint Site Architecture

The following diagram shows the SharePoint Foundation site architecture in relation to the collections and objects of the Microsoft.SharePoint namespace.
Site Achitecture
  1. Each SPSiteobject, despite its singular name, represents a set of logically related SPWeb objects (see below). Such a set is commonly called a "site collection," but SPSite is not a standard Microsoft .NET collection class, in contrast to SPWebCollection. Rather, it has members that can be used to manage the site collection. The AllWebs property provides access to theSPWebCollection object that represents the collection of all Web sites within the site collection, including the top-level site. The SPSite.OpenWebmethod of the SPSite class returns a specific Web site.
  2. Each site collection includes any number of SPWeb objects, and each object has members that can be used to manage a site, including its template and theme, as well as to access files and folders on the site. The Webs property returns an SPWebCollection object that represents all the subsites of a specified site, and the Lists property returns an SPListCollection object that represents all the lists in the site.
  3. Each SPList object has members that are used to manage the list or access items in the list. The GetItems method can be used to perform queries that return specific items. The Fields property returns an SPFieldCollection object that represents all the fields, or columns, in the list, and the Items property returns an SPListItemCollection object that represents all the items, or rows, in the list.
  4. Each SPField object has members that contain settings for the field.
  5. Each SPListItem object represents a single row in the list.

SharePoint Server Architecture

The following diagram shows the SharePoint Foundation server architecture in relation to the collections and objects of the Microsoft.SharePoint.Administration namespace.
Server architecture and Administration namespace
  1. The SPFarm object is the highest object within the SharePoint Foundation object model hierarchy. The Servers property gets a collection representing all the servers in the deployment, and theServices property gets a collection representing all the services.
  2. Each SPServer object represents a physical server computer. The ServiceInstances property provides access to the set of individual service instances that run on the individual computer.
  3. Each SPService object represents a logical service installed in the server farm. Derived types of the SPService class include, for example, objects for Windows services, such as the timer service, search, the database service, etc. and also objects for Web services, such as the basic content publishing Web service which supports the Web applications.
  4. An SPWebService object provides access to configuration settings for a specific logical service or application. The WebApplications property gets the collection of Web applications that run the service.
  5. If the service implements the Service Application Framework of SharePoint Foundation, then it can be split into multiple configured farm-scoped instantiations (CFSIs). Each of these provides the functionality of the service but each has its own individual permission and provisioning settings.
  6. Each instance of a service, or a CFSI, that is running on a specific server is represented by an SPServiceInstance object.
  7. An SPDatabaseServiceInstance object represents a single instance of a database service running on the database server computer. The SPDatabaseServiceInstance class derives from theSPServiceInstance class and thus inherits the Service property, which provides access to the service or application that the instance implements. The Databases property gets the collection of content databases used in the service.
  8. Each SPWebApplication object represents a Web application hosted in an Internet Information Services (IIS) Web site. The SPWebApplication object provides access to credentials and other farm-wide application settings. The Sites property gets the collection of site collections within the Web application, and the ContentDatabases property gets the collection of content databases used in the Web application.
  9. An SPContentDatabase object inherits from the SPDatabase class and represents a database that contains user data for a Web application. The Sites property gets the collection of site collections for which the content database stores data, and the WebApplication property gets the parent Web application.
  10. An SPSiteCollection object represents the collection of site collections within the Web application.