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

Sunday, 6 August 2017

Customizing Ribbon in SharePoint

There are certain cases where we need to Customize SharePoint Ribbon. Customizing ribbon in SharePoint is easy. today we will see what we can do in Customizing Ribbon in SharePoint.

Ribbon customization consists of two component
1. a custom Action
2. Command UI Extension or ribbon xml

1. Creating Custom Action

Lets start by creating a ribbon custom action so start by creating an empty SharePoint project and add an empty element named customribbon. now we can write the custom action in elements.xml file of customribbon.
Here is how we write a custom action.
 <CustomAction Id="TestRibbon" Location="CommandUI.Ribbon.ListView" RegistrationId="101" RegistrationType="List">
<!--commanduiextension -->

</CustomAction>

Location is where you want to insert the ribbon. here in my case ribbon will be inserted where ever is listview web part is present. below are some of locations

Location Description
CommandUI.Ribbon Add customization any where for registration id
CommandUI.Ribbon.ListView Add customization when list view is rendered
CommandUI.Ribbon.EditForm Add customization on the edit form of list
CommandUI.Ribbon.NewForm Add customization on new form of list 
CommandUI.Ribbon.DisplayForm Add customization on display form.

for further regarding the locations you can have a look of cmdui.xml in SharePoint hive/template/global/xml.

Apart from this declarative method you can also create custom action from server side code here is an example
  SPUserCustomAction testribbonaction = web.UserCustomActions.Add();
  testribbonaction.Location = "CommandUI.Ribbon.ListView";
  testribbonaction.RegistrationId = "101" // ; document library , 100 for custom list etc
  testribbonaction.RegistrationType = SPUserCustomActionRegistrationType.List;
  testribbonaction.CommandUIExtension = "";//command ui extension ribbon xml
  testribbonaction.Update();

So now we know how to create ribbon custom action so lets move to the next that is command ui xml

2. Ribbon XML

Customizing SharePoint Ribbon is about to write a ribbon xml and deploy it using a custom action.
There are two major component in ribbon xml CommandUIDeffinition and CommandUIHandler.
so it looks like bolow.
<CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Templates._children">
       </CommandUIDefinition>
      <CommandUIDefinition Location="Ribbon.Tabs._children">
       </CommandUIDefinition>
       ..
       ..
    </CommandUIDefinitions>
    <CommandUIHandlers>
        <CommandUIHandler Command="<command to handle>" CommandAction="<action                                       javascript>" EnabledScript="<conditionaly enable or disable the command>">                       </CommandUIHandler>
        ..
        ..
      </CommandUIHandlers>
</CommandUIExtension>
So basically a command ui extension can contain several command ui deffinitions and handlers.
Location is very important here for example with first commanduidefinition we are defining some template so the location is Ribbon.Templates._children and with second we are defining a tab in the tabs so the location is Ribbon.Tabs._children.

Suppose we need to add custom action in library tab of document lirary and under actions group.
note these things and search for the library tab in cmdui.xml as described earlier and try to find the actions group there and note the id.
I found the id was Ribbon.Library.Actions so if you want to add a button to actions group of library tab then you should set Location to Ribbon.Library.Actions.Controls._children


To dig little more lets create a tab. Tabs can have the maxsize , scaling and groups. Groups can have controls that have command and rendered by templates defined in Ribbon.Templates._children
So lets first create Template that will be later used to render the controls

<CommandUIDefinition Location="Ribbon.Templates._children">
          <GroupTemplate Id="Ribbon.Templates.TestTemplate">
            <Layout Title="TwoLarge" LayoutTitle="TwoLarge"> 
              <Section Alignment="Top" Type="OneRow">
                <Row>
                  <ControlRef DisplayMode="Large" TemplateAlias="test1"/>
                </Row>
              </Section>
              <Section Alignment="Top" Type="OneRow">
                <Row>
                  <ControlRef DisplayMode="Large" TemplateAlias="test2"/>
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>
    </CommandUIDefinition>

So we have defined a GroupTemplate named TestTemplate it contains layout element which defines title . it contains section and overflow section which i have not used but of course you can use

Section have alignment and type which can be OneRow,TwoRow or ThreeRow on the basis of that you can have more row elements.
ControlRef is like a placeholder where controls will be placed. please note the DisplayMode and TemplateAlias.
TemplateAlias defines the alias of the template and DisplayMode can have values Small , Medium , Large and Text which is self explanatory.

