Sunday, July 14, 2013

Use jQuery & cookies in SharePoint 2010

In this blog article I’ll show you how to use Cookies in jQuery for your SharePoint Designer 2010 no code applications.
With help of a cookie you can write information to the user’s computer and this can be useful if you need to store stuff like visitors preferences, for example if the user has checked a check box or not at some page. Cookies can be very useful in many ways, but in some situations you need to write such information to the server like a database instead, cookies should not be used for critical information or any kind of sensitive information especially at a public faced site. However a cookie can be a great choice for many tasks in your front end development.
Some examples of the usefulness of a cookie
  • Change color schemes
  • Hide / Show elements at the page
  • Resizing fonts, scale up or down
  • Form, auto save inputs in fields, selected check box or radio button
  • Accordion / tabs, remember last state of collapsed/opened
  • Navigation, remember the last location
  • Welcome message, for example if you want to show a popup only once at specific date at the start page.
jQuery doesn’t support cookies natively but you can use a super small plugin called ‘jquery.cookie.js’  that contains all kind of basic functions and options you’ll need for your scripting. This plugin is also included in jQuery UI development-bundle.
Jquery.cookies gives a couple of options like:
  • Expires
    The lifetime for the cookie. You can use a number of days or a specific date. If omitted, the cookie is a session cookie
  • Path
    Where the cookie is valid. If you want it to be valid at every site in the site collection, just use a slash /, if you want it to be valid at let’s say only the news site set e.g /news/

Get going

Let’s start with a simple example just to get going, the following example will set the top row to a red or green background color depending of which link you click. Let’s say you clicked at green one and then reload the page, the green background color will remain. If you restart the browser, the top row will be white again. This script do not have any expired date, therefore, the cookie will expire automatically when you close the browser.
Let’s try this out:
Download jquery.cookies.js and create a reference to this file in your custom master, don’t forget to include an reference to latest jQuery API as well.
HTML
Put this somewhere in your custom master page
1
2
3
4
5
6
<!-- Session -->
<div class="Wrapper">
    <div class="Red">Red</div>
    <div class="Pipe">|</div>
    <div class="Green">Green</div>
</div>
jQuery
Put this in an external JS file referenced from your master page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$(document).ready(function() {
 
// Click red
$('.Red').click(function() {
$('.Wrapper').css("background-color","red");
$.cookie('Wrapper', 'red');
});
 
// Click green
$('.Green').click(function() {
$('.Wrapper').css("background-color","green");
$.cookie('Wrapper', 'green');
});
 
// Cookies
var Wrapper = $.cookie('Wrapper');
if (Wrapper == 'red') {
$('.Wrapper').css("background-color","red");
};
if (Wrapper == 'green') {
$('.Wrapper').css("background-color","green");
};
 
});
CSS
Put this in an external CSS file referenced from your master page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
.Wrapper{
width:100%;height:16px;
background-color:#fff;color:#000;
}
.Red{
cursor:pointer;padding-left:5px;
float:left;
}
.Green{
cursor:pointer;float:left;
}
.Pipe{
float:left;padding:0px 5px 0px 5px
}
Maybe you want to set the cookie to a life span of 2 days, take a look at the jQuery script and the part where you set the name and the property:
1
$.cookie('Wrapper-', 'Green-');
Just add a path and a value; a number or a specific date, this will create the cookie
1
$.cookie('Wrapper-', 'Green-', {path: '/', expires: 2});
Take a look at the cookie in your disk, if you are using IE, you will find it through this path
1
C:\Users\...\AppData\Local\Microsoft\Windows\Temporary Internet Files
The file will contain the name of the cookie, the property and the path like this
1
Wrapper-Green-ecmtest67/108815182001923024639810215318430245996*

How to use cookies in a Data View web part

If we take this a step further and try to use cookies in a typical news roller DVWP. In this example, If you click at the icon next to the header for a news item that section will disappear, a kind of ‘I Have Read This’ function. At the bottom of the web part there’s a reset link that will delete the cookie.

