Friday, April 19, 2013

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);
            }

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 sayMembershipdb.
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.

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>

                    <addconnectionStringName="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>

                    <addconnectionStringName="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.

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 Definitions,  Job 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, nullSPJobLockType.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.