Thursday, June 14, 2012

Script Object Model and Dialog


 Script Object Model and Dialog
 Expected Out Put.
make sure 'you have to create 'Projects' list before execute this code.



//VisualWebPart1.webpart
<?xml version="1.0" encoding="utf-8"?>
<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="ScriptOMandDialog.VisualWebPart1.VisualWebPart1, $SharePoint.Project.AssemblyFullName$" />
      <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="Title" type="string">Script OM and Dialog</property>
        <property name="Description" type="string">Script OM and Dialog description</property>
      </properties>
    </data>
  </webPart>
</webParts>
-----------------------------------------------------------
//VisualWebPart1UserControl
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1UserControl.ascx.cs"
    Inherits="ScriptOMandDialog.VisualWebPart1.VisualWebPart1UserControl" %>
<SharePoint:ScriptLink ID="ScriptLink1" runat="server" Name="sp.js" Localizable="false"
    LoadAfterUI="true" />
<script language="ecmascript" type="text/ecmascript">
    var ProjectListName = "Projects";
    var ProjectNameField = "Title";
    var projectsList;
    var context;
    var context;
    var web;
    var modalDialog;
    var projectListItem;
    var copyOfAddProjectForm;
    _spBodyOnLoadFunctionNames.push("Initialize()");
    function Initialize() {
        alert("Initialize");
        context = SP.ClientContext.get_current();
        web = context.get_web();
        projectsList = web.get_lists().getByTitle(ProjectListName);
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View><Query/></View>');

        projects = projectsList.getItems(camlQuery);
        context.load(projects, 'Include(Title)');
        context.executeQueryAsync(onListsLoaded, OnError);
    }
    function onListsLoaded() {
        alert("onListsLoaded");
        var projectTable = document.getElementById('tblProjectList');
        while (projectTable.rows.length > 0)
            projectTable.deleteRow(projectTable.rows.length - 1);
        var content;
        var cell;
        var tbo = document.createElement('tbody');
        var listItemEnumerator = projects.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var newTR = document.createElement('tr');
            var projectLI = listItemEnumerator.get_current();
            var projectName = projectLI.get_item(ProjectNameField);
            cell = document.createElement('td');
            content = document.createTextNode(projectName);
            cell.appendChild(content);
            newTR.appendChild(cell);
            cell = document.createElement('td');
            content = document.createTextNode(projectDesc);
            cell.appendChild(content);
            newTR.appendChild(cell);
            tbo.appendChild(newTR);
        }
        projectTable.appendChild(tbo);
    }
    function onProjectAdded() {
        alert("Item Successfully Added");
        HideAddProject();
    }
    function ShowAddProject() {
        alert("ShowAddProject");
        var divAddProject = document.getElementById('divAddProject');
        copyOfAddProjectForm = divAddProject.cloneNode(true);
        divAddProject.style.display = "block";
        var options = { html: divAddProject, width: 200, height: 350, dialogReturnValueCallback: ReAddClonedForm };
        modalDialog = SP.UI.ModalDialog.showModalDialog(options);
    }
    function HideAddProject() {
        alert("HideAddProject");
        modalDialog.close();
        Initialize();
    }
    function ReAddClonedForm() {
        document.body.appendChild(copyOfAddProjectForm);
    }
    function AddProject() {
        alert("AddProject");
        var lici1 = new SP.ListItemCreationInformation();
        projectListItem = projectsList.addItem(lici1);
        projectListItem.set_item(ProjectNameField, getTBValue('<%=txtProjectName.ClientID%>'));
        projectListItem.update();
        context.load(projectListItem);
        context.executeQueryAsync(onProjectAdded, OnError);
    }
    function OnError(sender, args) {
        alert("OnError");
        var spnError = document.getElementById("spnError");
        spnError.innerHTML = args.get_message();
    }
    function getTBValue(elID) {
        var el = document.getElementById(elID);
        return el.value;
    }
</script>
<div style="font-weight: bold">
    Project List
</div>
<br />
<table id="tblProjectList" style="border: solid 1px silver">
</table>
<br />
<a href="javascript:ShowAddProject()">Add a project</a>
<br />
<div id="divAddProject" style="display: none; padding: 5px">
    <b>Project Information</b><br />
    <br />
    Title
    <br />
    <asp:TextBox runat="server" ID="txtProjectName"></asp:TextBox><br />
    Description<br />
    <asp:TextBox runat="server" ID="txtDescription"></asp:TextBox><br />
    <span id="spnError" style="color: Red" />
    <br />
    <asp:Button runat="server" ID="btnAddProject" Text="Add New Project" OnClientClick="AddProject()" />
</div>
--------------------------------------------------------------------------------

Programming with Content Types




// Programming with Content Types.
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Linq;

