Tuesday, June 5, 2012

WorkFlow SharePoint 2010


using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Workflow;
using System.Collections;
namespace test.Layouts.test
{
    public partial class test6 : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnClick_Click(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Announcements"];
                    SPListItem item = null;
                    SPQuery query = new SPQuery();
                    query.Query = "<Where><Contains><FieldRef Name='Title'/><Value  Type='Text'>Microsoft</Value></Contains></Where>";
                    query.RowLimit = 2;

                    SPListItemCollection items = list.GetItems(query);
                    if (items.Count > 0)
                    {
                        item = items[0];
                        lbl1.Text = item["Title"].ToString();

                        if (items[1] != null)
                        {
                            item = items[1];
                            lbl2.Text = item["Title"].ToString();
                        }
                        else { lbl2.Text = "Title Null"; }
                    }
                }
            }
        }
        protected void btnClick1_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList announcements = web.Lists["Announcements"];
                        SPList tasks = web.Lists["Tasks"];
                        SPList history = web.Lists["Workflow History"];
                        SPWorkflowTemplateCollection templateColl = web.WorkflowTemplates;
                        //int i = 0;
                        //foreach (SPWorkflowTemplate template1 in templateColl)
                        //{
                        //    lbl2.Text += i + ". " + template1.Name + " # ";
                        //    i++;
                        //}
                        SPWorkflowTemplate template = web.WorkflowTemplates.GetTemplateByName("Approval - SharePoint 2010", web.Locale);
                        SPWorkflowAssociation association = SPWorkflowAssociation.CreateListAssociation(template, "Announcements Approval", tasks, history);
                        announcements.WorkflowAssociations.Add(association);
                        //announcements.WorkflowAssociations.Remove(association);
                        announcements.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                lbl3.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick2_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPWorkflowAssociationCollection workflowsToUpdate = null;

                        SPList announcements = web.Lists["Announcements"];
                        SPList tasks = web.Lists["Tasks"];
                        SPList history = web.Lists["Workflow History"];
                        SPWorkflowTemplate template = web.WorkflowTemplates[new Guid("8AD4D8F0-93A7-4941-9657-CF3706F00409")]; //Approval - SharePoint 2010

                        workflowsToUpdate = announcements.WorkflowAssociations;
                        lbl1.Text += "Workflows associations in workflowsToUpdate: " + workflowsToUpdate.Count + " # ";

                        SPWorkflowAssociation workflow1 = SPWorkflowAssociation.CreateListAssociation(template, "Workflow 1", tasks, history);
                        announcements.WorkflowAssociations.Add(workflow1);
                        lbl2.Text += "Workflows associations in workflowsToUpdate after adding 'Workflow 1': " + workflowsToUpdate.Count + " # ";

                        SPWorkflowAssociation workflow2 = SPWorkflowAssociation.CreateListAssociation(template, "Workflow 2", tasks, history);
                        announcements.WorkflowAssociations.Add(workflow2);
                        lbl3.Text += "Workflows associations in workflowsToUpdate after adding 'Workflow 2': " + workflowsToUpdate.Count + " # ";
                    }
                }
            }
            catch (Exception ex)
            {
                lbl4.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick3_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        //foreach (SPWorkflowTemplate wfTemplate in web.WorkflowTemplates)
                        //{
                        //    if (wfTemplate.Id.Equals(new Guid("3BC0C1E1-B7D5-4e82-AFD7-9F7E59B60409"))) // .Name.Contains("Approval - SharePoint 2010"))
                        //    {
                        //        lbl1.Text += wfTemplate.Name + " @@ "; // .Id + " @@ "; // wfTemplate.Name.Contains("Approval");
                        //    }
                        //    else
                        //    {
                        //        lbl2.Text += wfTemplate.Name + " # "; ;
                        //    }
                        //}
                        SPWorkflowTemplate template = web.WorkflowTemplates.GetTemplateByBaseID(new Guid("8AD4D8F0-93A7-4941-9657-CF3706F00409"));
                        if (template == null || !template.Name.Contains("Approval")) //Announcements Approval
                        {
                            throw new ArgumentException("Expected to find the Approval workflow " + "template. Please verify the template ID and server type.");
                        }
                        else
                        {
                            lbl3.Text = template.Name + " # ";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbl4.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick4_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPWorkflowTemplate template = web.WorkflowTemplates[new Guid("8AD4D8F0-93A7-4941-9657-CF3706F00409")];
                        lbl1.Text += template.Name + " # ";
                        if (template == null)
                        {
                            throw new ArgumentException("The specified template could not be found.");
                        }
                        template = web.WorkflowTemplates[39];
                        lbl2.Text += template.Name + " # ";
                    }
                }
            }
            catch (Exception ex)
            {
                lbl4.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick5_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList announcements = web.Lists["Announcements"];

                        bool isRunning = false;
                        while (!isRunning)
                        {
                            SPWorkflowAssociation association = announcements.WorkflowAssociations.GetAssociationByName("Announcements Approval", web.Locale);
                            lbl2.Text = association.RunningInstances.ToString();
                            isRunning = (association.RunningInstances > 0);
                            System.Threading.Thread.Sleep(100);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbl3.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick6_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite adminSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb adminWeb = adminSite.OpenWeb())
                    {
                        SPUser user1 = adminWeb.Users["Domain\\user1"];
                        SPUser user2 = adminWeb.Users["Domain\\user2"];

                        using (SPSite user1Site = new SPSite(SPContext.Current.Site.ID, user1.UserToken))
                        {
                            using (SPWeb user1Web = user1Site.OpenWeb())
                            {
                                user1Web.AllowUnsafeUpdates = true;
                                lbl1.Text += user1.UserToken.ToString() + " # ";
                                SPList list = user1Web.Lists["Announcements"];
                                SPListItem item = list.GetItemById(1);
                                item["Title"] += " [updated by user1]";
                                item.Update();
                                user1Web.AllowUnsafeUpdates = false;
                            }
                        }
                        using (SPSite user2Site = new SPSite(SPContext.Current.Site.ID, user2.UserToken))
                        {
                            using (SPWeb user2Web = user2Site.OpenWeb())
                            {
                                lbl2.Text += user1.UserToken.ToString() + " # ";
                                SPList list = user2Web.Lists["Announcements"];
                                SPListItem item = list.GetItemById(2);
                                item[Title] += " [updated by user2]";
                                item.Update();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbl3.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick7_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["Announcements"];
                        SPListItem item = list.GetItemById(1);

                        bool isRunning = false;
                        while (!isRunning)
                        {
                            SPWorkflowAssociation assoc = list.WorkflowAssociations.GetAssociationByName("Announcements Approval", web.Locale);
                            lbl1.Text = item[list.WorkflowAssociations[assoc.Id].Name].ToString();
                            if (assoc.RunningInstances > 0)
                            {
                                lbl1.Text = "Workflow already started # ";
                                isRunning = true;
                            }
                            else if (Convert.ToInt32(item[list.WorkflowAssociations[assoc.Id].Name]) == 15)
                            {
                                lbl1.Text = "Workflow Cancled # ";
                                isRunning = true;
                            }
                            else
                            {
                                //site.WorkflowManager.StartWorkflow(item, assoc, String.Empty);
                                site.WorkflowManager.StartWorkflow(item, assoc, assoc.AssociationData, SPWorkflowRunOptions.Synchronous);
                                System.Threading.Thread.Sleep(1000);
                                item.EnsureWorkflowInformation();

                                isRunning = (assoc.RunningInstances > 0);
                                System.Threading.Thread.Sleep(100);

                                SPWorkflowTask task = item.Tasks[0];
                                String title = task["Title"].ToString();
                                if (title == null || !title.StartsWith("Please approve"))
                                {
                                    throw new System.FormatException("Unexpected task title: This task was not assigned " + "by the SharePoint 2010 Approval workflow.");
                                }
                                else
                                {
                                    lbl2.Text = "Workflow Started # ";
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbl3.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick8_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList announcements = web.Lists["Announcements"];
                        SPList tasks = web.Lists["Tasks"];
                        SPList history = web.Lists["Workflow History"];
                        SPWorkflowTemplate template = web.WorkflowTemplates.GetTemplateByName("Approval - SharePoint 2010", web.Locale);
                        SPWorkflowAssociation workflow = SPWorkflowAssociation.CreateListAssociation(template, "My Basic Workflow", tasks, history);
                        announcements.WorkflowAssociations.Add(workflow);
                        site.WorkflowManager.StartWorkflow(announcements.GetItemById(2), workflow, String.Empty, SPWorkflowRunOptions.Synchronous);
                        lbl1.Text += "Workflow Started for Item 1";
                        site.WorkflowManager.StartWorkflow(announcements.GetItemById(3), workflow, String.Empty, SPWorkflowRunOptions.SynchronousAllowPostpone);
                        lbl2.Text += "Workflow Started for Item 2";
                        site.WorkflowManager.StartWorkflow(announcements.GetItemById(4), workflow, String.Empty, SPWorkflowRunOptions.Asynchronous);
                        lbl3.Text += "Workflow Started for Item 3";
                    }
                }
            }
            catch (Exception ex)
            {
                lbl4.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick9_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["Announcements"];
                        SPListItem item = list.GetItemById(4);
                        //SPWorkflowAssociation assoc = list.WorkflowAssociations.GetAssociationByName("Announcements Approval", web.Locale);
                        //SPWorkflowAssociationCollection objWorkflowAssociationCollection;
                        //SPWorkflowManager objWorkflowManager;

                        SPWorkflowAssociation assoc = list.WorkflowAssociations.GetAssociationByName("Announcements Approval", web.Locale);

                        //foreach (SPWorkflowAssociation objWorkflowAssociation in objWorkflowAssociationCollection)
                        //{
                        //    SPWorkflowAssociation assoc = list.WorkflowAssociations.GetAssociationByName("Announcements Approval", web.Locale);                           

                        //    if (objWorkflowAssociation.BaseId == wfguid)
                        //    {
                        //        FCTimerJobListItem["wfguid"] = objWorkflowAssociation.BaseId.ToString();
                        //        FCTimerJobListItem.Update();
                        //        objWorkflowManager.StartWorkflow(ResignationListItem, objWorkflowAssociation, objWorkflowAssociation.AssociationData, true);

                        //        site.WorkflowManager.StartWorkflow(item, assoc, assoc.AssociationData, true);
                        //    }
                        //}

                        if (assoc.Id != null)
                        {
                            //site.WorkflowManager.StartWorkflow(item, assoc, assoc, String.Empty);
                            site.WorkflowManager.StartWorkflow(item, assoc, assoc.AssociationData, SPWorkflowRunOptions.Synchronous);
                        }
                        else
                        {
                            lbl2.Text = "No Workflow was associated with selected list item " + assoc.Id + " # ";
                        }
                        System.Threading.Thread.Sleep(5000);
                        item.EnsureWorkflowInformation();
                        SPWorkflowTask task = item.Tasks[0];

                        task[SPBuiltInFieldId.ExtendedProperties] += "ows_Color='Blue'";
                        Hashtable properties = SPWorkflowTask.GetExtendedPropertiesAsHashtable(task);
                        if (properties["Color"].ToString() != "Blue")
                        {
                            throw new Exception("The extended property 'Color' " + "was not set to the expected value 'Blue'.");
                        }
                        else
                        {
                            lbl2.Text = "Color is " + properties["Color"].ToString() + " # ";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbl3.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick10_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList docs = web.Lists["Shared Documents"];
                        SPList tasks = web.Lists["Tasks"];
                        SPList history = web.Lists["Workflow History"];
                        SPWorkflowTemplate template = web.WorkflowTemplates.GetTemplateByBaseID(new Guid("8AD4D8F0-93A7-4941-9657-CF3706F00409"));  //Approval - SharePoint 2010
                        //SPWorkflowAssociation workflow = SPWorkflowAssociation.CreateListAssociation(template, "Document Approval", tasks, history);
                        SPWorkflowAssociation workflow = docs.WorkflowAssociations.GetAssociationByName("Document Approval", web.Locale);
                        //docs.WorkflowAssociations.Add(workflow);
                        String data = String.Format("<dfs:myFields xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\' xmlns:dms=\'http://schemas.microsoft.com/office/2009/documentManagement/types\' xmlns:dfs=\'http://schemas.microsoft.com/office/infopath/2003/dataFormSolution\' xmlns:q=\'http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields\' xmlns:d=\'http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields\' xmlns:ma=\'http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes\' xmlns:pc=\'http://schemas.microsoft.com/office/infopath/2007/PartnerControls\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\"><dfs:queryFields></dfs:queryFields><dfs:dataFields><d:SharePointListItem_RW><d:Approvers><d:Assignment><d:Assignee><pc:Person><pc:DisplayName>{0}</pc:DisplayName><pc:AccountId>{1}</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person></d:Assignee><d:Stage xsi:nil=\'true\' /><d:AssignmentType>Serial</d:AssignmentType></d:Assignment></d:Approvers><d:ExpandGroups>true</d:ExpandGroups><d:NotificationMessage /><d:DueDateforAllTasks xsi:nil=\'true\' /><d:DurationforSerialTasks xsi:nil=\'true\' /><d:DurationUnits>Day</d:DurationUnits><d:CC /><d:CancelonRejection>false</d:CancelonRejection><d:CancelonChange>false</d:CancelonChange><d:EnableContentApproval>false</d:EnableContentApproval></d:SharePointListItem_RW></dfs:dataFields></dfs:myFields>", "TRAINING0\\latheef.hyder", "TRAINING0\\latheef.hyder");
                        site.WorkflowManager.StartWorkflow(docs.GetItemById(8), workflow, data);
                        lbl1.Text += "Workflow Started # ";
                        lbl2.Text += data + " # "; // SerialtrueDayfalsefalsefalse # 
                    }
                }
            }
            catch (Exception ex)
            {
                lbl4.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
    }
}
The Workflow status are constants (integers), So you'll need to refer to a list like:
1. Status: Value
2. Not Started: 0
3. Failed On Start: 1
4. In Progress: 2
5. Error Occurred: 3
6. Canceled: 4
7. Completed: 5
8. Failed On Start(Retrying): 6
9. Error Occurred (Retrying): 7
10. Canceled: 15
11. Approved: 16
12. Rejected: 17

Tuesday, May 29, 2012

ECMA SCRIPT SHAREPOINT 2010

SharePoint provides two sets of JavaScript file: minified and unminified/debug version.
For example sp.js file is minified and sp.debug is minified and debug version. The default master page in SharePoint has a scriptmanager in the page and whose ScriptMode is set to auto, as a result the minified version of js file loaded.
If you want to use debug version you can add the <deployment retail="false" /> in the <system.web> section of the web.config. In the production you need to remove this entry to make sure minified version is used.

Managed Client
DLL's needed : Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll. Find these files in the 14/ISAPI folder. Usually, the location would be at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI".

Silverlight
Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll. They find at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin".

ECMAScript
SP.js file - The file fund at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS".

SharePoint object model syntax:-
Server side syntax        Client side syntax 
SPContext                    ClientContext
SPSite                          Site
SPWeb                        Web
SPList                          List

After saving the .js file, press Ctrl + Shift + J to update the JavaScript IntelliSense.
Tip: Sometimes, you might have to press Ctrl + Shift + J for each .js file referenced.

please replace the below lines.... : http://msdn.microsoft.com/en-us/library/ee535709.aspx
{code}
<script type=”text/ecmascript” src=”/_layouts/SP.Core.js” />
<script type=”text/ecmascript” src=”/_layouts/SP.Debug.js” />
<script type=”text/ecmascript” src=”/_layouts/SP.Runtime.Debug.js” />
{code}
With
{code}
<SharePoint:ScriptLink ID=”ScriptLink1″ Name=”sp.debug.js” LoadAfterUI=”true” Localizable=”false” runat=”server” />
{code}

<!-- http://msdn.microsoft.com/en-us/library/ff798328.aspx -->
    <script type="text/javascript" src="/_layouts/SP.debug.js" ></script>
    <%--  CreateList --%>
    <script type="text/javascript">
        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());
        }</script>
    ​
    <%--  CreateSite --%>
    <script type="text/javascript">
        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());
        }</script>
    ​
    <%--     DeleteList--%>
    <script type="text/javascript">
        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());
        }</script>
    ​
    <%-- DeleteListItem --%>
    <script type="text/javascript">
        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());
        }</script>
    ​
    <%--  DeleteSite --%>
    <script type="text/javascript">
        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());
        }</script>
    ​
    <%-- LoadListData --%>
    <script type="text/javascript">
        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());
        }</script>
    ​
    <%-- LoadListItemsData --%>
    <script type="text/javascript">
        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 = '<View><RowLimit>5</RowLimit></View>';
            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());
        }</script>
    ​
    <%-- LoadSiteData --%>
    <script type="text/javascript">
        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());
        }</script>
    ​
    <%--  UpdateList --%>
    <script type="text/javascript">
        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());
        }</script>
    ​
    <%--  UpdateListItem --%>
    <script type="text/javascript">
        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', 'Praveen Battula 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());
        }