The HTML part of the DVWP, it’s important to use @ID for the id, classes and href as the script shows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<div class="NewsRow {@ID}">
<div class="NewsContentContainer">           
<div class="NewsTitle">
<div class="NewsHider"><a href="{@ID}" id="{@ID}"><img alt="" src="/Style%20Library/Custom/Images/IhaveReadThis.png" width="22" height="22" /></a></div>
<div class="NewsTitleInner"><a href="/news/Pages/{@LinkFilename}"><xsl:value-of select="@Title" /></a></div>
<div class="GeneralClearBoth"></div>
</div>       
</div>
<div class="NewsAuthorCreatedWrap">
<span class="NewsAuthor">By <xsl:value-of select="@PublishingContact.title" />,</span> <span class="NewsCreated"><xsl:value-of select="@ArticleStartDate" /></span>
</div>
<div class="NewsContent">
<xsl:call-template name="FirstNWords">
<xsl:with-param name="TextData" select="$DescText"/>
<xsl:with-param name="WordCount" select="15"/>
<xsl:with-param name="MoreText" select="'...'"/>
</xsl:call-template>
</div>
</div>
The jQuery goes here
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
jQuery(function ($) {
var removedLinks = 'removedLinks'
,Options = {
expires: 7,
path: '/news'
},
c=$.cookie(removedLinks)||'#DebuggingCode'
$(c).remove();
$(".NewsHider a").click(function (e) {
e.preventDefault();
var LinkClass = '.'+ $(this).attr('id'),
removeLinksClasses=c.split(',')
$(LinkClass).remove()
removeLinksClasses.push(LinkClass)
c=removeLinksClasses.join(',')
$.cookie(removedLinks, c, Options)
});
$('#NewsResetCookie').click(function(){
$.cookie(removedLinks,'',{expires:-1,path:'/news'})
})
});
If you prefer to use this in the ItemStyle.xsl and use it as a format for the Content Query web part, it works fine as well.

SharePoint Form field date validation using javascript


<script language=”javascript” type=”text/javascript”>
function PreSaveAction()
{
var date1 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”Start Date”);
var date2 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”End Date”);
var arrDate1 = date1.value.split(“/”);
var useDate1 = new Date(arrDate1[2], arrDate1[1]-1, arrDate1[0]);
var arrDate2 = date2.value.split(“/”);
var useDate2 = new Date(arrDate2[2], arrDate2[1]-1, arrDate2[0]);
if(useDate1 > useDate2)
{
alert(“The End Date cannot happen earlier than the Start Date”);
return false; // Cancel the item save process
}
return true; // OK to proceed with the save item
}
function getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length – len)) {
return tags[i];
}
}
return null;
}
</script>

Free ebook – 101 New Features In SharePoint 2013

IIS Manager Error: The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)


When i was tried to open my 80 Port  i got 404 error and checked on the IIS the web site was stopped and when I try to start it the error message "The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)" appears, and i solved the issues with a simple method.
There is another application(SKYPE) that is using port 80

1. Open the Skype window, then click on Tools menu and select Options.
2. Click on Advanced tab, and go to Connection sub-tab.
3. Uncheck the check box for Use port 80 and 443 as an alternatives for incoming connections option. 
4. Click on Save button 
5. Restart Skype to make the change effective. 

Enjoy :)

Send Email using Object Model


We will discuss various methods of Sending an e-mail in SharePoint 2010.
In First we need to configure Out going email on Central Administration.
Method 1 : –Code retrieves the SMTP host’s address from the SharePoint configuration database.