Our template is ready now lets create a tab and place a group and two buttons

        <CommandUIDefinition Location="Ribbon.Tabs._children">
          <Tab Id="Ribbon.TestTab" Title="Test" Description="this is test tab" Sequence="550">
            <Scaling Id="Ribbon.TestTab.Scaling">
              <MaxSize Id="Ribbon.TestTab.MaxSize" GroupId="Ribbon.TestTab.TestGroup"                                     Sequence="20" Size="TwoLarge"/>
              <Scale Id="Ribbon.TestTab.Scaling" GroupId="Ribbon.TestTab.TestGroup" Sequence="30"                    Size="TwoLarge"/>
            </Scaling>
            <Groups Id="Ribbon.TestTab.Groups">
              <Group Id="Ribbon.TestTab.TestGroup" Description="this is a test group" Sequence="10"                           Title="Test Group" Template="Ribbon.Templates.TestTemplate">
                <Controls Id="Ribbon.TestTab.TestGroup.Controls">
                  <Button Id="Ribbon.TestTab.TestGroup.TestButton1" TemplateAlias="test1" Alt="test                               button 1" Command="Ribbon.TestTab.TestGroup.TestButton1Command"                                              Image16by16="" Image32by32="/_layouts/15/1033/images/formatmap32x32.png?                              rev=23"  LabelText="Button 1" />
                  <Button Id="Ribbon.TestTab.TestGroup.TestButton2" TemplateAlias="test2" Alt="test                                     button 2" Command="Ribbon.TestTab.TestGroup.TestButton2Command"                                             Image16by16=""                                                                                                                                       Image32by32="/_layouts/15/1033/images/formatmap32x32.png?rev=23" 
                                LabelText="Button 2" />
                </Controls>
              </Group>
            </Groups>
          </Tab>
        </CommandUIDefinition>

The tab is ready however there are some important points the sequence should not be in multiple of 100 . it is used to arrange the controls or tabs for what to be shows first and what will be later.

Maxsize defines the max size of the controls and scale defines how the controls will be scaled when controls are added these are controlled by the layout we defined earlier.
Similary the group we have created is using the template that we defined in previous commandui definition.

Now the thing remains is CommandUIHandler. notice that the button defined above have command and we need to define the handler.
here is an example
<CommandUIHandlers>
        <CommandUIHandler Command="Ribbon.TestTab.TestGroup.TestButton1Command"                             CommandAction="javascript:alert('button 1');" EnabledScript="javascript:return true;">                </CommandUIHandler>
        <CommandUIHandler Command="Ribbon.TestTab.TestGroup.TestButton2Command"                                CommandAction="javascript:alert('button 2');" EnabledScript="javascript:return true;">            </CommandUIHandler>
      </CommandUIHandlers>
    
Command is the Command that has to be handled , CommandAction is the javascript that performs action and EnabledScript is the script that decideds when the command should be enabled.

