Monday 1 April 2013

Creating Custom Timer Job in share point 2010



Creating  Custom  Timer Jobs  in Share point 2010



A Timer job is periodically executed task on the share point server. Timer job is object of a class which is derived from  SPJobDefinition

A timer job can be described in three parts  :  Job DefinitionsJob Instances, and  Job Schedules.
Timer job definition is a .net class that is inherited from SPJobDefinition.  JobInstance , as the name suggests is instance of job definition which allows us to create multiple Instances of the same job with different properities. These job instances are scheduled for to run on some Web Application (SPWebApplication) or some Service (SPService) or on Server (SPServer). For ex Minutes , Daily, Weekly. Etc.
 From Central Administration >>Monitoring >> Review Job Definition , we can see various jobs which are scheduled . jobs running , history etc.

Timer Job Association


A timer job instance must be associated with either a SharePoint web application (SPWebApplication) or a SharePoint service application (SPService). It may also be associated with a server (SPServer) if you desire, but it is not a requirement. The reason behind the association requirements is that the SPJobDefinition class inherits from the SPPersistedObject class.
There are 3 constructors of SPJobDefinition .one Is default,  One of the constructors allows you to associate the timer job with a web application, and the other allows you to associate it with a service application.
For to associate a timer job to Central Admin just Pass SPWebAdministration.Local  as webApplecation. We can not associate a timerjob with a server and skipping other entities.
One other thing we must have some association . we can not pass null to association.
It is enough Lets start creating a Timer Job.

Creating  Custom Timer Job


Lets Start Step By Step . create a empty share point project  in the name box type TimerJobProject.
Right click on the project >> Add new Item  . add a class  name it TimeJob.cs , by default I will show as bellow.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Data;
using System.IO;

namespace TimerJob
{
    class TimeJob
    {
    }
}

Inherit this class with SPJobDefinition. For this add using statements.
using Microsoft.SharePoint.Administration;

class TimeJob : SPJobDefinition

now I will associate this timer job with WebApplecation so add constructor.
      
       /*DEFAULT CONSTRUTOR WITHOUT PUBLIC DEFAULT CONSTRUCTURE JOB CAN NOT BE DESERIALISED */
public TimeJob()
            : base()
        {
            this.Title = "Custom Timer Job";
        }
 public TimeJob(SPWebApplication webApplication) /* PASS TO BASE CLASS base( name,webapplecation,server,locktype*/
            : base("Custom Timer Job", webApplication, null, SPJobLockType.Job)
        {
            Title = "Project Status Timer Job";
        }

Now it is time to write some custom code I will send email simply. Override Execute method of SPJobDefinition.

public override void Execute(Guid targetInstanceId)
        {
          
          
            try
            {
                SPWebApplication webapp = this.Parent as SPWebApplication;
                SPSite site = webapp.Sites[0];

                SPWeb web = site.RootWeb;
             
               /*USE NAME SPACE USING SHAREPOINT.UTILITIES*/
               SPUtility.SendMail(web,"your email id ", "TimeJobEmail", “TestEmail”);
            }
            catch (Exception ex)
            {
               
               
               
            }
        }
OK Our Custom timer job has been created now need create and delete this timer job. So add a feature if not already added and add feature receiver.

Don’t forget to give scope of this feature to site.

Now on feature activated create and schedule timer job as bellow first delete job as during testing we usually deploy many times .

SPSite site = properties.Feature.Parent as SPSite;
            DeleteJob(site);// will be write this method to delete job
            TimeJob tasksTimerJob = new TimeJob(site.WebApplication);
       

            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 1;
            tasksTimerJob.Schedule = schedule;
            tasksTimerJob.Update();


avobe code creates and schedules job to run every minutes. For deleting job iterate for every job in webapplecation and find the job and delete it

private void DeleteJob(SPSite site)
        {
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name.Equals(“Custom Timer Job”,
                StringComparison.OrdinalIgnoreCase))
                {
                    job.Delete();
                }
            }
        }
Now on feature deactivativating delete the job simply.
       public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            DeleteJob(site);
        }
Deploy the Project Go to Central Admin>> Monitoring>> Review timer job. you will have your Timer job. You can schedule it

Once you have deployed the timer job it may not updated . on run type services.msc it will open services. Search for Share point 2010 Timer Services and restart it.

It at some place it need to debug the job then Please remember it can not be debugged by w3wp.exe as it is iis worker process.

Attach OSTIMER.EXE  to from debug >> attach process and run timer job to debug the job.











Tuesday 19 March 2013

Filter Xslt ListView Webpart from Query string varriable

