Wednesday, August 31, 2011

Alert Template Name                                                                 Description

SPAlertTemplateType.GenericList                       The first alert template in Alerttemplates.xml. GenericList
                                                                          is used unless there is a match to one of other event types.

SPAlertTemplateType.DocumentLibrary              Notification of changes in document libraries

SPAlertTemplateType.Survey                              Notification of changes in surveys

SPAlertTemplateType.Links                                Notification of changes in links

SPAlertTemplateType.Announcements                Notification of changes in announcements

SPAlertTemplateType.Contacts                          Notification of changes in contacts

SPAlertTemplateType.Events                              Notification of changes in events

SPAlertTemplateType.Tasks                               Notification of changes in tasks

SPAlertTemplateType.DiscussionBoard              Notification of changes in discussion boards

SPAlertTemplateType.PictureLibrary                  Notification of changes in picture libraries

SPAlertTemplateType.XMLForm                       Notification of changes in XML form

SPAlertTemplateType.DataConnectionLibrary            Notification of changes in data connection libraries
                
SPAlertTemplateType.AssignedtoNotification            Assigned to task / issue list notifications

SSO configuration in MOSS 2007

Open administration site Go to Administrative tools and then select Services in though services select Microsoft Single Sign-on Service make start-up type to Automatic  and then click Apply and then start the service
After starting this service Now go to Central Administration and then go to Operations Tab in this tab Under Security configuration ---> Manage settings for Single Sign-on
Over there under Server Setting click on Manage Server Settings over there you see a form fill in those fields see the image below, after filling all fields and click OK


After this SSO Name Database will be created in DB and all other links(Administration site related to SSO) which were previously disabled will get enabled
Now under Enterprise Application Definition Settings ---> Manage Settings for Enterprise Application Definition after that click on New Items
Fill Information as shown below you can give Display name & Application Name make sure that you giving Application Name a Sensible name because once given it can not be changed,after that fill E-mail address and Select Individual Under Account Type and Select Windows authentication leave Logon Account Information as it is and click ok

After that click on Manage account information for enterprise application definitions over there in drop down box of Enterprise application definition Select Application name which you just created above and enter user account name(same account which you have use in manage server settings) and click on update account information check box and click OK

SSO Configuration is Done

WSS,MOSS 2007,Sharepoint 2010: Uploading Files to moss 2007 using WinForm

WSS,MOSS 2007,Sharepoint 2010: Uploading Files to moss 2007 using WinForm: Hi Guys my client wanted application which can upload files from client folder to MOSS 2007 Site Library Scenario:- When client past any f...

Uploading Files to moss 2007 using WinForm

Hi Guys my client wanted application which can upload files from client folder to MOSS 2007 Site Library

Scenario:- When client past any file in a Folder call XYZ File upload should start!
Conclusion :- Apply File Watcher on folder XYZ folder so that all the activities can be traced

Code for Reference :-
//Attach Watch on particular folder
FileSystemWatcher oFileSystemWatcher = new FileSystemWatcher("D:\\redhatabhi\\xyz\\");
 //add watch on folder when New file is Created/Pasted/Moved
oFileSystemWatcher.Created += new FileSystemEventHandler(oFileSystemWatcher_Created);
// use following Property to Enable Event Raise in when new file are been added
oFileSystemWatcher.EnableRaisingEvents = true;
// use following Property for including Sub-folders also
oFileSystemWatcher.IncludeSubdirectories = true;

After applying this event you job is now to upload File in MOSS 2007.
Example :-
            FileInfo file = new FileInfo(e.FullPath);
            if (file.Extension == ".exe")
            notify.ShowBalloonTip(100, "Warning", "Uploading of Executable File is Not Allowed", ToolTipIcon.Warning);          
             using (SPSite oSPSite = new SPSite(siteURL))
            {
                using (SPWeb oSPWeb = oSPSite.OpenWeb())
                {
                    SPFolder oSPFolder = oSPWeb.GetFolder(oSPWeb.Url + "/DocumentLibrary/");
                    oSPFolder.Files.Add(file.Name, File.ReadAllBytes(file.FullName), true);
                    file.Delete();
                }        
             }