So here is everything on one place.

 <CustomAction Id="TestRibbon" Location="CommandUI.Ribbon.ListView" RegistrationId="101" RegistrationType="List">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Templates._children">
          <GroupTemplate Id="Ribbon.Templates.TestTemplate">
            <Layout Title="TwoLarge" LayoutTitle="TwoLarge"> 
              <Section Alignment="Top" Type="OneRow">
                <Row>
                  <ControlRef DisplayMode="Large" TemplateAlias="test1"/>
                </Row>
              </Section>
              <Section Alignment="Top" Type="OneRow">
                <Row>
                  <ControlRef DisplayMode="Large" TemplateAlias="test2"/>
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>
        </CommandUIDefinition>
        <CommandUIDefinition Location="Ribbon.Tabs._children">
          <Tab Id="Ribbon.TestTab" Title="Test" Description="this is test tab" Sequence="550">
            <Scaling Id="Ribbon.TestTab.Scaling">
              <MaxSize Id="Ribbon.TestTab.MaxSize" GroupId="Ribbon.TestTab.TestGroup" Sequence="20" Size="TwoLarge"/>
              <Scale Id="Ribbon.TestTab.Scaling" GroupId="Ribbon.TestTab.TestGroup" Sequence="30" Size="TwoLarge"/>
            </Scaling>
            <Groups Id="Ribbon.TestTab.Groups">
              <Group Id="Ribbon.TestTab.TestGroup" Description="this is a test group" Sequence="10" Title="Test Group" Template="Ribbon.Templates.TestTemplate">
                <Controls Id="Ribbon.TestTab.TestGroup.Controls">
                  <Button Id="Ribbon.TestTab.TestGroup.TestButton1" TemplateAlias="test1" Alt="test button 1" Command="Ribbon.TestTab.TestGroup.TestButton1Command" Image16by16="" Image32by32="/_layouts/15/1033/images/formatmap32x32.png?rev=23"  LabelText="Button 1" />
                  <Button Id="Ribbon.TestTab.TestGroup.TestButton2" TemplateAlias="test2" Alt="test button 2" Command="Ribbon.TestTab.TestGroup.TestButton2Command" Image16by16="" Image32by32="/_layouts/15/1033/images/formatmap32x32.png?rev=23"  LabelText="Button 2" />
                </Controls>
              </Group>
            </Groups>
          </Tab>
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler Command="Ribbon.TestTab.TestGroup.TestButton1Command" CommandAction="javascript:alert('button 1');" EnabledScript="javascript:return true;"></CommandUIHandler>
        <CommandUIHandler Command="Ribbon.TestTab.TestGroup.TestButton2Command" CommandAction="javascript:alert('button 2');" EnabledScript="javascript:return true;"></CommandUIHandler>
      </CommandUIHandlers>
    </CommandUIExtension>
    
  </CustomAction>

This custom action can be copied in an empty element and can be deployed to see the tab in action.







Tuesday, 25 July 2017

SharePoint ModalPopup: Show Modal Dialog in SharePoint

Modal Dialog in SharePoint

there are certain business conditions which requires to show modal popups and let the action decided by user.
I already have written a post to show how to show wait screens in SharePoint. sp.ui.dialog.js in SharePoint is responsible for showing modal dialogs also.
there is a method actually there are more, the one which looks most convenient to me is :

SP.UI.ModalDialog.showModalDialog(options)
only point you need to make sure is sp.js and sp.ui.dialog.js are loaded. one can use ExecuteOrDelayUntilScriptLoaded
all you need to do is to create options and pass argument to modal dialog. options is created as below.

var newPopUp = SP.UI.$create_DialogOptions();

now you can set url to open as dialog , title , height, width and many other thing please have a look on msdn link given below. here the important point is you can pass a callback function that can be called when dialog is closed.
dialog is closed by following method
SP.UI.ModalDialog.commonModalDialogClose(dialogresult,url); dialog result can be SP.UI.DialogResult.cancel or SP.UI.DialogResult.invalid or SP.UI.DialogResult.OK also you can pass a url to callback method using url parameter.

lets define a method to open the dialog with callback fuction and a method for opening dialog.


function openModalPopup(url, title, width, height,callbackfunction) 

     {

       // create options

        var newPopUp = SP.UI.$create_DialogOptions();

        newPopUp.url =url;
        if (title != null)
            newPopUp.title = title;
        if (width != null)
            newPopUp.width = width;
        if (height != null)
            newPopUp.height = height;
      //set callback function        
       newPopUp.dialogReturnValueCallback = Function.createDelegate(null, callbackfunction);
        //show popup
        SP.UI.ModalDialog.showModalDialog(newPopUp);
    }
now our function is ready to show modal dialog. now lets create a function and pass actual parameters to show the modal dialog.
function showpopup()
{
    var url =<url of your page>;
   //call our above method and define callback
    openModalPopup(url,"Test Popup",500,500,function(result,target){
          switch (result) {
       case SP.UI.DialogResult.invalid, -1:
                            // invalid has been passed from commonModalDialogClose
           SP.UI.Status.removeAllStatus(true);
           var sidErr = SP.UI.Status.addStatus("there was an error while performing task", target, true);
           SP.UI.Status.setStatusPriColor(sidErr, "yellow");
           break;
            case SP.UI.DialogResult.cancel, 0:
                           // dialog has been closed or cancelled
           SP.UI.Status.removeAllStatus(true);
           var sidErr = SP.UI.Status.addStatus("task was cancelled", target, true);
           SP.UI.Status.setStatusPriColor(sidErr, "green");
           break;
       case SP.UI.DialogResult.OK, 1:
                           // operation was done and ok
           SP.UI.Status.removeAllStatus(true);
           var sid = SP.UI.Status.addStatus("task performed successfully.", "", true);
           SP.UI.Status.setStatusPriColor(sid, "green");
                             // if you want you can refresh the page lets say after one seconds.
           setTimeout(
               function() {
                   SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
               }, 1000);
           break;
       }
    });
}
now the code is ready for showing modal popup just call showpopup method.
we should think how we will close the popup. so if you are opening an out of the box page then you will not write any thing.
but when you create your own page say in layouts then you define your OK and Cancel buttons 
on click of cancel just make a call to commonModalDialogClose with cancel option as below
function closepopuppage() {
// should be written in popup page
              SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, _spPageContextInfo.webAbsoluteUrl);
          }