</script>

Date Comparison ASP.NET + JAVA SCRIPT

Download Ajax Control Tool Kit form here
http://ajaxcontroltoolkit.codeplex.com/releases/view/33804

How to Add Ajax Toolkit to SharePoint Web.Config Refer below Link
http://inspiredbytechnology.com/using-ajax-control-toolkit-sharepoint-2010/

<%@ Register Assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"
    Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>


<script type="text/javascript">
        function ValidateDates(sender, args) {
            var fromDate = document.getElementById('<%= txtMyDate.ClientID %>').value;

            var validformat = /^\d{2}\/\d{2}\/\d{4}$/
            if (!validformat.test(fromDate)) {

                sender.errormessage = "Invalid Date Format. Please correct and submit again. ";
                args.IsValid = false;
                return false;
            }
            else {
                var dayfield = fromDate.split("/")[0]
                var monthfield = fromDate.split("/")[1]
                var yearfield = fromDate.split("/")[2]
                var dayobj = new Date(yearfield, monthfield - 1, dayfield)
                if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {

                    sender.errormessage = "Invalid Day, Month, or Year range detected. Please correct and submit again. ";
                    args.IsValid = false;
                    return false;
                }
                else {
                    var dtToday = new Date();
                    if (dayobj > dtToday) {
                        args.IsValid = false;
                        return false;
                    }
                    else {
                        args.IsValid = true;
                        return true;
                    }
                }
            }
        };  
    </script>


 <asp:ValidationSummary ID="ValidationSummary1" HeaderText="Please enter valid values for the following field(s)"
                    DisplayMode="BulletList" EnableClientScript="true" runat="server" ValidationGroup="valGroup1"
                    CssClass="error_msg" />



 <asp:TextBox ID="txtMyDate" runat="server" CssClass="myDesign"></asp:TextBox>