Tuesday, August 30, 2011

Web Service

hi guys while i was working in Project one requirement cam across,
requirement was as follows
using/referencing web-service but should work on which ever machine my code runs(for e.g. staging server & production server).
so i came across a solution,when you add reference of any web-service you get .disco file on project-explorer window click on show all files you then be able to see some file in Reference Folder in that open .cs file
and search for this.Url after that just place code below 

ConfigurationManager.AppSettings["EmployeeLog"].ToString();

function looks like this.

public EmployeeStatus()
    {
        string str = ConfigurationManager.AppSettings["EmployeeLog"].ToString();
        if (str != null)
        {
            this.Url = str;
        }
        else
        {
            this.Url = "";
        }
    }

now make Entry in web.config App-setting
that's it you are now all set to access web-service on any server.at-least you don't need to rebuild code again and again

Friday, August 26, 2011

How to set Favicon for SharePoint 2010 site?

SharePoint 2010 comes with a orange Favicon and it's present in C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES\. Open this folder and search for favicon.ico and rename the file to Favicon_Backup.ico. Now copy your favicon to this folder and make sure it's named as "favicon.ico". Now restart IIS(open Command Prompt -> IISReset), clear browser cache/temproary internet files. Close the browser and reopen then browse the SharePoint site.
If mulitple sites are hosted in same farm and need to set different favicons for different sites then we have to update Master Page Code. Open the site with SharePoint Designer 2010 and select Master pages -> v4.master. The default.master is still present in SharePoint 2010 for backward compatibility and visual upgrade. But SharePoint 2010 uses v4.master only. Now click "Edit File" link to add the favicon code. If it asks for check out, click yes and continue.

Find and change the path of favicon. Save and close (If you have checked out then you need to check in and site collection administrator has to approve it via Site Settings -> Galleries -> Master pages and page layouts -> Check in and Approve). Now reset IIS/clear browser cache and check.

Thursday, August 18, 2011

Javascript in Hyperlink Button in Gridview


In this Blog like to share you how we can do some scripting in Gridview hyperlink & conditional formatting.
below is example

in Text you can see i am getting value from gridview IsActive and making text change if  true the DeActive else Activate

Onclick i am opening a popup window for Activation and Deactivation on value which i get in IsActive
if it true then run a javascript function ConfirmDeActiveUsers,in this Function i can pass value with the help of following way.Command is nothing but value i need to pass it to javascript function or can even use javascript over there for example i can use Alert Function in Javascript to alert ID of that particular item

<asp:HyperLink Text='<%# Convert.ToBoolean(Eval("IsActive")) ? "Deactivate" : "Activate" %>' runat="server" ID="hyperlnkView" OnClick='<%# Convert.ToBoolean(Eval("IsActive")) ? Eval("command","return ConfirmDeActiveUsers(\"{0}\");") : Eval("command","ConfirmNonActiveUsers(\"{0}\");") %>' ></asp:HyperLink>

Wednesday, August 17, 2011

Uploading File in Sharepoint Document Library in folder

                                using (SPWeb userweb = new SPSite(url).OpenWeb())
                                {
                                    userweb.AllowUnsafeUpdates = true;
                                    //here url is nothing but site url,My Documents is Folder in document library                                    SPFolder oSPFolder = userweb.GetFolder(url + "/My Documents/");
                                    //here i have a object of file which i need to upload as SPFILE                                    SPFile file = properties.ListItem.File;
                                    if (file.ModifiedBy.LoginName == currentusr)
                                    {
                                        //get file in Byte formate for Upload bz when we say oSPFolder.Files.Add it
                                         requires Byte
                                        byte[] data = file.OpenBinary();
                                        // this will upload my file to document library in that particular folder
                                        oSPFolder.Files.Add(file.Name, data, file.Author, file.Author, file.TimeCreated, DateTime.Now);
                                    }
                                }

