Friday, 30 November 2012

SharePoint Create CAML Query dynamically


Most of the time we require to create dynamic caml query and hit sharepoint list to get the results.
For an example; you have custom search page where you have few filter criteria; may be in drop down. Every dropdown has approx 10 items. Now when you select “All” in each drop down that means we need to take every element of dropdown with or condition and create caml query.
Also put “And” condition between different dropdown values.
That means we have several filter with “Or” and “And” conditions.
To make it generic I have created 2 classes which help us to generate dynamic caml query.
Before we start developing code; we have to understand how CAML works in brief:-

If you have 1 query then it will be like this
<Where>
  <Eq>
    <FieldRef Name="Title" />
    <Value Type="Text">as</Value>
  </Eq>
</Where>

If you have 2 query then it will be like this
<Where>
  <Or>
    <Eq>
      <FieldRef Name="Title" />
      <Value Type="Text">as</Value>
    </Eq>
    <Eq>
      <FieldRef Name="ID" />
      <Value Type="Counter">w</Value>
    </Eq>
  </Or>
</Where>

And now for every new item (I mean more than 2 items) we will add 1 query and put join 
(<or>) in start (row no 27) and in end (row no 42). See below:-
<Where>
  <Or>
    <Or>
      <Eq>
        <FieldRef Name="Title" />
        <Value Type="Text">as</Value>
      </Eq>
      <Eq>
        <FieldRef Name="ID" />
        <Value Type="Counter">w</Value>
      </Eq>
    </Or>
    <Eq>
      <FieldRef Name="HR" />
      <Value Type="Text">w</Value>
    </Eq>
  </Or>
</Where>
Similarly we can create query for n number of items

The Code 
Below are 2 classes CamlQueryElements and CamlQuery.
CamlQueryElements: This class holds the property to build caml query.
using System;
using System.Text;

namespace SharePoint.UI
{
    public class CamlQueryElements
    {
        public string LogicalJoin { get; set; } // like <Or>, <And>
        public string ComparisonOperators { get; set; } // like <Eq>, <Contains>
        public string FieldName { get; set; } // Like Title
        public string FieldType { get; set; } // Like Text
        public string FieldValue { get; set; } // some value
    }
}
CamlQuery: This class has 2 methods.
1st method for adding elements and another for generating query.
Add element:- you can modify as you wish but at the end you have to
return IList<CamlQueryElements> object.
Generating query:- Here you need to pass IList<CamlQueryElements> object and then function will return required caml query.
using System;
using System.Text;
using System.Collections.Generic;

namespace SharePoint.UI
{
    public class CamlQuery
    {
        public IList<CamlQueryElements> AddElement()
        {
            IList<CamlQueryElements> lstOfElement = new List<CamlQueryElements>();

            lstOfElement.Add(new CamlQueryElements
            {
                ComparisonOperators = "Eq",
                FieldName = "Title",
                FieldType = "Text",
                FieldValue = "SomeTitle",
                LogicalJoin = "Or"
            });
            lstOfElement.Add(new CamlQueryElements
            {
                ComparisonOperators = "Eq",
                FieldName = "Title",
                FieldType = "Text",
                FieldValue = "SomeTitle",
                LogicalJoin = "Or"
            });
            lstOfElement.Add(new CamlQueryElements
            {
                ComparisonOperators = "Contains",
                FieldName = "Title",
                FieldType = "Text",
                FieldValue = "SomeTitle",
                LogicalJoin = "AND"
            });
            /*
              similarly we can add n number of elements
              You can change this code to fill your criteria as per your web app.
              But at the end you will return back "IList of CamlQueryElements" object.
   */

            return lstOfElement;
        }
public string GetDynamicQuery()
{
IList<CamlQueryElements> camlIlist = AddElement();
string dyanmicCamlQuery = GenerateQuery(camlIlist);
return dyanmicCamlQuery;
}

// This function loop List of camlqueryelments which has our filter criteria
// Then generate query in required format.
// At end it return string which holds caml query.
        public string GenerateQuery(IList<CamlQueryElements> lstOfElement)
        {
            StringBuilder queryJoin = new StringBuilder();
            string query = @"<{0}><FieldRef Name='{1}' /><Value {2} Type='{3}'>{4}</Value></{5}>";
            if (lstOfElement.Count > 0)
            {
                int itemCount = 0;
                foreach (CamlQueryElements element in lstOfElement)
                {
                    itemCount++;
                    string date = string.Empty;
                    // Display only Date
                    if (String.Compare(element.FieldType, "DateTime", true) == 0)
                        date = "IncludeTimeValue='false'";
                    queryJoin.AppendFormat
                   (string.Format(query, element.ComparisonOperators,element.FieldName, 
                       date, element.FieldType, element.FieldValue, element.ComparisonOperators));

                    if (itemCount >= 2)
                    {
                        queryJoin.Insert(0, string.Format("<{0}>", element.LogicalJoin));
                        queryJoin.Append(string.Format("</{0}>", element.LogicalJoin));
                    }
                }
                queryJoin.Insert(0, "<Where>");
                queryJoin.Append("</Where>");
            }
            return queryJoin.ToString();
        }
    }
}
Summary
The main point to learn here is: What’s the structure of caml query if it’s less than 3 items and if it’s more than 2 items?
Once we are clear with this; we can easily create methods to return caml query as we required.
Hope it helps.
Thanks!
Avinash