<img id="imgMyImage" src="/_layouts/images/MyProject/calander.png" width="20"
                                                height="20" alt="" class="icon" />
                                            <div style="width: 50px; position: relative;">
                                                <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtMyDate "
                                                    Format="dd/MM/yyyy" PopupButtonID="imgMyImage" CssClass="cal_Theme1" />
                                            </div>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txtMyDate"
                                                ErrorMessage="Date of Purchase" Display="None" ValidationGroup="valGroup1" Text="*">
                                            </asp:RequiredFieldValidator>
                                            <asp:CustomValidator ID="CustomDateValidator" runat="server" ErrorMessage="Please ensure that 'Date of Purchase' is lesser than or equal to 'Current Date'."
                                                ClientValidationFunction="ValidateDates" Display="None" ValidationGroup="valGroup1"> </asp:CustomValidator>



<asp:Button ID="btnSave" runat="server" Text="Add" OnClick="btnSave_Click" CssClass="button"
                                                ValidationGroup="valGroup1" />
-----------------------------------------------------------------------------------------------------------


<html>
<head>
<script  language="javascript">
function cal()
{
document.f1.y1.value= mydiff(document.f1.n1.value,document.f1.n2.value,"days");
}
function mydiff(date1,date2,interval) {
var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
    date1 = new Date(date1);
    date2 = new Date(date2);
    var timediff = date2 - date1;
        return Math.floor(timediff / day);
}        
</script>
</head>
<body>