Wednesday, August 10, 2011

Editing UserInformation List From DB for MOSS 2007 & SharePoint 2010

Many developers have to work on VM Machine for Development,due to this they have limited acces to outside world like Domain and because of that you can't add user which have there email address.
we have a twick for this open SQL server and then go to DB to which your site is attached.

Now expand Table's Structure and search for UserInfo Table.
that's it you can open this table search for tp_Email Column and add which ever Email address you want, you can add you personal Email address also

Wednesday, August 3, 2011

Getting Attachment from List Items

with the help of following Function you can get Attached files of that particular Item

public List<SPFile> GetListItemAttachments(SPListItem listItem)
        {
            try
            {
                List<SPFile> lstSPFile = null;
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite oSite = new SPSite(
                       listItem.ParentList.ParentWeb.Site.ID))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPFolder folder = listItem.ParentList.RootFolder.
                               SubFolders["Attachments"].SubFolders[listItem.ID.ToString()];
                            if (null != folder)
                            {
                                lstSPFile = new List<SPFile>();
                                foreach (SPFile file in folder.Files)
                                {
                                    lstSPFile.Add(file);
                                }
                            }
                        }
                    }
                });
                return lstSPFile;
            }
            catch
            {
                return null;
            }
        }

Getting SPUser Object from PeoplePicker Field

if you are working on Sharepoint workflows and you want PeoplePicker Value in workflow 
with the help of following code we can get SPUser object.

SPFieldUser userField = (SPFieldUser)_activeWorkflow.ParentItem.Fields.GetField("AssignedTo");
SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(Convert.ToString(spI["AssignedTo"]));
SPUser user = fieldValue.User;

Adding SPUtility Mail Headers TO,CC,BCC

Using Following Code you can send mail TO,CC,BCC

StringDictionary headers = new StringDictionary();

headers.Add("to", sendTo);
headers.Add("cc", "");
headers.Add("bcc", "");
headers.Add("from", "admin@test.com");
headers.Add("subject", "Testing");
headers.Add("content-type", "text/html");
SPUtility.SendEmail(web,headers, Body);

Automatically Dispose SharePoint objects using C#

Follwoing Code help yoiu to automaticaly Dispose SPSite & SPWeb Object
this is because SPSite & SPWeb implements IDisposable Interface
you can use "Using" for disposing other objects which implements IDisposable Interface.