namespace SPHOL302_Ex2.Features.Feature1
{
    [Guid("8c019752-8354-430b-ba1c-bed7daac7c48")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (SPWeb spWeb = properties.Feature.Parent as SPWeb)
            {
                SPContentType newAnnouncement = spWeb.ContentTypes.Cast<SPContentType>().FirstOrDefault(c => c.Name == "New Announcements");
                if (newAnnouncement != null)
                {
                    newAnnouncement.Delete();
                }
                SPField newField = spWeb.Fields.Cast<SPField>().FirstOrDefault(f => f.StaticName == "Team Project");
                if (newField != null)
                {
                    newField.Delete();
                }
                SPContentType myContentType = new SPContentType(spWeb.ContentTypes["Announcement"], spWeb.ContentTypes, "New Announcements");
                myContentType.Group = "Custom Content Types";
                spWeb.Fields.Add("Team Project", SPFieldType.Text, true);
                SPFieldLink projFeldLink = new SPFieldLink(spWeb.Fields["Team Project"]);
                myContentType.FieldLinks.Add(projFeldLink);
                SPFieldLink companyFieldLink = new SPFieldLink(spWeb.Fields["Company"]);
                myContentType.FieldLinks.Add(companyFieldLink);
                spWeb.ContentTypes.Add(myContentType);
                myContentType.Update();
            }
        }
        // Uncomment the method below to handle the event raised before a feature is deactivated.
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            using (SPWeb spWeb = properties.Feature.Parent as SPWeb)
            {
                SPContentType myContentType = spWeb.ContentTypes["New Announcements"];
                spWeb.ContentTypes.Delete(myContentType.Id);
                spWeb.Fields["Team Project"].Delete();
            }
        }
        // Uncomment the method below to handle the event raised after a feature has been installed.
        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}
        // Uncomment the method below to handle the event raised before a feature is uninstalled.
        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}
        // Uncomment the method below to handle the event raised when a feature is upgrading.
        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}

Wednesday, June 6, 2012

SharePoint Unified Logging Service from JavaScript