Share point Renders Lists and libraries in XSLT List View Webpart. today , we will see,  How we can filter this list view on  the basis of query string.

Ok , it easy . insert the list on to some page, if you want , or use default view i.e AllItems.aspx.

let us take some example.
supose we have to show news in the website. ok . onto home page probably we want to display news in some custom webpart . these news will be linked to items there may be an option to show all news .

Share Point uses filterfield and filter value combination. for ex. considering avobe point in mind , we may have to display only one record on the basis of id . QueryString will be
?FilterField1=ID&FilterValue1=1
this query string will show item with id 1

similarly we can use filters on any field and on also on several fields.  

How to Create Custom Mobile View in Sharepoint 2010



Today we will see how we can create custom mobile view in share point 2010.
Ok when  we create a site , by default , when opened in browser it shows something like bellow

Which does not look good enough . it only shows lists and libraries. Suppose I want to customize the look and feel completely  then why not to deploy some pages in the layout directory for our use in Mobile site.
Ok , I am telling just concepts  here map layout folder in visual studio. Create a directory for  your projects for example
Layouts/your project/
Here we will place all stuffs like css etc.
In the same folder we can create a master page and some pages to so the data . master page will determine the mobile page look and feel.
Now the work remains to stop the default mobile redirection and redirect to our own pages.  Ok
Just add a line in web.config of content site before</system.web>
<browserCaps>
<result type="System.Web.Mobile.MobileCapabilities, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<filter>isMobileDevice=false</filter>
</browserCaps>
Now add a webpart on to home page of site . check the user agent and redirect to mobile view . as bellow.
string userAgent = HttpContext.Current.Request.UserAgent;
          
            if (userAgent.Contains("BlackBerry") || (userAgent.Contains("iPhone") || (userAgent.Contains("Android"))))
            {
                HttpContext.Current.Response.Redirect("_layouts/<your project>/index.aspx");
                Control control = Page.LoadControl(_ascxPath);
                Controls.Add(control);
            }
There are other ways also to customize mobile view . and I will discuss it in upcoming posts.

Thursday 14 March 2013

Bind Sharepoint 2010 Document Library to GridView

Yes guys i am back . with a topic How you can bind a sharepoint document library folders and  files i will also tell you the technique how you can put a meaning full title and then link to file .

very first it will show all the folders then then we can browse the folders. so let us begin our journy by first creating a document library named CompanyDocs. in it create some folders like Design ,Development , Finance. put some files in it.

ok Finaly our Structure is
 CompanyDocs
      >>Design
      >>Development
      >>Finance


yes we have done . now create a webpart drag a gridview on to it.



<asp:GridView  ID="grdDocs" GridLines="None"
    RowStyle-HorizontalAlign="Center" runat="server"
     Width="100%" AutoGenerateColumns="false"
    AlternatingRowStyle-CssClass="gray_bg" EmptyDataText="There is no records"
     EmptyDataRowStyle-Font-Bold="true" EmptyDataRowStyle-ForeColor="Red"
     EmptyDataRowStyle-HorizontalAlign="Center"
     CssClass="mytableclasse"
    onrowdatabound="grdGroups_RowDataBound" AllowPaging="True"
    onpageindexchanging="grdGroups_PageIndexChanging" PageSize="15">
    <Columns>
    <asp:TemplateField HeaderText="S.No">
    <ItemStyle Width="5%" />
    <ItemTemplate>
    <asp:Label ID="lblsn" runat="server"></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
 
    <asp:TemplateField HeaderText="Title">
    <ItemStyle Width="80%" />
    <ItemTemplate>
    <asp:HyperLink ID="hypfile" runat="server"></asp:HyperLink>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Date">
    <ItemTemplate>
    <asp:Label ID="lblDate" runat="server"></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
 </asp:GridView>
i have taken a grid view and three template fields seriel no , folder or file and Date .