using(SPSite oSPsite = new SPSite("http://server"))
{
  using(SPWeb oSPWeb = oSPSite.OpenWeb())
   {
       str = oSPWeb.Title;
       str = oSPWeb.Url;
   }

Friday, July 29, 2011

Hiding Ribbon in SP2010

The new ribbon in SP2010 looks nice from a editors point of view. All web-parts seems controlled by the contextual ribbon.Using web-parts on a public website, like a discussion board etc....
The public website is fully skinned now how do we make only the editor to see the ribbon for page.
Answer is as follows :- place you Ribbon Div inside below tag and see the result

<sharepoint:spsecuritytrimmedcontrol permissions="”ManageWeb”" runat="”server”"> 
Control/Ribbon
</sharepoint:spsecuritytrimmedcontrol> 
 
this was for hiding Ribbon but with the help of this we can hide our control also.instead of div just place you control over there.

Permission used in above example is ManageLists we do have other permissions also as follows :-

AddAndCustomizePages
AddDelPrivateWebParts
AddListItems
ApplyStyleSheets
ApplyThemeAndBorder
ApproveItems
BrowseDirectories
BrowseUserInfo
CancelCheckout
CreateAlerts
CreateGroups
CreateSSCSite
DeleteListItems
DeleteVersions
EditListItems
EditMyUserInfo
EmptyMask
EnumeratePermissions
FullMask
ManageAlerts
ManageLists
ManagePermissions
ManagePersonalViews
ManageSubwebs
ManageWeb
Open
OpenItems
UpdatePersonalWebParts
UseClientIntegration
UseRemoteAPIs
ViewFormPages
ViewListItems
ViewPages
ViewUsageData
ViewVersions

Custom SpellCheck in Moss 2007 for Page

Register this Js in you page where you want to use Spell Check


Use followinf funtion in you button click and you are ready yo have custom SpellCheck ready

function doSpellCheck() {
        SpellCheckEntirePage('/_vti_bin/SpellCheck.asmx', '/_layouts/SpellChecker.aspx');
    }

Javascript Formating

Following Function can be use to IsNumeric & Formating Phone Number

    function fncInputNumericValuesOnly() {
        if (!(event.keyCode == 45 || event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 || event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 57 || event.keyCode == 0 || event.keyCode == 46)) {
            event.returnValue = false;
        }
    }

This Function will return Formated Phone Number E.g : (123)-123-1234

    function fncInputNumericValuesOnlyPhone(objFormField) {
        if (!(event.keyCode == 45 || event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 || event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 0 || event.keyCode == 46 || event.keyCode == 57)) {
            event.returnValue = false;
        }
        else {
            var PH = objFormField.value;
            PH = PH.replace("(", "");
            PH = PH.replace(")", "");
            PH = PH.replace("-", "");
            PH = PH.replace(" ", "");
            if (PH.length < 3) {
                objFormField.value = "(" + PH;
            }
            if (PH.length > 3 && PH.length <= 6) {
                objFormField.value = "(" + PH.substring(0, 3) + ") " + PH.substring(3, 6);
            }
            if (PH.length > 6) {
                objFormField.value = "(" + PH.substring(0, 3) + ") " + PH.substring(3, 6) + "-" + PH.substring(6, 10);
            }
        }
    }

Sharepoint 2007 Alert Template Name

Alert Template Name                                                              Description

SPAlertTemplateType.GenericList                                          The first alert template in Alerttemplates.xml.                                                                 GenericList is used unless there is                                                                                            a  match to one of other event types.

SPAlertTemplateType.DocumentLibrary                                 Notification of changes in document libraries

SPAlertTemplateType.Survey                                                 Notification of changes in surveys

SPAlertTemplateType.Links                                                   Notification of changes in links

SPAlertTemplateType.Announcements                                   Notification of changes in announcements

SPAlertTemplateType.Contacts                                              Notification of changes in contacts

SPAlertTemplateType.Events                                                 Notification of changes in events

SPAlertTemplateType.Tasks                                                  Notification of changes in tasks

SPAlertTemplateType.DiscussionBoard                                 Notification of changes in discussion boards

SPAlertTemplateType.PictureLibrary                                     Notification of changes in picture libraries

SPAlertTemplateType.XMLForm                                         Notification of changes in XML form

SPAlertTemplateType.DataConnectionLibrary                       Notification of changes in data connection libraries
                
SPAlertTemplateType.AssignedtoNotification                        Assigned to task / issue list notifications

Adding Context Menu List/library MOSS 2007/Sharepoint 2010

You can add this javascript sharepoint pages with the help of webparts,of using sharepoint designer

Following Javascript Function will add new Menu item Custom Menu to Custom List

function Custom_AddListMenuItems(m, ctx)
{
//this is Title
var strText = "Custom Menu";
//this will add action to be performed e.g in our case it will alert ListItem id
var strAction ="alert(currentItemID)";
//this will add Image to you Context Menu
var strSelectionImage = '';
//this will add you Menu Item to list Menu
CAMOpt(m, strText, strAction, strSelectionImage);
return true;
}

Following Javascript Function will add new Menu item Custom Menu to Custom Library

function Custom_AddDocLibMenuItems(m, ctx)
{
var strText = "Custom Menu";
var strAction ="alert(currentItemID)";
var strSelectionImage = '';
CAMOpt(m, strText, strAction,strSelectionImage);
return true
}

Hope this will help you to add and customize you Sharepoint Context Menu


Following are some usefull javascript object of Sharepoint

0: ctx[listBaseType] : 1                                                 1: ctx[listTemplate] : 101

2: ctx[listName] : {5726BE86-34A8-47F8-AB73-105E34D807F2}

3: ctx[view] : {475151F9-6C22-45FB-B19E-FFE7EC13ADC3}

4: ctx[listUrlDir] : /projects/scans

5: ctx[HttpPath] : /projects/_vti_bin/owssvr.dll?CS=65001

6: ctx[HttpRoot] : http://xxx/projects

7: ctx[serverUrl] : null                                                    8: ctx[imagesPath] : /_layouts/images/

9: ctx[PortalUrl] : null                                                    10: ctx[RecycleBinEnabled] : -1

11: ctx[isWebEditorPreview] : 0                                   12: ctx[rootFolderForDisplay] : null

13: ctx[isPortalTemplate] : null                                      14: ctx[isModerated] : false

15: ctx[recursiveView] : false                                                                                       

16: ctx[displayFormUrl] : /projects/scans/Forms/DispForm.aspx

17: ctx[editFormUrl] : /projects/scans/Forms/EditForm.aspx

18: ctx[newFormUrl] : null                                            19: ctx[ctxId] : 1                                              

20: ctx[CurrentUserId] : 24                                           21: ctx[isForceCheckout] : false

22: ctx[EnableMinorVersions] : false                             23: ctx[ModerationStatus] : 0

24: ctx[verEnabled] : 1                                                 25: ctx[isVersions] : 0

26: ctx[WorkflowsAssociated] : true                             27: ctx[ContentTypesEnabled] : false

28: ctx[SendToLocationName] :                                   29: ctx[SendToLocationUrl] :

30: ctx[OfficialFileName] :                                            31: ctx[WriteSecurity] : 1

32: ctx[SiteTitle] : Projects                                            33: ctx[ListTitle] : scans


Continu............................

0: m[language] :                                                            1: m[scrollHeight] : 0

2: m[isTextEdit] : false                                                   3: m[currentStyle] : [object]

4: m[document] : [object]                                              5: m[onmouseup] : null

6: m[oncontextmenu] : null                                             7: m[isMultiLine] : true

8: m[clientHeight] : 0                                                     9: m[onrowexit] : null

10: m[onbeforepaste] : null                                            11: m[onactivate] : null

12: m[scrollLeft] : 0                                                      13: m[lang] :

14: m[onmousemove] : null                                            15: m[onmove] : null

16: m[onselectstart] : null                                               17: m[parentTextEdit] : [object]

18: m[oncontrolselect] : null                                           19: m[canHaveHTML] : true

20: m[onkeypress] : null                                                21: m[oncut] : null

22: m[onrowenter] : null                                                23: m[onmousedown] : null

24: m[onpaste] : null                                                      25: m[className] : ms-SrvMenuUI

26: m[id] : 14_menu                                                      27: m[onreadystatechange] : null

28: m[onbeforedeactivate] : null                                    29: m[hideFocus] : false

30: m[dir] :                                                                   31: m[isContentEditable] : false

32: m[onkeydown] : null                                                33: m[clientWidth] : 0

34: m[onlosecapture] : null                                            35: m[parentElement] : [object]

36: m[ondrag] : null                                                       37: m[ondragstart] : null

38: m[oncellchange] : null                                              39: m[recordNumber] : null

40: m[onfilterchange] : null                                             41: m[onrowsinserted] : null

42: m[ondatasetcomplete] : null                                    43: m[onmousewheel] : null

44: m[ondragenter] : null                                               45: m[onblur] : null

46: m[onresizeend] : null                                                47: m[onerrorupdate] : null

48: m[onbeforecopy] : null                                            49: m[ondblclick] : null

50: m[scopeName] : HTML                                         51: m[onkeyup] : null

52: m[onresizestart] : null                                               53: m[onmouseover] : null

54: m[onmouseleave] : null                                            55: m[outerText] :

56: m[innerText] :                                                         57: m[onmoveend] : null

58: m[tagName] : MENU                                             59: m[title] :

60: m[offsetWidth] : 0                                                  61: m[onresize] : null

62: m[contentEditable] : inherit                                     63: m[runtimeStyle] : [object]

64: m[filters] : [object]                                                 65: m[ondrop] : null

66: m[onpage] : null                                                      67: m[onrowsdelete] : null

68: m[tagUrn] :                                                             69: m[offsetLeft] : -1

70: m[clientTop] : 0                                                      71: m[style] : [object]

72: m[onfocusout] : null                                                73: m[clientLeft] : 0

74: m[ondatasetchanged] : null                                      75: m[canHaveChildren] : true

76: m[ondeactivate] : null                                              77: m[isDisabled] : false

78: m[onpropertychange] : null                                     79: m[ondragover] : null

80: m[onhelp] : null                                                       81: m[ondragend] : null

82: m[onbeforeeditfocus] : null                                      83: m[disabled] : false

84: m[onfocus] : null                                                      85: m[behaviorUrns] : [object]

86: m[accessKey] :                                                       87: m[onscroll] : null

88: m[onbeforeactivate] : null                                        89: m[onbeforecut] : null

90: m[readyState] : complete                                        91: m[all] : [object]

92: m[sourceIndex] : 1421                                            93: m[onclick] : null

94: m[scrollTop] : 0                                                      95: m[oncopy] : null

96: m[onfocusin] : null                                                  97: m[tabIndex] : 0

98: m[onbeforeupdate] : null                                          99: m[outerHTML] :


100: m[innerHTML] :                                                  101: m[ondataavailable] : null

102: m[offsetHeight] : 0                                                103: m[onmovestart] : null

104: m[onmouseout] : null                                             105: m[scrollWidth] : 0

106: m[offsetTop] : -1                                                  107: m[onmouseenter] : null

108: m[onlayoutcomplete] : null                                     109: m[offsetParent] : [object]

110: m[onafterupdate] : null                                           111: m[ondragleave] : null

112: m[children] : [object]                                             113: m[nodeName] : MENU

114: m[nodeValue] : null                                               115: m[ownerDocument] : [object]

116: m[firstChild] : null                                                  117: m[lastChild] : null

118: m[childNodes] : [object]                                       119: m[nextSibling] : null

120: m[parentNode] : [object]                                      121: m[type] :

122: m[compact] : false                                                 123: m[nodeType] : 1

124: m[previousSibling] : [object]                                  125: m[attributes] : [object]

Friday, July 15, 2011

ECMA + JScript

In this blog we are using ECMA + Jquery For Quering Sharepoint 2010 List and then get result with the help of Jquery Like Foreach and then assign to respective field in page

Declare one variable in which we can store our query


var soapEnv =
"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
<soapenv:Body> \
<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
<listName>New Messages</listName> \
<query><Query><Where><Eq><FieldRef Name='ID'/><Value Type='Counter'>" + ValueID + "</Value></Eq></Where></Query></query> \
<viewFields> \
<ViewFields> \
<FieldRef Name='Title' /> \
<FieldRef Name='Description' /> \
<FieldRef Name='Address' /> \
<FieldRef Name='Name' /> \
</ViewFields> \
</viewFields> \
</GetListItems> \
</soapenv:Body> \
</soapenv:Envelope>";


Now here with the help of Jquery Ajax we can query List and give our Query

$.ajax({
url: getServerUrl() + "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
complete: processResult,
contentType: "text/xml; charset=\"utf-8\""
});

Now you are ready to get data so with the help of Jquery get Value one by one

function processResult(xData, status) {
// following thing will loop foreach Item
$(xData.responseXML).find("z\\:row").each(function () {
//taking value of field Title,Description,Address,Name
var header = $(this).attr("Title");
var description = $(this).attr("Description");
var from = $(this).attr("Address");
var category = $(this).attr("Name");
//you are ready to assign retreved data in page
});

Close Sharepoint 2010 Popup Window

hey with the help of following script you can close Sharepoint 2010 popup window & the window/Frame Element(IFrame)

OnClientClick="javascript:window.frameElement.commitPopup();"

Assign PeoplePicker with logedinuser

function PeoplePicker() {
this.context = null;
this.web = null;
this.currentUser = null;
this.parentTagId = null

this.SetParentTagId = function (id) {
this.parentTagId = id;
}

this.SetLoggedInUser = function () {
if (this.parentTagId != null) {
this.getWebUserData();
}
}

this.getWebUserData = function () {
this.context = new SP.ClientContext.get_current();
this.web = this.context.get_web();
this.currentUser = this.web.get_currentUser();
this.currentUser.retrieve();
this.context.load(this.web);
this.context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod),
Function.createDelegate(this, this.onFailureMethod));
}

this.onSuccessMethod = function () {
this.setDefaultValue(this.currentUser.get_title());
}
this.onFailureMethod = function () {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

this.setDefaultValue = function (value) {
var parentTag = document.getElementById(this.parentTagId);
if (parentTag != null) {
var peoplePickerTag = this.getTagFromIdentifierAndTitle(parentTag, 'div',
'UserField_upLevelDiv', 'People Picker');
if (peoplePickerTag) {
peoplePickerTag.innerHTML = value;
}
}
}

this.getTagFromIdentifierAndTitle = function (parentElement, tagName, identifier, title) {

var len = identifier.length;
var tags = parentElement.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;
}


}

ExecuteOrDelayUntilScriptLoaded(SetWebUserData, "sp.js");
function SetWebUserData() {
var pplPicker = new PeoplePicker();
pplPicker.SetParentTagId("RequesterPeoplePicker");
pplPicker.SetLoggedInUser();
}

Thursday, July 14, 2011

Sharepoint DateTimecontrol Validation

Hey hi guys if you are looking out for javascript validation for MOSS2007 & SharePoint 2010 then here is some Javascript


//this function is used to find control in page
//Tagname :- is nothing but tages in html like "INPUT","DIV"
//Identifer:- Control in sharepoint i.e DateTimeFieldDate control
//Title :- for example if we create field with "Contract Date" then out title could be "Contract Date"
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; }