<form name="f1">
       enter From Date:<input type="text" name="n1">
   <br>enter To Date:<input type="text" name="n2">
   <br>No Of Days: <input type="text" name="y1">
   <input type="button"  value="Get Days"  name="ab" onclick="cal();">
</form>
</body>
</html>




Monday, May 28, 2012

Property or indexer 'Microsoft.SharePoint.SPListItem.Title' cannot be assigned to -- it is read only


Property or indexer 'Microsoft.SharePoint.SPListItem.Title' cannot be assigned to -- it is read only :-



 protected void btn1_Click(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Announcements"];
                    SPListItem item = list.AddItem();
                    item["Title"] = "New Announcement";
                    item.Update();
                }
            }
        }


SharePoint Version


Friday, December 23, 2011

Create BAT File in MOSS 2007 / SharePoint 2007


To ease the deployment process, create a batch file called InstallAll.bat in the folder that contains the FormDataWorkflow.sln Visual Studio solution file. Add the following code to the InstallAll.bat file.
iisreset /stop

"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -uf FormDataAspxPages
"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -if FormDataASPXPages\bin\Debug\FormDataAspxPages.dll

"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -uf FormDataWorkflow
"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -if FormDataWorkflow\bin\Debug\FormDataWorkflow.dll

iisreset /start