Read More

The Web application at ‘’ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.


A client of mine is used to building applications in Visual Studio 2010 as Console applications or Windows Forms Applications in SharePoint 2007.  When they were running the application on their SharePoint 2010 Server, their application kept on getting the following error, when trying to create a new instance of SPSite:
System.IO.FileNotFoundException: “The Web application at http://sharepointserver could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.”
image
To fix this in SharePoint 2010, there are a few things that should be done:
1. Under Project Properties –> Application, Ensure that the target framework to be compiled against is .NET Framework 3.5
image
2. Under Project Properties –> Build, Ensure that the platform target is set to x64
image
3. Ensure that the SPSite URL you are trying to open is in your Central Admin –> Web Application alternate access mappings

Read More

SharePoint 2010 Connected Web Parts



In SharePoint 2010 we can create two type of web parts.

image

Here we are going to use Visual Web Part template to create Connectable Web parts. In  Asp.NET the Web Parts are communicated via interfaces  this allows Web Parts to exchange information with each other at run time.  This Interfaces will define the message structure which is passed between two connectable Web Parts.

Here are the steps we need to do to create a Connectable web parts .

Define the Interface that will specify the data we wanted pass or exchange from one web part to another web part.
Create Provider Web Part.
Consumer Web Part.
First Fire of VS.NET 2010 and  create Empty SharePoint project.

image


Now Visual studio  provides you to select Deployment options.  Here we are going with  Farm based solution. because Visual Web part can not be deployed in  Sandboxed solution .

image

If you select Sandboxed solution and deploy to SharePoint you get the following error.

image

Now we need to add the Interface to our project . Here I am calling it  ICommunicationChannel. 

public interface ICommunicationChannel 
   { 
       int GetInvoiceId { get; } 
   }

Now we need to Add both Provider & Consumer Visual  Web Parts .

In provider web part UI just add  Dropdown list box.

image

Now add Consumer web part UI just  add GridView control.

image

Now open of the Provider Web part and Add our Interface to Implement as shown here.

image

Now  open of the Consumer web part  and add method to receive Provider Web Part message.

image

I am using  LINQ to SQL to connect my Data Source. Invoice and Invoice Line are tables from my Database.

image

Now we need to populate the drop down List box with Invoice ID’s from our Database table called Invoice Line. 

image

In consumer web part we need to Query the Invoice Details information for the Invoice ID passed by Provider web part . [which is selected in Provider web part drop down list].

image

Now build the project correct it if any compiler errors and then  deploy to SharePoint. Now go to the SharePoint site where you wanted add this web parts and test.

Click Edit -> Insert and select Web Part button from the Ribbon menu now select Custom from Categories ->select Provider web part->  click add button this will adds provider web part to the Page. follow the same steps to add Consumer Web Part as well .


image

Once Both Provider and Consumer web parts are added to the Page now we need to establish the connection between these two web parts.  To do click Edit Web Part on Provider web Part you will see the connections and select Consumer web Part as shown below.   

image

Here is the result of Connectable Web Parts.

image


Read More

Monday, 26 November 2012

SharePoint check if page is in edit mode in javascript



I have written javascript code in my SharePoint Page which hide some controls on the page depending on the criteria. 

