Showing posts with label Ankur Madaan. Show all posts
Showing posts with label Ankur Madaan. Show all posts

Saturday, June 23, 2018

Create Angular Application using Angular CLI

Where to start on your Angular Project? if this is the question you have then this blog will be very helpful, In this blog we will explore Angular CLI to create/bootstrap angular project. We will use VSCode Node.js, NPM to setup an Angular project using Angular CLI and later clean up some of the code and add support for Jquery and Twitter Bootstrap in the project, also will showcase how to create a component in few seconds with Angular CLI.

It is suggested to read Angular CLI documentation at the official site:- https://cli.angular.io/.

Start your angular application using Angular CLI


Open your system and follow these point step by step to learn the approach:-






  • Open your favorite Command Line tool on the system, CMDER, VSCode Terminal or Git BASH .
  • I am using CMDER http://cmder.net/, in this example. Make sure your system has Node.JS installed and npm availlable to use globally.
  • As a first thing we will install angular CLI using NPM globally.

    npm install -g @angular/cli
  • We can also specify the version after the above command to target specific version:-
    npm install -g @angular/cli@1.7.3
  • This is how it will appear on CMDER:-
  • Next in your work folder create your project by using Angular CLI command to create new project:-
  • ng new {ProjectName}

  • Here is how the output will appear after you run this ng command on your Command Line interface:-

  • It will create the Folder and code files under your workspace. 
    Note: Folder Name will be the same as of your ProjectName,

    Next, lets open this folder in your fav Code editor.

    I am using VSCode here, first thing to notice is package.json file
                                            





    • This package.json file is the one which tells npm which version of dependencies to install while generating the project. If you see closely you will notice ^ on top of version, it tells/dictates the page that atleast this version or greater than this version, we will stabilize this and keep most recent version here. so that in future if we migrate the code, there should be rights dependencies installed. If you hover on top of each setting it will tell you what is the current version available. You can leave the settings as it is if you want for always upgrading to latest ones.
    • Next, remove node module folder to re install the dependencies files, open cmder and run this command to do it:-

    • rm -rf node_modules
    • After this is done, we will reinstall dependencies by using   npm install command:-


    • Npm_modules will get back and all appropiate versions of the file gets installed.
    • Now lets modify the port to run you application on angular-cli.json file, under scripts --start, write

      ng serve --port 1200
    • /This will run when we type npm start in command line and browse the location on 1200 port instead of default 4200 port. I do this just to control on which port i want to run my application:-

    • type npm start  in CMDER as shown above it will start your application, browse https://localhost:1200, it will open your Angular Application, like this:-


     How to add external packages to the project?

    Now lets see how to add other packages to your Angular Project, we will add twitter bootstrap and as it has jQuery Dependency we will add jquery too.

    Too add Bootstrap, go to CMDER and run this command:-

    npm install Bootstrap









































    • It will install all dependency files of bootstrap to npm_modules folder and as well add a refference in Package.json file.
    • Next add jQuery as bootstrap has dependency on it:-

    npm install jQuery

    And as recent bootstrap has dependency to Popper then install Popper.JS too as shown above.


    • If you would like to install specific version of bootstrap and jquery then go to package.js folder and mention the specific version and then clear node_modules and npm install like we did earlier to get specific version of jquery and bootstrap.
    • Next to use bootstrap and jquery in our current project we have to modify angular-cli.json file.

    As shown in image above, go to Styles section an in the array include the location of bootstrap css file :- "../node_modules/boostrap/dist/css/bootstrap.min.css"

    And to Scripts section in the value array put the Jquery file's path first and then the bootstrap's file's path. which is :-

    jQuery :- "../node_modules/jquery/dist/jquery.min.js"
    bootstrap:- "../node_modules/boostrap/dist/js/bootstrap.min.js"


    These paths are in respect of index.html files as eventually on that file root module and components will get registers.

    and if you do npm start in CMDER, you will see the bootstrap properties in action, just modify html file a little bit like add a container and row div.

    Generate a new component using Angular CLI.

    Its very easy to generate html template, component ts file and testing files using angular CLI, not only that it automatically registers the new component on the module. to do it you have to just type a simple command in your Command line editor:-


    • We will create component for nav-bar at top of the page. For that just use this command to generate the component:-
    ng generate component nav-bar



















    CLI will perform five steps first it will create html template for componenet, next the test file spec.ts, then the component itself and then the css file and finally update the main module to register component it has creeated, you can see these changes in your folder structure:-


    You will see it has generated a new folder with the component name and respective files are automatically added to it.

    CLI generally dictates this as best practice to create each component and its respective files under a single folder, you can nest multiple components under one component, and have them communicate with each other, thats not part of this blog though.

    Lets delete the spec.ts file as its not needed as of now, i am not doing testing of anything, and just copy the code of Nav Bar from bootrstrap sample to the html template. And then add the on top of major app.component template to load the newly created nav component as shown here:-




















    Thats it, you should see nav bar added on your main page Will share more magic we can do with angular cli further in my blogs, please keep following.

    Wednesday, June 6, 2018

    Posting updates to SharePoint Online via PowerShell and Rest API

    In my previous blog office 365 powershell and restApi i demonstrated how to read/get data from SharePoint online site, here in this example we will Post updates.

    Here are the important things to consider when posting updates to office 365:-

    1. We have to pass  X-RequestDigest value for the form digest HTTP header.
    2. If updating Lists/Document Library and items/documents to avoid concurrency conflicts we need to specify additional HTTP header with the name "IF-MATCH", which takes a value of Etag. Etag can be retrieved by retrieving the target entity(list or list item) with a GET method. This is included in the response HTTP headers and in the response content. In situations where we dont care about concurrency its ok to pass "*" as value.
    I will use the PnPOnline msi PowerShell module to connect to Office 365 developer tenant of mine. Kindly read the office 365 powershell and restApi to understand how to use it and load the module.

    Lets talk about the script here.

    • First we will Import the PowerShell module.

    Import-Module "Microsoft.Online.SharePoint.PowerShell"

    • Next create a global webSession variable, we will add headers to this session via different functions as our code progresses.

    #create webRequest session global Object
    $Global:webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
    


    • Lets create a function where we will pass the url of the SharePoint online site as a param and then will connect to it using Connect-PnPOnline function of PnP SharePoint Online Powershell:-


    
    function Init-PnPSecuritySession{
    param($targetSite)
    $targetSiteUri = [System.Uri]$targetSite
    #connect to the Sharepoint online site 
    Connect-PnPOnline $targetSite
    $context = (Get-PnPWeb).Context
    $credentials = $context.Credentials
    $authenticationCookies = $credentials.GetAuthenticationCookie($targetSiteUri, $true);
    
    #set retrieved cookies as header to wenreq
    $Global:webSession.Cookies.SetCookies($targetSiteUri,$authenticationCookies)
    $Global:webSession.Headers.Add("Accept","application/json;odata=verbose");
    
    }
    
    Will retrieve the Context from PnP web and then grab the credentials and Authentication Cookie.
    Next setup the authentication cookie value and include Accept header for content type.


    We are using odata=verbose, instead we can use odata = minimalmetadata or odata = nometadata for reducing metadata returned after the rest call.


    • Next we will write a function in which we will make a rest call to ContextInfo namespace, retrieve the RequestDigest value and pass it to websession object:-
    #function to get RequestDigest Value and set it with Http Header
    function Init-PnPDigestValue{
    param ($targetSite)
    
    $contextInfoUrl = $targetSite + "_api/ContextInfo"
    
    $webRequest = Invoke-WebRequest -Uri $contextInfoUrl
    -Method Post -WebSession $Global:webSession
    
    $jsonContextInfo = $webRequest.Content | ConvertFrom-Json
    $digestValue = $jsonContextInfo.d.GetContextWebInformation.FormDigestValue
    $Global:webSession.Headers.Add("X-RequestDigest",$digestValue)
    }
    


    • Now lets add additional HTTP Headers, as its an Update we will user X-HTTP-Method "MERGE" or You can use "PATCH"  along with Post so that any writable property that is not specified in the content Metadata we are passing, will retain its current value.

    $Global:webSession.Headers.Add("X-HTTP-Method","MERGE")
    $Global:webSession.Headers.Add("IF-MATCH", "*")#optional
    $Global:webSession.Headers.Add("content-type","application/json;odata=verbose")
    

    We are keeping If-Match to *, this is optional and one can ignore it in this case. Its important to mention content-type.

    • Now lets declare the content, we will use stringified JSON object to update Title of the Web here. so it should be like this:-
    $newContent = "{ '__metadata': { 'type': 'SP.Web' }, 'Title': 'PHLY CITY Site' }";
    $Global:webSession.Headers.Add("content-length",$newContent.Length)
    

    Our Object is SPweb and the property we are modifying is Title. so newContent is set accordingly and also an additional Header parameter is added to provide the content-length.

    Now lets provide our url for sharepoint site and call the functions and then finally Invoke the web request:-

    $targetSite = "https://phly.sharepoint.com/sites/phly/"
    Init-PnPSecuritySession -targetSite $targetSite
    Init-PnPDigestValue -targetSite $targetSite
    $restCallUrl = $targetSite + "_api/web"
    
    #Invoking the web request with websession and POST method.
    $webRequest = Invoke-WebRequest -Uri $restCallUrl -Body $newContent  
    -Method Post -WebSession $Global:webSession 
    


    Save the entire script and execute it, it will ask you credentials to login to office 365 site and then will invoke the web request. you should be able to see the updated result on the site:-




    Tuesday, July 14, 2015

    JavaScript Closures (Step 1 for App development)

    JavaScript Closures

    In this blog i like to write and discuss about the Closures in JavaScript, i am using JavaScript in SharePoint sites from 2007 version, In my first working assignment i was told to premeditate a Site template made using SPServices and Jquery to new SharePoint JavaScript client object model Site back in 2009, It was a Template which enables functionality of  Twitter on SharePoint. But that time i just created and written everything in functions which were added under Global namespace automatically.
    And this is normally we do in creating our applications or making some modifications, but with the advancement in client side programming and trend of Single Page applications and many other factors  has introduced design patterns and writing javascript libraries.

    To make such libraries one basic important concept is Closure.

    A closure is concept made out of anonymous functions and a basic fact in javascript that an anonymous function can be returned from other functions, like it  can also be assigned to a variable

    Local variables defined within the containing function are available through the returned anonymous function and this is called Closure.

    Now lets see this in a series of examples:-


    1. Basic Closure example:-
      var Maddy = window.Maddy || {};
      
      Maddy.getStudentName = function Student(id) {
          var students = { '1': 'ankur', '2': 'nelson', '3': 'drew' };
          var getName = function () {
              alert(students[id]);
          };
          return getName;
      
      };
      
      Maddy.getStudentName(3)();
      


      here we have a namespace Maddy and under that we have a function getStudentName which incorporates an anonymous function accessing local variable students  and retrieving the value of name of student contained in students variable.

      We have just returned the function to the original function.
    2. The inner function is the closure in above example, it has three access chains, it can access its own variable and variables scoped to outer function and also can access Global function, but it can not access arguments directly of outer function, see this example:-

      Look at this example which does not use Closure:-

      Maddy.addArguments = function()
      {
          var sum =0;
          for(var i=0;i<arguments.length;i++)
          {
      
              sum += Number(arguments[i]);
          }
      
          return sum;
      }
      alert(Maddy.addArguments(1,2,3,4,5));
      
      

      It will work perfectly and will give you output of 15.

      Now if you use Closure and try to access arguments it wont work.

      Maddy.addArgumentsWithclosure = function () {
          var sum = 0;
      
          var doTheSum = function () {
              for (var i = 0; i < arguments.length; i++) {
      
                  sum += Number(arguments[i]);
              }
      
              return sum;
          };
          return doTheSum;
      };
      
      alert(Maddy.addArguments(1,2,3,4,5)());
      

      it will return '0' in alert and wont work.

      So Closure can access local,outer and global variables but cant work with outer function arguments object.
    3. Closures have access to the outer function’s variable even after the outer function returns, also it stores references to the outer function’s variables;

      example demonstration:-

      Maddy.getValueID = function () {
          var valueId = 101;
      
      
          return {
      
              get_valueId: function () {
      
                  return valueId;
              },
      
              set_valueId: function (newValue) {
                  valueId = newValue;
              }
      
      
      
          };
      
      };
      
      var dummyVar = Maddy.getValueID();
      alert(dummyVar.get_valueId()); //output will be 101
      dummyVar.set_valueId(1000); 
      alert(dummyVar.get_valueId()); //output will be 1000
      
      
    As shown above set_valueId closure still keeps reference to outer function variables even outer functions is allready executed.

    Tuesday, July 2, 2013

    Develop Microsoft SharePoint 2013 APPS - Part 1

    Yes this is the time I think I should talk about my learning and work with SharePoint 2013 Apps, The main reason of APPS in SharePoint 2013 is to give Developers the power of creating customizations without full trust access to the target farm, and the sweet reason is you can create apps and publish them in marketplace or corporate app catalog.
    This blog series about sharepoint apps will be of different parts and i will try to discuss everything i know here with demonstration. So lets begin:-
    APPS the Word(APPS for SharePoint):- You all are familliar with the word app, it was Nokia, Apple then Android who made this word popular in today Techno World, and even a first grade student can explain to you what does an "app" means, Microsoft evolve this in sharepoint from Farm Solutions --> then came SandBox Solutions --> then SharePoint Apps, the reason of this evaluation was mainly to avoid hick ups that admin people feels for Solution Deployment and to avoid effecting SharePoint Farm with custom Solutions or Customizations.
    Many of Clients i worked with preffered SharePoint Designer Based customization even though i gave them explanation on how this disturbes the caching and Loading of SharePoint Pages as these have to go through different Parsing mechanism, the only answer they have is Designer based things are easy to modify, change and does not effect our SharePoint Environment.
    Yes partially they are right but actually it costs alot to performance and Migration , Upgradation Scenerios.
    So i think this evolution of SharePoint Apps are handy but this does not means that Sandbox Solutions are completely Obsolute, Microsoft Says that one should now preffer APPS as much as one can but at situations you have to go with Sandbox Solutions, as we can not modify things on SharePoint Main Sites with Apps
    Silly Classification :-
    One can classify apps on the basis of Configuration  and hosting model.
    Conifguration:- 1) Full Page 2)App Parts 3)UI Command Extension.
    Personally if you ask then my favourite is APP Parts but in this part of series we will work with Full Page Apps.
    Ahhh i am sorry i should explain you guys first what are these:-
    Full-page Based on one or more web pages, these apps include a dedicated UI. You should provide a back button for returning to the parent site, where the app is launched from—but your app will have a UI of its own.Simple as it sounds.. create web pages put javascript on the background yeah and here we go.
    App Parts
    Also called Client Parts, these render some app content in an IFrame inside pages of the parent site. Usually, App Parts are used to provide users with a small piece of information or functions that can directly interact with the SharePoint user interface.
    UI command extension
    Used to extend the UI of the parent site, these apps may include a ribbon button or an ECB (Edit Control Block) command to lead the user to a page or function provided by an external app.

    Hosting Model Classification
    SharePoint-hosted

    This model relies on a subweb of the parent site (also called an app web) and enables you to use all the common SharePoint artifacts for implementing the UI and the behavior of the SharePoint app. You can take advantage of all the features of SharePoint, such as lists, Web Parts, pages, workflows, and so on.

    Autohosted
    Apps following this model are hosted on Microsoft Windows Azure, which can access a Microsoft SQL Azure database for managing data, too. The apps are automatically deployed on Windows Azure on your behalf and can communicate with SharePoint through events and the Client Object Model. Secure communication with SharePoint is enforced using OAuth.

    Provider-hosted
    From a functional perspective, apps that follow this model are almost the same as autohosted apps. The only difference is that a provider-hosted app has to be deployed on your own hosting environment and does not necessarily use the Windows Azure environment.

    Lets Start:-
    Ok so lets stop any more discussion and jump on the first app development, I have my development environment ready services required for APPS and Forward lookup Zones for Apps and Service Applications are configured Properly. There are several blogs availlable on how to do this http://msdn.microsoft.com/en-us/library/fp179923.aspx

    Ok SO lets begin to develop our very basic and Simple App.

    • This going to be a on-premise/sharepoint hosted app.
    • Open Visual Studio 2012, create a new project -> Select SharePoint Apps ->;Apps for SharePoint 2013, .Net Framework 4.5 and give a proper name to project (I have given it as KickOff).
    

    • Enter Url of target SharePoint Site & then Change hosting to “SharePoint Hosted” from Autohosted .
    • Click Finish and VS 2012 will create a Project for us.
    • And this will be what you will get :-


    Now let me brief about what we have :-
    1. Features Folder:-
     Contains all the features for provisioning contents and capabilities to the target web site, Upon creation this contains only one feature scoped to web-level.

    One Major thing to note is you cant modify the scope of this feature and it packages all the contents, the main perpose of this feature is to deploy all the APP contents to the “TARGET APP WEBSITE”.


    I would like to add a note here that you should know:-

    NOTE:-One has to remember that an app website is provisioned and unprovisioned together with its app. Thus, we create an app that stores content inside its app web, if end user remove or uninstall the app, however the app will be gone also its related data will go away.

    2. Package Folder:- Contains the package for deploying the app.
    3. Content Folder:- Contains CSS style and a Module to deploy it to the target app.
    4. Images Folder:- A Module and Images with default APP Icon image of 96*96 pixel, you can modify this with one of yours.
    5. Pages Folder:- Module Feature and the pages of target app contains in this folder, default.aspx is the page contained by default.
    6. Scripts Folder:- Represents a Module Feature that is for Javascript Files, APP.js file is the file where we put oue custom scripts(it is our entry point.
    7. AppManifest.xml file:- Contains configuration and deployment information related to app.
    8. Packages.config file:- Information about the packages referenced by Visual studio project.

    Allright now lets just see what happens when out of box feature contained web is deployed to the Site, press F5 and see what happens:-
    First Uploading of app starts then installation begins:-

    Depending on the kind of environment and configuration installation progresses and takes time

    And thus the app will get open:-

    You can see there that it does have its default.aspx page loaded and link to go to the site from which it was reffered, in my case "test site" 
    If you go back to the Man Site "Test Site in my case" then This app is located under site contents:-
    Now Lets Start the Fun :- Make Changes
    Open Default.aspx page:-
    You will see this :-

    Apart from SP.js files it also contains an App.js file reference and this is our target start point of scripting and we will use this to provide our logic.


    Now let me just show you a very simple thing, we will create a div and load all site users into it:- so declare a div element in your page with id:- “AppDetails”


    And Now lets open" App.js" file and modify the code in it

    add two global variables :-


    var htmltoappend = ""; //Will store the html string to append in div
    var siteUsers; // will store the siteUser object retrieved from CSOM of SharePoint 2013.

    This is how the modified APP.js will be:-



    We are just initializing siteusers and showing the title of each users and creating a table and loading  this table into the div, just run the app now and see the changes:-


    Thanks and coming up next is App Parts and many more exiting Notes about SharePoint Apps....

    Friday, October 19, 2012

    Custom SharePoint 2010 Ribbon Action for a Specific List Using Visual Studio 2010

    Greeting to all my blog readers, we all know how good the sharepoint 2010 Ribbon is, and most wonderfull part is that it is Customizable by using both Visual Studio 2010 and SharePoint Designer 2010.

    Recently on Microsoft Technet Forums a person asked this question: "I need a Ribbon Button for a Specific Lists using Visual Studio 2010" as he was thinking to attach Javascript code or CSOM code on that button(not possible with designer way), there was no way he was able to achieve the same using in Elements.xml file.

    So i tried my luck with Server Side Object Model to achieve this and later even got the code Client Script object model and Server Side Object Model code to do this. In this blog i am only sharing the way i discovered this in server side object model.
    I am showing code written as a Console Application to create a Ribbon Button on Specific List using Visual Studio.

    It uses UserCustomActions Collection Property of SPList Object and to add a new UserCustomAction.
    The Major Property is:
    UserCustomAction.CommandUIExtension, this recieves token from the XML, the same way we enter in the Elements.xml during the traditional way. So here is how my code looks like:-  

     
     
     
     
     
    Thats it and you will get a Explicit Ribbon button for a Particular List Only...

    Thursday, July 19, 2012

    SharePoint 2013 is Running at my Home System Now


    SP 2013 is at my home now:

    It took me three days to make it happen, but yes I have got SP2013 Foundation Preview running on my system.
    It is not that tricky that I thought it going to be, actually if we struggled during 2010 and know very well the right ways of installing SharePoint on  a 64 bit environment then it won’t be a big deal this time as we are habitual of certain issues.

    So here Is how my first 2013 site  SharePoint foundation site looks like:



    My Current System Configuration:

    1)Windows Server 2008 R2

    2)Sql Server 2008 R2.

    3)VS 2012 RC

    4)SharePoint Foundation 2013.

    How I made it happen:

    1)I downloaded SP Foundation from here:
    http://www.microsoft.com/en-us/download/details.aspx?id=30345


    2)Next I Downloaded SP 1 for Windows Server 2008 R2, which is require for SP2013 install from here:

    Next I ran the Pre-requisite for SP2013 , if you find any issues with pre-requisite then suggest to follow this blog, which describes awesome powershell scripts to get them all, it helped me too:

    Monday, March 12, 2012

    Creating Custom Workflow Activity using Visual Studio 2010 for SharePoint 2010 (SharePoint A to Z Series)

    Hi, since long i was thinking to blog about this topic and finally got a chance to do so. Normally we prefer to create Designer Based Workflows, as they are easy to create, manage and quite flexible.

    But still at situations Designer Workflows not allow us to do certain Tasks, for an instance , performing cross site Tasks, like Creating a Document Library in a different site or Creating a new site on certain conditions.
    Instead of Creating Complete Workflow we can still use Custom Activities Development in Visual Studio 2010 which is much easier to built and easy to manage for client's Power Users.

    So what  i mean is simple “Code an Activity” instead of Coding a Complete Workflow.
    Now lets come to the point and follow some steps to create a simple Workflow Activity. Remember this will be Number 1, and quite easy one, later i will post some bigger and much cruciall Activities.
    What I’m about to show you is what I did and tested in the following environment: 
    • Microsoft Windows server 2008 R2 Enterprise Edition
    • SharePoint Server 2010 Enterprise Edition
    • MS SQL 2008 Enterprise Edition
    • Visual Studio 2010 Ultimate
    • Code was done in C# only
    (Note: we don’t need the exact environment, but as such a similar one to get started)

    Step: 1) Create a Project to support Activity Deployment to Farm

    Create an Empty Project in VS2010 and Name it “CustomActivityDemo”, make Sure it should be a Farm Scoped Project.(No SandBoxed), And select the site on which you like to test it /*Empty SharePoint Project*/

    Next Click Finish.. It will be just like a scenerio where this project will act as a Rocket Launcher for our Rocket(Activity).. :)
    We will setup code and properties later in this, now lets move ahead and create our Activity Project in the Same Solution.
    Step :2) Create WorkFlow Activity Project
    At the Solution level Right Click and “Add a Project” in VS2010.
    Next  Select the Visual C# >Workflow >Workflow Activity Library and set the project name as ‘CreateSiteActivity’.
    Now whole solution will appear like this:
    Note that after adding Workflow Activity Library Project  a Design view of Activity appears which shows Activity1.cs
    lets now follow these subpoints:
    • Right click the Activity1.cs and rename it to “CreateSiteActivity.cs”,


    • Again Right Click “CreateSiteActivity” and click “View Code”.



    • Now add a reference to
     Microsoft.SharePoint.dll and  Microsoft.SharePoint.WorkflowActions.dll   located in ISAPI Library:

    • Import the following NameSpaces in the code file:
    
    

    This will how the code will appear now:
    Before going further lets discuss some of the important terminologies:

     
    Step :3) Some Introduction to WorkFlow Terminologies:
    This will be boring a bit but very quickly please do read these lines as it will clear our process in a bigger way:

    Dependency Property
    Dependency properties provide a centralized repository of a workflow's state.
    The DependencyObject is a hash table that stores the current values of any DependencyProperty that is applied to it.

    Dependency Object Class:

    An instance type of a dependency property can be bound to instance data, in which case the actual value is not determined until runtime.
    You set this type of dependency property's value to be an ActivityBind to bind to the actual value that is accessed at runtime.

    ActivityBind binds an activity property to any of the following:
    • Another activity property.
    • A field.
    • A property.
    • A method.

    In Simpler Word:

    Dependency Property provide a mechanism that allows SharePoint Designer to provide values for your custom action before you add your custom functionality.

    To allow SharePoint Designer to pass values to your custom action when the workflow runs, you must create public properties inside your custom action. In this example, you will create a custom action that will create a new site within SharePoint whenever executed inside a SharePoint Designer workflow.

    Before Writing any Dependency Property and its Binding Property, we have to think about our Inputs, so in this example here are the inputs:

    SiteUrl: Where the site will be located.

    SiteTitle: Title for the new site.

    SiteDescription: Description for the new site.


    SiteTemplate: Template to use to create the new site.

    InheritPermissions: True, if the new site will inherit permissions from its parent site.


    For each field, you create a property in your custom action to allow the users to specify these values when designing their workflow in SharePoint Designer.

    When creating properties for a custom action, you create the property itself and a matching DependencyProperty. The DependencyProperty class allows SharePoint Designer to bind the property to the UI in the workflow wizard, where the user specifies the values of these properties in the workflow being created.



    Note: Please follow the Syntax we will use while Creating a Property and a Matching Dependency Property, there is Matching Relation require in both of these Names.

    Add the following code to create a property and DependencyProperty for SiteUrl:

    Parameters it takes are : 1)String Name of the associated Property, Type of Property, Type of Owner(Activity Class Name)

    
    

    Now for a while just think on what we have written:

    Dependency Property Name : SiteUrlProperty and Matching Property Name is SiteUrl
    It is required to follow above Syntax i.e always write Dependency Property with Suffix “Property” if you miss this then you will get Compilation Error.
    Step: 4) Getting Current Workflow Context

     


    Step:5) Complete Rest of Dependency Properties Simmilarly

    simmilarly complete the Dependency Properties for rest of inputs we discussed earlier and code should now look like this:

    Step:6) Execution of Main Action

    Whenever in Workflow the pointer reaches to the Activity then There is an entry method which executes and this method/function is Execute :


    We need to override this function to write the functionality of our activity:

    This function returns an ActivityExecutionStatus which is an enum containing values. And takes executionsyntax as parameter.


    For getting refference to current site , we will use _Context property that we defined above


    Step:7) Code to insert in Execute Method:





    Note: If an error occured then we have used ISharePointService to logtohistory list whatsoever error occurs.

    Step : 8) Create ACTIONS file

    NOTE:Before reading the next lines first Sign the Assembly and run "sn.exe -T 'Path to Dll'" command to get the PublicKeyToken Value of CreateSiteActivity.dll

    Next Step is to Create an Action File, this file is require to tell Designer how the Activity will appear in UI to the USER, this will make the custom activity to appear in the Wizard.



    An ACTIONS file is an XML file that is used by SharePoint Designer's workflow wizard to provide a user-friendly experience for configuring actions. Every action must be configured in an ACTIONS file before it can be used in SharePoint Designer. By default, there is only one ACTIONS file, located at


    {14 Hive}\TEMPLATE\1033\Workflow\WSS.ACTIONS, and it contains an entry for each of the built-in actions in Windows SharePoint Services.

     




    for a complete refference of this file please visit this msdn article:
    http://msdn.microsoft.com/en-us/library/bb897811.aspx

    Step:9) Deployment Process

    Deployment Process Consists of Four Sub Steps:


    1)Sign The Assembly and Get The Public Token and place it in the ACTIONS file:

    Right Click “CreateSiteActivity” Project and then go to Properties and then in “Signing”, create a new key name it “CreateSiteActivity”, then BUILD the Project and later Sign the assembly using:

    Sn.exe –T “path to CreateSiteActivity.dll”

    Note the PublicKeyToken and modify the Actions file accordingly.

    2)Place the ACTIONS file to the Worklfow Mapped Folder of SharePoint 14 Hive:


    In the CustomActivityDemo project Add a SharePoint Mapped Folder to Template /1033/Workflow

    i.e{SharePointRoot}/Template/1033/Workflow and save the above ACTIONS file, with ACTIONS as extension.

    3)Deploying CreateSiteActivity DLL to GAC and Create Safe Control in Web Config of the Web Application.


    1)Expand the Package Item in the CustomActivityDemo Project,







     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
    Then double click it, which will open the Package properties then click Advanced.

     click Add. And select Existing Assembly:
    Add Necessary Information to add safe control, when complete it will appear as this:

    4)Add Authorize Type in web config

    To do this, we will include a feature in sharePoint Project: "CustomActivityDemo" (The Rocket Launcher) Project, Name it something Suitable and Scope it to WebApplication:





    Then right click the Feature and Add a Reciever:
    Add using Microsoft.SharePoint.Administration Namespace to its code file
    Uncomment Feature Activated Block.
    As scope of the Feature is SPWebApplication , from properties take the instance of feature parent as spwebapplication:

    If you see the properties of SPWebAPPlication Instance then you can see a collection WebConfigModifcations:

    Now we have to add a new webconfigmodifcation to this collection , to do so create an Instance of SPWebConfigModification class:


    SPWebConfigModification modification = new SPWebConfigModification();


    Now we will initiate these properties of Modification:

     
     
     
     
    Entire Code will appear as this:


    Next Build, Package and Deploy your solution.

    Step: 10) Test the new Action
    Next open the site which we used for testing this project in SharePoint Designer and Create a New List  Workflow  on any of List (take Task).

    And in List Actions you can see our newly created activity:

    It will Work as it did at my end. Please test yourself and use it in your daily workflow cycle.

    Hope it will help and Workflow Activities creation will be now a simple process for you all.