similarly on click of OK you will perform your task , close the dialog using SP.UI.DialogResult.OK option and in case of exceptions you will pass invalid option.
in all cases you can register script from server side to close the popup( in the cs file of popup).
for ex.

string script = "var url='" + SPContext.Current.Web.Url +

                                    "';SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK,url);";

 Page.ClientScript.RegisterStartupScript(GetType(), "testscript", script, true);



for all the option values you can have a look on msdn.
https://msdn.microsoft.com/en-us/library/office/ff410058%28v=office.14%29.aspx?f=255&MSPPError=-2147217396


Friday, 21 July 2017

Working with Status and Notification in SharePoint using sp.js


There are certain business situations where we need to show status and notifications to user.
these are important because these are used to inform business users that something is happening in the back end.
lets have a look of what are the methods available in sp.js to show status and notifications and later i will put a working code here that can be used for showing status and notifications.

Working with Notification 


SP.UI.Notify module is used to work with notifications. this class has two methods

1. addNotification(notificationHtml,sticky)

notificationHtml : it is a string value that is shown as Notification
sticky : it is a boolean value that if true then notification will not be removed until we will not           remove  it by calling remove notification. if false then notification is removed in three seconds.

2. removeNotification(nid) 

nid : it is notification id that has to be removed

I will show an example at the end of this post.

Working with Status

SP.UI.Status module is used to work with the status here are the methods that are there in Status module

addStatus(strTitle, strHtml, atBegining) : used to add status
SP.UI.Status.setStatusPriColor(sid, strColor) : set the background colour of status
removeStatus(sid) : remove the status
appendStatus(sid,strhtml) : append in existing status
updateStatus(sid,strhtml) : update the status

There can be four options while setting background colour of status red : very important , yellow : important , green : everything ok , blue : for information
below is a working example you can copy the code and same in a .html file in a SharePoint library
then anywhere you can used content editor with content link pointing to this file.
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript">
    var notificationid='';
    var statusid='';
    function ShowNotification()
    {
       notificationid= SP.UI.Notify.addNotification("Working on it...",true);
    }
    function RemoveNotification()
    {
        if(notificationid!='')
        {
            SP.UI.Notify.removeNotification(notificationid);
            notificationid='';
        }
    }
    function AddStatus()
    {
        statusid=SP.UI.Status.addStatus("test","Task has been completed successfully.");
        SP.UI.Status.setStatusPriColor(statusid,'green');
    }
    function RemoveStatus()
    {
        if(statusid!='')
        {
            SP.UI.Status.removeStatus(statusid);
            statusid='';
        }
    }
</script>
<div>
    
    <input type="button" value="Show Notification" onclick="ShowNotification();"/>
    <br/><br/>
    <input type="button" value="Remove notification" onclick="RemoveNotification();"/>
    <br/><br/>
    <input type="button" value="Add Status" onclick="AddStatus();"/>
    <br/><br/>
    <input type="button" value="Remove Status" onclick="RemoveStatus();"/>
</div>
for more information you can have a look on msdn
https://msdn.microsoft.com/en-us/library/office/ff407632%28v=office.14%29.aspx?f=255&MSPPError=-2147217396#Notifications

Tuesday, 18 July 2017

SharePoint Modal Dialog: Show wait screen to user