now on cs file see how binding has been done

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }
        private void BindGridView()
        {
        // first impersonate user
            SPSite site=new SPSite(SPContext.Current.Site.ID, SPContext.Current.Web.CurrentUser.UserToken);
            SPWeb web=site.RootWeb;
         
            try
            {
                SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["CompanyDocs"];
                DataTable table=new DataTable();
                table.Columns.Add("Title");
                table.Columns.Add("URL");
                table.Columns.Add("Target");
                table.Columns.Add("Date");
                SPFolder folders=null;
                bool flag=false;
                if (string.IsNullOrEmpty(Request.QueryString["RootFolder"]))
                {
                    folders = docLib.RootFolder;
                    flag = true;
                }
                else
                {
                    folders = web.GetFolder(Request.QueryString["RootFolder"]);
                    flag = false;
                }
                foreach (SPFolder folder in folders.SubFolders)
                {
                    if (flag)
                    {
                        if (folder.Name != "Forms")
                        {
                            SPListItem item = folder.Item;
                            DataRow drfolder = table.Rows.Add();
                            drfolder["Title"] = item["Title"] == null ? folder.Name : item["Title"].ToString();
                            drfolder["URL"] = System.Web.HttpContext.Current.Request.Path + "?RootFolder=" + folder.Url;
                            drfolder["Target"] = "_self";
                            drfolder["Date"] = Convert.ToDateTime(item["Modified"]).ToString("dd/MM/yyyy");
                        }
                     
                    }
                    else
                    {
                        SPListItem item = folder.Item;
                        DataRow drfolder = table.Rows.Add();
                        drfolder["Title"] = item["Title"] == null ? folder.Name : item["Title"].ToString();
                        drfolder["URL"] = System.Web.HttpContext.Current.Request.Path + "?RootFolder=" + folder.Url;
                        drfolder["Target"] = "_self";
                        drfolder["Date"] = Convert.ToDateTime(item["Modified"]).ToString("dd/MM/yyyy");
                    }
                 
                 
                }
                foreach (SPFile file in folders.Files)
                {
                    SPListItem item = file.Item;
                    DataRow drfolder = table.Rows.Add();
                    drfolder["Title"] = item["Title"]==null ? file.Name : item["Title"].ToString();
                    drfolder["URL"] = SPContext.Current.Web.Url + "/" + file.Url;
                    drfolder["Target"] = "_blank";
               
                       drfolder["Date"] = Convert.ToDateTime(item["Created"]).ToString("dd/MM/yyyy");
                 
                }
                grdGroups.DataSource = table;
                grdGroups.DataBind();
            }
            catch(Exception ex)
            {
            }
        }

        protected void grdGroups_RowDataBound(object sender, GridViewRowEventArgs e)
        {
         
           Label  lblsn = e.Row.FindControl("lblsn") as Label;
           HyperLink hypfile = e.Row.FindControl("hypfile") as HyperLink;
           Label lblDate = e.Row.FindControl("lblDate") as Label;

           try
           {
             
               lblsn.Text =(e.Row.RowIndex+1) .ToString();
               hypfile.Text = DataBinder.Eval(e.Row.DataItem, "Title").ToString();
               hypfile.NavigateUrl = DataBinder.Eval(e.Row.DataItem, "URL").ToString();
               hypfile.Target = DataBinder.Eval(e.Row.DataItem, "Target").ToString();
               lblDate.Text = DataBinder.Eval(e.Row.DataItem, "Date").ToString();
         
           }
           catch (Exception ex)
           {
         
           }



        }

        protected void grdGroups_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdGroups.PageIndex = e.NewPageIndex;
            BindGridView();

        }

Just copy and paste avobe cs code in your web part cs file .
see i have impersonate the user to the library
SPSite site=new SPSite(SPContext.Current.Site.ID, SPContext.Current.Web.CurrentUser.UserToken);
if you u do not want use SPContext.Current.Web and AllowUnsafeUpdates to true.

yes insert web part on to some page in the same site as Document Library.
and be happy. all will be fine.





Friday 8 March 2013

How To Enable FBA in Sharepoint 2013.


Configuring Form  Based Authentication in Sharepoint 2013


When we first create a site in sharepoint 2010,  by default it uses claims based authentication unlike share point 2010 which uses by default windows authentication.

In share point 2013 claim authentication is default authentication available in central administration. And our newly created site by default uses windows authentication .

So like share point 2010 it is not need to configure central administration for FBA . only need to configure Security service Application and  our content site.

Follow following steps to configure FBA.
1.      
Create member ship database .
Browse to c:\windows\microsoft.net\framework\<latestframework> on command prompt and type aspnet_regsql.exe . follow the wizard name the database say Membershipdb.
2.       Set up Membership provider and role manager in content site.
Go to CA >> Application Management >>select Your Application . from ribbon click on authentication providers and set ASP.net membership provider and role Manager. Say. FBAMemberShipProvider and FBAMemberShipProvider

3.       Update these in STS web.config. go to IIS Manager explore Security Token Service Application. Open web.config backup it and begin to make changes.
STS File Changes avobe </configuration> Write bellow lines

<system.web>
<membership>
                <providers>
                                <add connectionStringName="SqlConnectionString" applicationName="/" name="FBAMemberShipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
                </providers>