<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test6.aspx.cs" Inherits="test.Layouts.test.test6"
    DynamicMasterPageFile="~masterurl/default.master" %>
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <%--http://msdn.microsoft.com/en-us/library/hh803115--%>
    <script src="/_layouts/LoggingSample/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript">
        // Creates a custom ulslog object
        // with the required properties.
        function ulsObject() {
            this.message = null;
            this.file = null;
            this.line = null;
            this.client = null;
            this.stack = null;
            this.team = null;
            this.originalFile = null;
        }
        // Detecting the browser to create the client information
        // in the required format.
        function getClientInfo() {
            var browserName = '';
            if (jQuery.browser.msie)
                browserName = "Internet Explorer";
            else if (jQuery.browser.mozilla)
                browserName = "Firefox";
            else if (jQuery.browser.safari)
                browserName = "Safari";
            else if (jQuery.browser.opera)
                browserName = "Opera";
            else
                browserName = "Unknown";
            var browserVersion = jQuery.browser.version;
            var browserLanguage = navigator.language;
            if (browserLanguage == undefined) {
                browserLanguage = navigator.userLanguage;
            }
            var client = "<client><browser name='{0}' version='{1}'></browser><language>{2}</language></client>";
            client = String.format(client, browserName, browserVersion, browserLanguage);
            return client;
        }
        // Utility function to assist string formatting.
        String.format = function () {
            var s = arguments[0];
            for (var i = 0; i < arguments.length - 1; i++) {
                var reg = new RegExp("\\{" + i + "\\}", "gm");
                s = s.replace(reg, arguments[i + 1]);
            }
            return s;
        }
        // Creates the callstack in the required format
        // using the caller function definition.
        function getCallStack(functionDef, depth) {
            if (functionDef != null) {
                var signature = '';
                functionDef = functionDef.toString();
                signature = functionDef.substring(0, functionDef.indexOf("{"));
                if (signature.indexOf("function") == 0) {
                    signature = signature.substring(8);
                }
                if (depth == 0) {
                    var stack = "<stack><function depth='0' signature='{0}'>{1}</function></stack>";
                    stack = String.format(stack, signature, functionDef);
                }
                else {
                    var stack = "<stack><function depth='1' signature='{0}'></function></stack>";
                    stack = String.format(stack, signature);
                }
                return stack;
            }
            return "";
        }
        // Creates the SOAP packet required by SendClientScriptErrorReport
        // web method.
        function generateErrorPacket(ulsObj) {
            var soapPacket = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
                                       "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
                                       "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                          "<soap:Body>" +
                            "<SendClientScriptErrorReport " +
                              "xmlns=\"http://schemas.microsoft.com/sharepoint/diagnostics/\">" +
                              "<message>{0}</message>" +
                              "<file>{1}</file>" +
                              "<line>{2}</line>" +
                              "<stack>{3}</stack>" +
                              "<client>{4}</client>" +
                              "<team>{5}</team>" +
                              "<originalFile>{6}</originalFile>" +
                            "</SendClientScriptErrorReport>" +
                          "</soap:Body>" +
                        "</soap:Envelope>";

            soapPacket = String.format(soapPacket, encodeXmlString(ulsObj.message), encodeXmlString(ulsObj.file),
                 ulsObj.line, encodeXmlString(ulsObj.stack), encodeXmlString(ulsObj.client),
                 encodeXmlString(ulsObj.team), encodeXmlString(ulsObj.originalFile));
            return soapPacket;
        }
        // Utility function to encode special characters in XML.
        function encodeXmlString(txt) {
            txt = String(txt);
            txt = jQuery.trim(txt);
            txt = txt.replace(/&/g, "&amp;");
            txt = txt.replace(/</g, "&lt;");
            txt = txt.replace(/>/g, "&gt;");
            txt = txt.replace(/'/g, "&apos;");
            txt = txt.replace(/"/g, "&quot;");
            return txt;
        }
        // Function to form the Diagnostics service URL.
        function getWebSvcUrl() {
            var serverurl = location.href;
            if (serverurl.indexOf("?") != -1) {
                serverurl = serverurl.replace(location.search, '');
            }
            var index = serverurl.lastIndexOf("/");
            serverurl = serverurl.substring(0, index - 1);
            serverurl = serverurl.concat('/_vti_bin/diagnostics.asmx');
            return serverurl;
        }
        // Method to post the SOAP packet to the Diagnostic web service.
        function postMessageToULSSvc(soapPacket) {
            $(document).ready(function () {
                $.ajax({
                    url: getWebSvcUrl(),
                    type: "POST",
                    dataType: "xml",
                    data: soapPacket, //soap packet.
                    contentType: "text/xml; charset=\"utf-8\"",
                    success: handleResponse, // Invoke when the web service call is successful.
                    error: handleError// Invoke when the web service call fails.
                });
            });
        }
        // Invoked when the web service call succeeds.
        function handleResponse(data, textStatus, jqXHR) {
            // Custom code...
            alert('Successfully logged trace to ULS');
        }
        // Invoked when the web service call fails.
        function handleError(jqXHR, textStatus, errorThrown) {
            //Custom code...
            alert('Error occurred in executing the web request');
        }
        // Registering the ULS logging function on a global level.
        window.onerror = logErrorToULS;
        // Set default value for teamName.
        var teamName = "Custom SharePoint Application";
        // Further add the logErrorToULS method at the end of the script.
        // Function to log messages to Diagnostic web service.
        // Invoked by the window.onerror message.
        function logErrorToULS(msg, url, linenumber) {
            var ulsObj = new ulsObject();
            ulsObj.message = "Error occurred: " + msg;
            ulsObj.file = url.substring(url.lastIndexOf("/") + 1); // Get the current file name.
            ulsObj.line = linenumber;
            ulsObj.stack = getCallStack(logErrorToULS.caller); // Create error call stack.
            ulsObj.client = getClientInfo(); // Create client information.
            ulsObj.team = teamName; // Declared in the consumer script.
            ulsObj.originalFile = ulsObj.file;
            var soapPacket = generateErrorPacket(ulsObj); // Create the soap packet.
            postMessageToULSSvc(soapPacket); // Post to the web service.
            return true;
        }
        // Function to log message to Diagnostic web service.
        // Specifically invoked by a consumer method.
        function logMessageToULS(message, fileName) {
            if (message != null) {
                var ulsObj = new ulsObject();
                ulsObj.message = message;
                ulsObj.file = fileName;
                ulsObj.line = 0; // We don't know the line, so we set it to zero.
                ulsObj.stack = getCallStack(logMessageToULS.caller);
                ulsObj.client = getClientInfo();
                ulsObj.team = teamName;
                ulsObj.originalFile = ulsObj.file;
                var soapPacket = generateErrorPacket(ulsObj);
                postMessageToULSSvc(soapPacket);
            }
        }
    </script>
    <script type="text/javascript" language="javascript">
        var teamName = "Simple ULS Logging";
        function doWork() {
            unknownFunction();
            alert("unknownFunction");
        }
        function logMessage() {
            logMessageToULS('This is a trace message from CEWP', 'loggingsample.aspx');
            alert("logMessage");
        }
    </script>
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:Button ID="btn1" runat="server" Text="Log Exception" OnClientClick="return doWork();" />
    <asp:Button ID="btn2" runat="server" Text="Log Trance" OnClientClick="return logMessage();" />
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    Application Page
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea"
    runat="server">
    My Application Page
</asp:Content>

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

Featured Post

Sent Email in C#

Sent Email in C# : //Option 1: using S ystem; using System.Net.Mail; using System.Security; using System.Text; using System.Threading.T...

Popular posts