//past this function in our page using sharepoint designer thats its ready to go

function PreSaveAction() { var date1 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Contract Date"); var date2 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Contract 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
}

other examples are :-
//for DropDown user following parameter

var country = getTagFromIdentifierAndTitle("select", "dropDownList", "Country");

//for TextField(Text box) user following parameter

var title = getTagFromIdentifierAndTitle("input", "TextField", "Requested Title");

//for MultipleLine-TextField user following parameter

var description = getTagFromIdentifierAndTitle("textarea", "TextField", "Description of the change");

ECMA Scritp for UpdateListItem

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
this.list = web.get_lists().getByTitle('My custom generic list');
this.oListItem = list.getItemById(1);
oListItem.set_item('Title', 'Abhijeet Updated');
oListItem.update();

clientContext.executeQueryAsync(Function.createDelegate(this, this.onUpdateListItemSuccess), Function.createDelegate(this, this.onQueryFailed));
}
function onUpdateListItemSuccess(sender, args) {
alert("list item updated");
}

function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

ECMA Script for UpdateList

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
this.list = web.get_lists().getByTitle('My custom generic list');
list.set_description('My custom generic list description');
list.update();
clientContext.load(list, 'Description');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onSiteLoadSuccess), Function.createDelegate(this, this.onQueryFailed));
}
function onSiteLoadSuccess(sender, args) {
alert("list description : " + this.list.get_description());
}