I want to execute this script only when page is published and my problem was this script was executed if the page is in edit mode.


I have found that SharePoint maintain this html input control which is rendering on the page when it is in edit mode

You can refer to this control in javascript and do your work accordingly.

var pageMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;

if (pageMode == ''){
//Page is not in edit mode 
}
Read More

Read, Create and Remove Cookies in Javascript



On this page I give three functions to save, read and erase cookies. Using these functions you can manage cookies on your site.
First an introduction to cookies, and a summary of document.cookie, followed by an example. Then come the three functions and their explanation.

Cookies

Cookies were originally invented by Netscape to give 'memory' to web servers and browsers. The HTTP protocol, which arranges for the transfer of web pages to your browser and browser requests for pages to servers, is state-less, which means that once the server has sent a page to a browser requesting it, it doesn't remember a thing about it. So if you come to the same web page a second, third, hundredth or millionth time, the server once again considers it the very first time you ever came there.
This can be annoying in a number of ways. The server cannot remember if you identified yourself when you want to access protected pages, it cannot remember your user preferences, it cannot remember anything. As soon as personalization was invented, this became a major problem.
Cookies were invented to solve this problem. There are other ways to solve it, but cookies are easy to maintain and very versatile.

How cookies work

A cookie is nothing but a small text file that's stored in your browser. It contains some data:
  1. A name-value pair containing the actual data
  2. An expiry date after which it is no longer valid
  3. The domain and path of the server it should be sent to
As soon as you request a page from a server to which a cookie should be sent, the cookie is added to the HTTP header. Server side programs can then read out the information and decide that you have the right to view the page you requested or that you want your links to be yellow on a green background.
So every time you visit the site the cookie comes from, information about you is available. This is very nice sometimes, at other times it may somewhat endanger your privacy. Fortunately more and more browsers give you the opportunity to manage your cookies (deleting the one from the big ad site, for example).
Cookies can be read by JavaScript too. They're mostly used for storing user preferences.

name-value

Each cookie has a name-value pair that contains the actual information. The name of the cookie is for your benefit, you will search for this name when reading out the cookie information.
If you want to read out the cookie you search for the name and see what value is attached to it. Read out this value. Of course you yourself have to decide which value(s) the cookie can have and to write the scripts to deal with these value(s).

Expiry date

Each cookie has an expiry date after which it is trashed. If you don't specify the expiry date the cookie is trashed when you close the browser. This expiry date should be in UTC (Greenwich) time.

Domain and path

Each cookie also has a domain and a path. The domain tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie, in the case of this page www.quirksmode.org.
Please note that the purpose of the domain is to allow cookies to cross sub-domains. My cookie will not be read by search.quirksmode.org because its domain is www.quirksmode.org . When I set the domain to quirksmode.org, the search sub-domain may also read the cookie.
I cannot set the cookie domain to a domain I'm not in, I cannot make the domain www.microsoft.com . Only quirksmode.org is allowed, in this case.
The path gives you the chance to specify a directory where the cookie is active. So if you want the cookie to be only sent to pages in the directory cgi-bin, set the path to /cgi-bin. Usually the path is set to /, which means the cookie is valid throughout the entire domain.
This script does so, so the cookies you can set on this page will be sent to any page in the www.quirksmode.org domain (though only this page has a script that searches for the cookies and does something with them).

document.cookie

Cookies can be created, read and erased by JavaScript. They are accessible through the property document.cookie. Though you can treat document.cookie as if it's a string, it isn't really, and you have only access to the name-value pairs.
If I want to set a cookie for this domain with a name-value pair 'ppkcookie1=testcookie' that expires in seven days from the moment I write this sentence, I do
document.cookie =
  'ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'
  1. First the name-value pair ('ppkcookie1=testcookie')
  2. then a semicolon and a space
  3. then the expiry date in the correct format ('expires=Thu, 2 Aug 2001 20:47:11 UTC')
  4. again a semicolon and a space
  5. then the path (path=/)
This is a very strict syntax, don't change it! (Of course the script manages these dirty bits for you)
Also, even though it looks like I'm writing this whole string to the string document.cookie, as soon as I read it out again I only see the name-value pair:
ppkcookie1=testcookie
If I want to set another cookie, I again do
document.cookie =
  'ppkcookie2=another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'