copy /Y "FormDataAspxPages\FormDataAssocForm.aspx" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS"
copy /Y "FormDataAspxPages\FormDataInitForm.aspx" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS"

mkdir  %SystemDrive%"\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\FormDataWorkflow"

copy "FormDataWorkflow\Feature.xml" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\FormDataWorkflow"
copy "FormDataWorkflow\workflow.xml" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\FormDataWorkflow" 

pushd "%programfiles%\common files\microsoft shared\web server extensions\12\bin"

stsadm -o deactivatefeature -filename "FormDataWorkflow\feature.xml" -url http://localhost -force
stsadm -o uninstallfeature -filename "FormDataWorkflow\feature.xml" -force

stsadm -o installfeature -filename "FormDataWorkflow\feature.xml" -force
stsadm -o activatefeature -filename "FormDataWorkflow\feature.xml" -url http://localhost -force

popd

PAUSE

Friday, December 9, 2011

Debugging Feature Receivers


Feature receivers can be difficult because they are often executed within a separate process. To see an example of this problem put a breakpoint on the first line of our FeatureActivated method and try debugging using Visual Studio.  The code will be deployed and the feature will be activated, but execution will not stop at the breakpoint.  Visual Studio makes use of a separate process, VSSPHost.exe, to automate the deployment only, and therefore the breakpoint is never hit but the code still execures.
        We can work around this issue in one of two ways: we can either attach a debugger to the appropriate process, or we can ensure that our feature receiver runs in the W3SVC process. To ensure  that a debugger is attached to the correct process, we can take the following steps:
   
            1.   Add the following line of code to the method to be debugged:
    Debugger.Break();

   When error window open then select “Debug the Program”
 

Featured Post

Generating a Microsoft Graph Bearer Token in Power Automate Desktop (App ID + Secret)

Generating a Microsoft Graph Bearer Token in Power Automate Desktop (App ID + Secret) Power Automate Desktop has no native Microsoft Graph c...

Popular posts