public static bool SendMail(string Subject, string Body,bool IsBodyHtml, string From, string To, string Cc, string Bcc)
{
bool mailSent= false;
try
{
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = SPContext.Current.Site.WebApplication.
OutboundMailServiceInstance.Server.Address;
MailMessage mailMessage = new MailMessage(From, To, Subject, Body);
if (!String.IsNullOrEmpty(Cc))
{
MailAddress CCAddress = new MailAddress(Cc);
mailMessage.CC.Add(CCAddress);
}
if (!String.IsNullOrEmpty(Bcc))
{
MailAddress BCCAddress = new MailAddress(Bcc);
mailMessage.Bcc.Add(BCCAddress);
}
mailMessage.IsBodyHtml = IsBodyHtml;
smtpClient.Send(mailMessage);
mailSent = true;
}
catch (Exception) { return mailSent; }
return mailSent;
}
This ensures that you get the advantages of.NET-style mail delivery while keeping your configuration in Central Administration.
If however, you are not working in a SharePoint context, you can get the SPWebApplication reference from a new SPSite object like below
public static string GetSharePointMailService(string mysite)
{
string address;
using (SPSite site = new SPSite(mysite))
{
address = site.WebApplication.OutboundMailServiceInstance.Server.Address;
}
return address;
}
Method 2 : – This uses the embedded SharePoint SendEmail which has fewer capabilities, but is as straightforward as possible, and is the preferred approach if you simply want to send e-mail:
SPUtility.SendEmail(web, useHtml, htmlEncode, to, subject, htmlBody)
The Paramets are :
web(SPWeb) – An object that represents the site
headers(StringDictionary) – A collection of additional headers
useHtml(bool) – Used to append an HTML tag to the message (true)
htmlEncode(bool) – Encodes the message and replaces characters in HTML tags with entities
to(string) – The address to which to send the e-mail
subject(string) – Contains the subject for the e-mail message
htmlBody(string) – Contains the body of the e-mail message
addFooter(bool) – Used if there is a footer to be appended to the e-mail
The headers parameter is used instead of the to and subject parameters. It allows you to set all possible mail headers and forces you to add at least the to header that way. An example follows:
StringDictionary headers = new StringDictionary();
headers.add(“to”,”authors@apress.com”);
headers.add(“cc”,”joerg@krause.net”);
headers.add(“bcc”,”checkthis@apress.com”);
headers.add(“from”,sp2010@apress.com);
headers.add(“subject”,”Send an EMail from SPUtility”);
headers.add(“content-type”,”text/html”);
string bodyText =”This is an html formatted message.”;
SPUtility.SendEmail(web, headers, bodyText);
Note that StringDictionary is defined in the System.Collections.Specialized namespace.
Method 3 : - Sending E-Mail from a WCF Service
Sending an e-mail from a service when SPContext is not available could fail. As a workaround, you have to prevent the mail function from reading the current context by using HttpContext.Current = null. If it can’t, it will retrieve the right context and it will then work. The next example shows this.
Sending E-mail Using SendMail from a WCF Service
try
{
using (SPSite site = new SPSite(“http://sharepointserve”))
{
SPWeb thisWeb = site.RootWeb;
{
string to = “someone@apress.com”;
string subject = “Book Message”;
string body = “A message from SharePoint”;
HttpContext curCtx = HttpContext.Current;
HttpContext.Current = null;
bool success = SPUtility.SendEmail(thisWeb, true, true, to, subject, body);
HttpContext.Current = curCtx;
}
}
}
catch (Exception ex)
{// Exception handling skipped for clarity}
In the above code the current context is set to null to force the context to be retrieved again. Saving the current context ensures that the service works properly after the method has been executed.

IIS, Worker Process, Application Pool


What is IIS?
IIS (Internet Information Server) is one of the most powerful web servers from Microsoft Corporation that is used to host the Asp.Net web application. IIS has its own ASP.NET process engine to handle the ASP.NET request. So, when request comes from client to server, IIS takes the request and process it and send response back to the clients.
IIS means when request comes from client to the server a lot of operation is performed before sending response to the client. This is about how IIS process the request.
What is Worker Process?
Worker process (w3wp.exe) runs the ASP.NET application in IIS. This process is responsible to manage all the request and response that are coming from the client system. All the ASP.NET functionality runs under the scope of worker process. When request comes to the server from a client worker process is responsible to generate the request and response.
In single word, we can say worker process is the heart of ASP.NET web application runs on IIS.
What is Application Pool?
Simply to say about what is application pool is: A group of one or more URLs are served by a particular worker process or set of worker processes.
Application pool is the container of worker process. Application pools are used toseparate sets of worker processes that share same configuration. Application pools enable a better security, reliability, and availability for any web application.
The worker process servers as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn’t impact other web application as they are configured into different application pool.
Application pool with multiple worker process is called “Web Garden”.
http://msdn.microsoft.com/en-us/library/gg552610.aspx
Why are application pools important?
They provide a way for multiple sites to run on the same server but still have their own
worker processes and identity.
Note:
• Isolation of Different Web Application.
• Individual worker process for different web application.
• More reliably web application.
• Better Performance.
How to find the application pool account for a web application?
Go to IIS settings (type inetmgr in command mode) and select the web application on left pane and click on the “Basic Settings” on the right pane.

Difference Between SharePoint Application Pages Vs Site Pages

Application Pages:
  • Application pages are stored in the server’s file system. 
  • SharePoint Designer tool cannot be used with application pages. 
  • Application pages cannot be used within sandboxed solutions. 
  • An Application page cannot be customized and modified by end user, instead a developer is required. 
  • These are the normal .aspx pages deployed within SharePoint. Most common of them are the admin pages found in _layouts folder.
  • These are deployed either at the farm level or at application level. If they are deployed within _layouts folder or global SharePoint Virtual Directory, then they can be used by any SharePoint application (available at farm level), otherwise they can be deployed at application level only by creating a virtual directory.
  • These are typical ASP.Net aspx pages and can utilize all of the functionalities available within ASP.Net including code-behind, code-beside, inline coding etc.
  • These are compiled by .Net runtime like normal pages.
  • If you deploy your custom ASPX pages within _layouts folder or within SharePoint application using a virtual directory, you will not be able to use SharePoint master pages and have to deploy your master page within the virtual directory or _layouts folder.
  • Application Pages cannot use contents as this concept is associated with SharePoint Page Layouts not with ASP.Net.
  • Since application pages are compiled once, they are much faster
  • Normally application pages are not web part pages, hence can only contain server controls or user controls and cannot be personalized by users.
  • Easiest way to deploy your existing ASP.Net web site within SharePoint is to deploy its pages as Application Pages within SharePoint. In this way you can convert any ASP.Net web solution as SharePoint application with minimal efforts.
  • SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages not against application pages.
  • Application pages can be globalized using Resource files only. 
Site Pages:
  • Site Pages is a concept where complete or partial page is stored within content database and then actual page is parsed at runtime and delivered to end-users.
  • Site pages can be edited by using SharePoint Designer tool.
  • Site pages are used within Sandboxed solutions. 
  • A site page can be customized and modified by end user. 
  • Pages stored in Pages libraries or document libraries or at root level within SharePoint (Wiki pages) are Site Pages
  • You must be thinking why we should use such pages? There are many reasons for this. One of the biggest catch of the SharePoint is the page layouts, where you can modify page once for a specific content type and then you can create multiple pages using the same page layout with different contents. In this case, contents are stored within database for better manageability of data with all the advantages of a data driven system like searching, indexing, compression, etc and page layouts are stored on file system and final page is created by merging both of them and then the outcome is pared by SharePoint not compiled.
  • Site Pages can contain web parts as well as contents placeholders, and all of them are stored per page-instance level within database and then retrieved at run time, parsed and rendered.
  • Another advantage is they are at user-level not at web-application or farm level and can be customized per site level.
  • Since their definition is retrieved from database, they can utilize master pages stored within SharePoint masterpages library and merged with them at run time for rendering.
  • They are slower as compared to Application pages as they are parsed everytime they are accessed.
  • SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages not against application pages.
  • Since they are rendered not compiled hence it is not easy to add any inline code, code behind or code beside. Best way of adding code to these pages is through web-parts, server controls in master pages, user controls stored in "Control Templates" folder or through smart parts. If you want to add any inline code to master page, first you need to add following configuration within web.config:<PageParserPaths>
            <PageParserPath VirtualPath="/_catalogs/masterpage/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" />
    </PageParserPaths>
  • To add code behind to SharePoint master pages or page layouts.
  • Since Site pages are content pages, hence all SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages.
  • Variations can only be applied against Site pages for creating multilingual sites.
  • "SPVirtualPathProvider" is the virtual path provider responsible for handling all site pages requests.