</membership>
<roleManager>
                <providers>
                                <add connectionStringName="SqlConnectionString" applicationName="/" name="FBARoleManager" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
                </providers>
</roleManager>

</system.web>

<connectionStrings>
                <add name="SqlConnectionString" connectionString="Data Source=.;Initial Catalog=Membershipdb;Integrated Security=SSPI" />
</connectionStrings>

4.Content site web.config changes

Open web.config search for <membership> in <providers> one will be added . add one more as bellow.  
<add connectionStringName="SqlConnectionString" applicationName="/" name="FBAMemberShipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web,&#xD;&#xA; Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

Similarly in role Manager Section Add
role Manager section add bellow code

<add connectionStringName="SqlConnectionString" applicationName="/" name="FBARoleManager" type="System.Web.Security.SqlRoleProvider, System.Web,&#xD;&#xA; Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

add connection string connection string avobe the </configuration>

<connectionStrings>
                <add name="SqlConnectionString" connectionString="Data Source=.;Initial Catalog=Membershipdb;Integrated Security=SSPI" />
</connectionStrings>

Save all of Avobe and Reset the IIS . and you are done.

Thursday 7 March 2013

How to Enable FBA in Sharepoint 2010


Create a site using Claims Authentication or convert existing a site which is using windows

authentication to claims authentication. By using following Power shell script.
      
$App = get-spwebapplication “http://sp1:8000”
          $app.useclaimsauthentication = “True”
          $app.Update()
type avobe script in to notepad and save some where in suppose in c drive.
Now open power shell and type
./filename.ps1

Now we have a site which uses claims based Authentication.

2.       Configure Member ship provider and role  manager data base in sql .
On command prompt go to C:\windows\microsoft.net\framework\latest frame work.
And type astnet_regsql.exe.  it will open a dialog box for configuring Member ship database
Enter the names of  Membership Provider , Role Manager , Membership Database.
Whatever name can be used Just remember these names  .
3.       Now data base has been configured ad some users in it here is a tool  on code plesk . extract open bin folder . run exe file . if data base is other than aspnetdb then open config files and change to appropriate database name.
4.       Modify web.config files to update these data base . three web.config files has to be updated .
a.       Web.config of Content Site.
b.      Web.config of central administration
c.       Web.config of web  services token.
a.        paste connection string information after </ Sharepoint>  and before <system.web>
<connectionStrings>
<add name="SQLConnectionString" connectionString="Data Source=.;Initial Catalog=Membershipdb;Integrated Security=True" />
</connectionStrings>

Paste bellow code in before </System.web>
<membership defaultProvider="i">
      <providers>
<add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add connectionStringName="SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="SQL-MembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
    <roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">
      <providers>
 <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
               
<add connectionStringName="SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="SQL-RoleManager" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
    </roleManager>
Web.config of Central Administration .
Backup before changing.
Add the connection string after </sharepoint> and before </System.web>
<connectionStrings>
<add name="SQLConnectionString" connectionString="Data Source=.;Initial Catalog=Membershipdb;Integrated Security=True" />
</connectionStrings>

Add membership provider and role manager in the provider section of both respectively. Focus on highlights
<roleManager defaultProvider="AspNetWindowsTokenRoleProvider" enabled="true" cacheRolesInCookie="false">

              <providers>

                    <add connectionStringName="SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="SQL-RoleManager" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

              </providers>

        </roleManager>

        <membership defaultProvider="SQL-MembershipProvider">

              <providers>

                    <add connectionStringName="SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="SQL-MembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

              </providers>

        </membership>
Above will be in System.web section in web.config.


Web.config of STS


Explore STS From IIS Manager.
 Backup before changing.

Before </Configuration> and
<connectionStrings>

                                <add name="SQLConnectionString" connectionString="Data Source=.;Initial Catalog=Membershipdb;Integrated Security=True" />

                </connectionStrings>

                <system.web>

                                <roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">

                                                <providers>

                                                                <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />

                                                                <add connectionStringName="SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="SQL-RoleManager" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

                                                </providers>

                                </roleManager>

                                <membership defaultProvider="i">

                                                <providers>

                                                                <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />

                                                                <add connectionStringName="SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="SQL-MembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

                                                </providers>

                                </membership>

                </system.web>
Keep Highlighted points in mind.

Save and reset the IIS and you are done.

please Read next Post to Read how to enable FBA in Sharepoint 2013 .

Setup dev environment for spfx

So lets setup dev environment for SharePoint Framework abbreviated as SPFX. for an Introduction of What is SPFX and What are the capebiliti...