There are certain business scenarios where we need to show wait screen to user as SharePoint does and shows “working on it…” dialog.
Fortunately, we have api available in sp.ui.dialog.js there are two methods available for showing wait screen.
1. showWaitScreenWithNoClose(title,description,height,width)
This method shows a wait screen without close option or button on it. once you show wait screen, parent screen gets freezes and you need to close by calling close method.
For example, it will look like this.
SP.UI.ModalDialog.showWaitScreenWithNoClose("Working on it...", "this should not take long.", 100, 400);
Before writing this code you need to make sure that sp.js and sp.ui.dialog.js is loaded. complete code is given below.
<script type="text/javascript">
function ShowWaitScreen()
{
ExecuteOrDelayUntilScriptLoaded(function(){
ExecuteOrDelayUntilScriptLoaded(function(){
window.waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose("Working on it...", "this should not take long.", 100, 400);
},"sp.ui.dialog.js");
},"sp.js");
}
</script>
Just call ShowWaitScreen and it will start showing wait screen.
To close wait screen call waitDialog.close(). Please note waitDialog is defined in window object you here you need to call like this
if(window.waitDialog)
{
window.waitDialog.close();
}
2.  showWaitScreenSize(title,description,callbackfunction,height,width)
unlike above method, it also shows close and cancel buttons. You can also pass a callback function which will be called when dialog will be closed.
An example is given below.
var waitDialog=SP.UI.ModalDialog.showWaitScreenSize("Working on it...","this should not take long.",closeDialogCallback,200,400);

Please note that we need to make sure that sp.js and sp.ui.dialog.js is loaded as in first case.

Monday, 8 May 2017

Update lookup field or person field in jsom

When we talk about how to update lookup field or person or group field using jsom then it is treated little diffirently.
for example, for normal field we use

listitemobj.set_item(fieldname,value)
but that will not work for lookup fields.
for lookup fields following step should be followed.

to update person or group field we should pass id of the person or group.

for example if id of the user is 5 then update should be like below.

listitemobj.set_item(personfieldname,5);

similarly for lookup field, a lookup field value should be created first.

example:
var lookupfieldvalue = new SP.FieldLookupValue();
 lookupfieldvalue.set_lookupId(<id of the item to lookup>);
 oListItem.set_item(lookupfield, lookupfieldvalue);
 oListItem.update();

if we summarise both in a function then

function createListItem(personfield,lookupfield) {

        var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);
        var oList = clientContext.get_web().get_lists().getByTitle(<list name>);
        var itemCreateInfo = new SP.ListItemCreationInformation();
        this.oListItem = oList.addItem(itemCreateInfo);

// set person field
        oListItem.set_item(personfield, <id of the user or group>);

//set lookupfield
var lookupfieldvalue = new SP.FieldLookupValue();
        lookupfieldvalue.set_lookupId(<id of the item to lookup>);
        oListItem.set_item(lookupfield, lookupfieldvalue);
        oListItem.update();
        clientContext.load(oListItem);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),      Function.createDelegate(this, this.onQueryFailed));
    }

    function onQuerySucceeded() {
        alert('Item created Successfully !!!!');
    }

    function onQueryFailed(sender, args) {

        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
  

Sunday, 7 May 2017

Linking Author Name to Profile in XSLT in Share Point 2010


How to Link Author name to profile Picture using xslt:


Recently I was working on a project and i need to link the author name to profile i.e created by name to profile in content query webparts ItemStyle in Item style.xsl

Now bellow <xsl:styleSheet tag Create parameters as bellow
<xsl:param name="PageUrl"/>
<xsl:param name="SiteUrl"/>
<xsl:param name="WebUrl"/>
PageUrl will contain the url of the page . SiteUrl will contain Url to Site. Web Url contain url to web.
you can concat SiteUrl and WebUrl to get WebUrl as below.

First declare a variable and perform a user lookup  on the account name of the user.
<xsl:variable name="authoraccount">
<xsl:value-of select="ddwrt:UserLookup(string(@Author) ,'Login')" />
</xsl:variable>
Now as we have account I can link it to sites person.aspx
 <xsl:variable name="FinalUrl">
                    <xsl:value-of  select="concat($SiteUrl,$WebUrl)"/>
   </xsl:variable>
Please Contact <a href="{$FinalUrl}/_layouts/userdisp.aspx?accountname={$authoraccount}&amp;Source={$PageUrl}"><xsl:value-of select="@Author"></xsl:value-of></a>

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.

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