function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

ECMA Script for LoadSiteData

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
clientContext.load(web, 'Title');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onSiteLoadSuccess), Function.createDelegate(this, this.onQueryFailed));
}
function onSiteLoadSuccess(sender, args) {
alert("site title : " + web.get_title());
}

function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

ECMA Script for LoadListItemsData

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
var list = web.get_lists().getByTitle("Pages");
var camlQuery = new SP.CamlQuery();
var q = '5';
camlQuery.set_viewXml(q);
this.listItems = list.getItems(camlQuery);
clientContext.load(listItems, 'Include(DisplayName,Id)');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess),
Function.createDelegate(this, this.onQueryFailed));
}
function onListItemsLoadSuccess(sender, args) {
var listEnumerator = this.listItems.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();
var title = item.get_displayName();
var id = item.get_id();
alert("List title : " + title + "; List ID : "+ id);
}
}

function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

ECMA Script for LoadListData

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
this.list = web.get_lists().getByTitle("Images");
clientContext.load(list, 'Title', 'Id');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onListLoadSuccess),
Function.createDelegate(this, this.onQueryFailed));
}
function onListLoadSuccess(sender, args) {
alert("List title : " + this.list.get_title() + "; List ID : "+ this.list.get_id());
}

function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

ECMA Script for DeleteSite

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
this.website = web.get_webs().getByTitle('Rare Solutions');
website.deleteObject();