The first cookie is not overwritten, as it would when document.cookiewould be a real string. Instead the second one is added todocument.cookie, so if we read it out we get
ppkcookie1=testcookie; ppkcookie2=another test
If I reset a cookie
document.cookie =
  'ppkcookie2=yet another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'
the old cookie is overwritten and document.cookie reads
ppkcookie1=testcookie; ppkcookie2=yet another test
To read out a cookie you have to treat document.cookie as a string and search for certain characters (semicolons, for instance) and for the cookie name. I'll explain how to do it below.
Finally, to remove a cookie, set it with an expiry date before today. The browser sees that the cookie has expired and removes it.
document.cookie =
  'ppkcookie2=yet another test; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/'

Example

If you're thoroughly confused by all this strange syntax, try the example below. You can set two cookies, ppkcookie1 and ppkcookie2. Fill in the desired value in the text box.
The value of the cookie should be 
For comparision, read out document.cookie.
I set the cookies to remain active for seven days. If you return to this page within that time, you'll get an alert that the cookie(s) is/are still active. Try it by setting a cookie, then reloading this page.

The scripts

These are the three scripts you need.
function createCookie(name,value,days) {
 if (days) {
  var date = new Date();
  date.setTime(date.getTime()+(days*24*60*60*1000));
  var expires = "; expires="+date.toGMTString();
 }
 else var expires = "";
 document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
 var nameEQ = name + "=";
 var ca = document.cookie.split(';');
 for(var i=0;i < ca.length;i++) {
  var c = ca[i];
  while (c.charAt(0)==' ') c = c.substring(1,c.length);
  if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
 }
 return null;
}

function eraseCookie(name) {
 createCookie(name,"",-1);
}

Explanation

The functions are not very difficult, the hardest part is creating the correct syntax for setting a cookie.

createCookie

When calling createCookie() you have to give it three bits of information: the name and value of the cookie and the number of days it is to remain active. In this case the name-value pair should becomeppkcookie=testcookie and it should be active for 7 days.
createCookie('ppkcookie','testcookie',7)
If you set the number of days to 0 the cookie is trashed when the user closes the browser. If you set the days to a negative number the cookie is trashed immediately.
The function receives the arguments and starts doing its job.
function createCookie(name,value,days) {
First of all see if there is a days value. If there isn't we don't need to do the time calculation.
 if (days) {
If there is, create a new Date object containing the current date.
  var date = new Date();
Now get the current Time (in milliseconds) and add the required number of days (in milliseconds). Set the Time of the date to this new value, so that it now contains the date in milliseconds that the cookie should expire.
  date.setTime(date.getTime()+(days*24*60*60*1000));
Set the variable expires to this date in the UTC/GMT format required by cookies.
  var expires = "; expires="+date.toGMTString();
 }
If 0 is passed to the function, expires is not set and the cookie expires when the user closes his browser..
 else var expires = "";
Finally write the new cookie into document.cookie in the correct syntax.
 document.cookie = name+"="+value+expires+"; path=/";
}
Cookie created.

readCookie

To read out a cookie, call this function and pass the name of the cookie. Put the name in a variable. First check if this variable has a value (if the cookie does not exist the variable becomes null, which might upset the rest of your function), then do whatever is necessary.
var x = readCookie('ppkcookie1')
if (x) {
 [do something with x]
}
The function receives the argument and starts.
function readCookie(name) {
We're going to search for the name of the cookie, followed by an =. So create this new string and put it in nameEQ:
 var nameEQ = name + "=";
Then split document.cookie on semicolons. ca becomes an array containing all cookies that are set for this domain and path.
 var ca = document.cookie.split(';');
Then we go through the array (so through all cookies):
 for(var i=0;i < ca.length;i++) {
Set c to the cookie to be checked.
  var c = ca[i];
If the first character is a space, remove it by using the substring()method. Continue doing this until the first character is not a space.
  while (c.charAt(0)==' ') c = c.substring(1,c.length);
Now string c begins with the name of the current cookie. If this is the name of the desired cookie
  if (c.indexOf(nameEQ) == 0)
we've found what we were looking for. We now only need to return the value of the cookie, which is the part of c that comes after nameEQ. By returning this value we also end the function: mission accomplished.
  if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
 }
If, after having gone through all cookies, we haven't found the name we're looking for, the cookie is not present. We return null.
 return null;
}
Cookie read.

eraseCookie

Erasing is extremely simple.
eraseCookie('ppkcookie')
Pass the name of the cookie to be erased
function eraseCookie(name) {
and call createCookie() to set the cookie with an expiry date of one day ago.
 createCookie(name,"",-1);
}
The browser, seeing that the expiry date has passed, immediately removes the cookie.
Read More

Add Event Handler Feature in Sharepoint

This example simply shows how to handle delete item event of list in share point.




Create the event handler in visual studio
  1. Create a new project in Visual Studio by clicking File, pointing to New, and then clicking Project.
  2. In the New Project dialog box, select Visual C# in theProject types box, select Class Library in theTemplates box, type DeletingEventHandler in theName box, and then click OK.
  3. In Solution Explorer, select DeletingEventHandler, and click Add Reference on the Project menu.
  4. In the Add Reference dialog box, selectMicrosoft.SharePoint on the .NET tab and then clickOK.
  5. Add the following code within the class to override theItemDeleting method.
public override void ItemDeleting(SPItemEventProperties properties)
{
properties.Cancel = true;
properties.ErrorMessage = "You can not delete item from " + 
properties.RelativeWebUrl;
}

6. In Solution Explorer, right-click the DeletingEventHandlernode, and then click
Properties.

7. In the Properties dialog box, click the Signing tab, selectSign the asembly, select
Choose a strong name key file, and then click .

8. In the Create Strong Name Key dialog box, typeDeletingEventHandler.snk in the
Key file name box, optionally specify a password for the key, and then click OK.

9. Build the project.

10. Find the \DeletingEventHandler\bin\Debug folder in the Visual Studio Projects folder, and
drag the DeletingEventHandler.dll file toLocal_Drive:\WINDOWS\assembly to place the
DLL in the global assembly cache.


To Add Event handler as a windows share point services feature
  1. Create a folder in Local_Drive:/Program Files/Common Files/Microsoft Shared/web server extensions/12/TEMPLATE/FEATURES calledDeletingEventHandler.
  2. Create a Feature.xml file in this folder like the following that identifies the Feature and its element manifest file and sets the Feature scope to Web site.
    Xml
    GUID">
    xmlns="http://schemas.microsoft.com/sharepoint/">
    
       
    
  3. To replace the GUID placeholder in the previous Idattribute, generate a GUID by running guidgen.exe located in Local_Drive:\Program Files\Microsoft Visual Studio 8.
  4. Create an Elements.xml file in the DeletingEventHandler folder that identifies the assembly, class, and method to implement as the event handler. This example applies the event handler to all announcements lists of a site, as specified by the ListTemplateId attribute. For the IDs of other default Windows SharePoint Services list template types, see the Type attribute description of theListTemplate element.
    Xml
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <Receivers ListTemplateId="104">
       <Receiver>
          <Name>DeletingEventHandlerName>
          <Type>ItemDeletingType>
          <SequenceNumber>10000SequenceNumber>
          <Assembly>DeletingEventHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a26b5449ac4a4cf3Assembly>
          <Class>DeletingEventHandler.DeletingActionClass>
          <Data>Data>
          <Filter>Filter>
       Receiver>
    Receivers>
    Elements>
  5. To get the Public Key Token of the assembly, in Windows Explorer find the DeletingEventHandler.dll file in theLocal_Drive:\WINDOWS\assembly, right-click the file, clickProperties, and on the General tab of the Propertiesdialog box, select and copy the token.
  6. At a command prompt, navigate to \Program Files\Common Files\Microsoft Shared\web server extensions\12\BINon the local drive, and type each of the following commands to install the Feature in the deployment, activate the Feature on a specified subsite, and reset Microsoft Internet Information Services (IIS) so that the changes take effect:
    stsadm -o installfeature -filename DeletingEventHandler\Feature.xml
    
    stsadm -o activatefeature -filename DeletingEventHandler\Feature.xml -url http://Server/Site/Subsite
    
    iisreset
  7. Try to delete an item in an announcements list on the specified Web site to see the effects of the event handler Feature

Reference - http://msdn.microsoft.com/
Read More

Translate

Total Pageviews

Powered By Blogger · Designed By Seo Blogger Templates