clientContext.executeQueryAsync(Function.createDelegate(this, this.onSiteDeleteSuccess),

Function.createDelegate(this, this.onQueryFailed));
}
function onSiteDeleteSuccess(sender, args) {
alert("site deleted");
}

function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

ECMA Script for DeleteListItem

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
this.list = web.get_lists().getByTitle('My custom generic list');
this.oListItem = list.getItemById(1);
oListItem.deleteObject();

clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemDeleteSuccess),

Function.createDelegate(this, this.onQueryFailed));
}
function onListItemDeleteSuccess(sender, args) {
alert("list item deleted");
}

function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

ECMA Scritp for DeleteList

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
this.list = web.get_lists().getByTitle('My custom generic list');
list.deleteObject();

clientContext.executeQueryAsync(Function.createDelegate(this, this.onListDeleteSuccess),

Function.createDelegate(this, this.onQueryFailed));
}
function onListDeleteSuccess(sender, args) {
alert("list deleted");
}

function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

ECMA Script for CreateSite

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
var webCreateInfo = new SP.WebCreationInformation();
webCreateInfo.set_description("All about Rare solutions.");
webCreateInfo.set_language(1033);
webCreateInfo.set_title("Rare Solutions - SharePoint and .NET");
webCreateInfo.set_url("RareSolutionsSharePoint");
webCreateInfo.set_useSamePermissionsAsParentSite(true);
webCreateInfo.set_webTemplate("BLOG#0");

this.oNewWebsite = this.web.get_webs().add(webCreateInfo);

clientContext.load(this.oNewWebsite, 'ServerRelativeUrl', 'Created');

clientContext.executeQueryAsync(Function.createDelegate(this, this.onCreateWebSuccess),

Function.createDelegate(this, this.onQueryFailed));
}
function onCreateWebSuccess(sender, args) {
alert("Web site url : " + this.oNewWebsite.get_serverRelativeUrl());
}

function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

ECMA Script CreateList

var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
var itemCreateInfo = new SP.ListItemCreationInformation();
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_title('My Custom Generic List');
listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
this.oList = web.get_lists().add(listCreationInfo);

clientContext.load(oList, 'Title', 'Id');

clientContext.executeQueryAsync(Function.createDelegate(this, this.onListCreateSuccess),
Function.createDelegate(this, this.onQueryFailed));
}
function onListCreateSuccess(sender, args) {
alert("List title : " + this.oList.get_title() + "; List ID : "+ this.oList.get_id());
}

function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}