Ads

Showing posts with label Visual Studio. Show all posts
Showing posts with label Visual Studio. Show all posts

Tuesday, 25 November 2014

Some shortcut keys in visual studio


Manage Visual Studio
Shortcut Key
Description
Ctrl + K, D
Format document to code formatting settings
Ctrl + K + F
Format selection to code formatting settings
Ctrl + K, C
Comment Selected lines of code
Ctrl + K, U
Uncomment selected lines of code
Ctrl + Alt + P
Attach process
Shift + Alt + Enter
Toggle full screen mode in VS
Ctrl + M, M
Collapse the selected method only
Ctrl + M + O or Ctrl + M + L
Collapse all functions
Ctrl + m, ctrl + T
Collapse Html tag
Ctrl + M + X
Uncollapse all
Shift + F6
Build the Project
Shift + Shipt+B or F6
Build the solution
Ctrl + Break
Cancel build process
F9
Toggle breakpoint
Ctrl + Shift + F9
Delete all breakpoints
Shift+F5
Stop Debugging
Ctrl + F4
Close current tab
Ctrl + Shift + U
Change text to upper case
Ctrl +  U
Change text to lower case
Ctrl+F6/Ctrl+Shift+F6
Go to next / go to previous window
Ctrl + Shift + A
Add item to project
F7
Toggle between Design and Code behind pages
Shift + F7
Toggle between Design and HTML Source
Ctrl+K+\
Remove white space and tabs in selection or around current cursor position

Monday, 30 June 2014

Creating a Classic Webpart - VS 2010

Overview
Classic webparts can be created by deriving from the WebPart class. You must write the code from scratch, in the CreateChildControls method, to create the layout design of the Web Part, which can be time consuming. One of the challenges that you face when designing a Web Part that has a complex user interface (UI) is the lack of drag-and-drop support.

Creating a Classic Webpart
Following are the steps for creating a Classic Webpart.

1) Open Visual Studio and select "New Project->SharePoint->2010". The following window will open displaying all SharePoint project templates. Select "Empty SharePoint Project", give a suitable name and click "Finish".

2) The following window pops-up. Enter the suitable Site collection name for debugging purpose. You also have the option to select Farm Solution or Sandboxed Solution.  

3) Right click on Solution and select Add->New Item. 
4) Another window with SharePoint templates will open as shown in the below figure. Select "Web Part".

 5) When a webpart is added 2 main components are added. First one is the webpart "MyClassicWP" which contains all the files supporting the webpart. Second one is "Features" contains the features for deploying the webpart to the site.
(Note: We will take a closer look into features in the upcoming posts.)
6) Now we will some custom code to display a welcome text along with date and time. Add the following code in the CreateChildControls() method.
SPWeb currentWeb = SPControl.GetContextWeb(HttpContext.Current);
String currentUserName = currentWeb.CurrentUser.LoginName;
this.Controls.Add(new LiteralControl(String.Format(
"<h1>Welcome {0}!</h1>", currentUserName)));
this.Controls.Add(new LiteralControl(String.Format(
"<div>Current DateTime: {0}</div>", DateTime.Now)));

7) Select "Build-> Deploy MyVisualWebPart" to deploy the webpart to the site collection that we entered in the "SharePoint Customization Wizard" in the 2nd step.
(Note: For deploying the wepart solution to another site collection or subsite we must use the STSADM command line tool or SharePoint Management Shell. We will discuss deployment in detail in the upcoming sessions.)

8) Now open the Webpart page in "Edit mode" and click "Add a Web Part". The webpart "MyClassicWP" is now available in the webpart gallery under "Custom" group. Select the webpart and click "Add".

9) Our webpart has been created and displays the Welcome message along with date and time.

This is just small example of creating a Classic Webpart. In the next post we will create a sample visual webpart.

Monday, 8 July 2013

Way of Safe Control Entries in Web Config File from code

There may come a situation where we want to add a custom new safe control entry in web.config file. 

Create New Empty SharePoint Project.

Add new "Empty Element" in project.

Select the newly created element and press F4 to open properties window.

Click ellipse button against the "Safe Control Entries" property as shown in below image.


The safe control entry dialog opens as shown below.

Click "Add" This will add a new safe control entry. Set properties 
Name: name of safe control entry
Assembly: A strong assembly name, such as: MyFirstProject.MyFirstAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=11e9bce111e9418c.
NameSpace: The fully-qualified namespace for the class/control
Safe: True

Add as many entries as you like.

Wednesday, 15 May 2013

C# code to Create SharePoint list programmatically using visual studio

In this article I’m going to discuss how we can create a SharePoint list programmatically in c# and how we can add columns to the created list. Actually this is very simple task; this is a sample code.

public void createList()
{
    // choose your site
    SPSite site = new SPSite("Site URL");
    SPWeb web = site.OpenWeb();
    SPListCollection lists = web.Lists;
    // create new Generic list called "My List"
    lists.Add("My List", "My list Description", SPListTemplateType.GenericList);
    SPList list = web.Lists["My List"];
    // create Text type new column called "My Column"
    list.Fields.Add("My Column", SPFieldType.Text, true);
    // make new column visible in default view
    SPView view = list.DefaultView;
    view.ViewFields.Add("My Column");
    view.Update();
}


In the above code I have created Generic list and normal Text column. You can use whatever list type and field type according to your requirement

Remove Event Receiver in Sharepoint List programmatically using feature

Create a custom feature for a custom list, that feature will be added to all the custom lists. Then if you want to create list dynamically and don’t want to add those features you can use this code to remove unwanted events.

public void  removeEvents()
{
 // choose your site
 string strUrl = "http://mysite:5050/";
 using (SPSite site = new SPSite(strUrl))
 {
  using (SPWeb web = site.OpenWeb())
  {
   SPListCollection lists = web.Lists;
   SPList list = web.Lists["My List"];
       
   SPEventReceiverDefinitionCollection erdc = list.EventReceivers;
   List <SPEventReceiverDefinition> eventsToDelete = new List <SPEventReceiverDefinition>();
       
   foreach (SPEventReceiverDefinition erd in erdc)
   {
    if (erd != null)
    {
     try
     {
      eventsToDelete.Add(erd);
     }
     catch (Exception e)
     {
      Console.Write(e.ToString());
     }
    }
   }
   foreach (SPEventReceiverDefinition er in eventsToDelete)
   {
    //if(er.Type == SPEventReceiverType.ItemAdded)
    er.Delete();
   
  }
 }
}

Before delete the Event Receiver, if you want you can check the type and delete. In the above code I have commented that part. So if you use the above code as it is, it will remove all the Event Receivers.

Create Simple Web Service in Visual Studio 2008 / 2010


1. Create the Web Service


First create new project and select "New ASP.NET Web Service Application" and I'm giving the name "MyFirstWebService" to it, you can give any name to your project.

Now you can see auto generated code that you can add methods to create your web service. You can see simple method "HelloWorld" and in this sample code I have removed it.

I'm going to add simple method called "simpleMethod" which takes a string as an input and add "Hello" to beginning of that string. Now the code will appear like bellow.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace MyFirstWebService
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string simpleMethod(String srt)
        {
            return "Hello "+srt;
        }
        [WebMethod]
        public int anotherSimpleMethod(int firstNum, int secondNum)
        {
            return firstNum + secondNum;
        }
    }
}

Then you can run your code and you can see the resulting page as bellow.

2. Create the Client Program


We have created our simple web service and we have to create small
client program to use this web service. There you can open another
instant of Visual Studio and create new "Console Application" project.


Then you have to add Service Reference so that you can access your web service. Here are the screen-shots.




Here you have to give the URL of the web service we created earlier.
As I said before previously created web service application should be
running on another instant of Visual Studio.


Note that I have set the "Web reference name" as "TestWeb".


Now you can update your client program using following code. Note the line 5 "using WebServiceTest.TestWeb;".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebServiceTest.TestWeb;
namespace WebServiceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Service1 webservice = new Service1();
            string srt = webservice.simpleMethod("Saranga Rathnayake");
            Console.WriteLine(srt);
            Console.WriteLine(webservice .anotherSimpleMethod(4,3));
        }
    }
}


Now you can run the client program to see the result.

3. Publish Our Web Service in Internet Information Service (IIS)


Let's see how we can publish our web service in IIS. Otherwise you always need to run your web service application in separate VS instant. There first stop the web service application and go to the Solution Explore and Right Click on the project. Then select "Publish...".


Then the following window will appear and there you can directly publish to the IIS by selecting "Web Deploy" as the publishing method. But here I'm going to use the "File System as the publishing method. There you have to provide the target location. I have created new folder called "MyApp" in my D drive and selected it.


Now click "Publish" and check the "MyApp" folder. There you will be able to see Service1.asmx file, Web.config file and bin folder which contains the DLL file has been generated. Then copy this "MyApp" folder to "wwwroot" folder. You may find it in "C:\inetpub\wwwroot".

Now enable IIS in your computer and open IIS Manager. I'm going to add my service to Default Web Site. There Right Click on the "Default Web Site" and click "Add Application...".


There you will get following window. Now you can provide appropriate Alias (I have given testservice) and select the physical path of your application. There you can provide the path to the folder we copied previously as following figure and click Ok.

You have to make sure that the application pool identity has Read access to the physical path. So it is better if you copy your files to the "wwwroot" folder other than keep it in separate partition. Please check the following screen-shot


Now restart the IIS and goto http://localhost/testservice/Service1.asmx. You will be able to see the Web Service running.

Now you have published your web service in IIS and you can update the Client Program by giving the new Web Reference URL using Properties Window.

ADD|Update|Delete Item in list by using SharePoint Web Services

Here we discuss how we can update a SharePoint list using Web Services. Please refer my previous article on "SharePoint List Web Service GetListItems" to learn how to add Web References to your project. Then you can use the following sample codes to Update SharePoint lists.

Updating Existing Items
In the following code I have update the "Tasks" list, there I have update the title of two items which has the ID 7 and 10.


public void updateListItemsWS()
{
    WS_Lists.Lists myservice = new WS_Lists.Lists();
    myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
    myservice.Url = "http://mermoss:5050/testsara/_vti_bin/Lists.asmx";
    try
    {
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");

        elBatch.SetAttribute("OnError", "Continue");
        elBatch.SetAttribute("ListVersion", "1");

        string strBatch = "<Method ID='1' Cmd='Update'>" +
              "<Field Name='ID'>7</Field>" +
              "<Field Name='Title'>Sara1</Field></Method>" +
              "<Method ID='2' Cmd='Update'><Field Name='ID' >10</Field>" +
              "<Field Name='Title'>Sara2</Field></Method>";

        elBatch.InnerXml = strBatch;
        myservice.UpdateListItems("Tasks", elBatch);

    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
}

Delete Items:

To delete item, use following phrase in the above code, this will delete the item which has ID of 10.

string strBatch = "<Method ID='1' Cmd='Delete'>" +
"<Field Name='ID'>10</Field></Method>";

Add New Item:
To add item, use following phrase in the above code,

string strBatch = "<Method ID='1' Cmd='New'>" +
"<Field Name='ID'>New</Field>"+
"<Field Name='Title'>TestTitle1</Field>"+
"</Method>";

Use SharePoint List Web Service to get list items by using GetListItems method

Lets discuss how we can retrieve data from a SharePoint List using its Web Services. First to know about SharePoint Web Services please refer this. We can user List Web Service which provides methods for working with SharePoint Lists, Content Types, List Items, and Files to read a List. Here we are going to use GetListItems method.

To use the above method we should know the GUIDs of the target list and view. Please follow my article on SharePoint List GUIDs to see how we can get them.

This is how you can Add Web Reference; I’ll get created Web Site Project in Visual studio to illustrate. Actually it is simple, first click on Add Web Reference and give the URL to the Web Service.
This is a sample code to read SharePoint list,

public void getListData()
{
    WS_Lists.Lists myservice = new WS_Lists.Lists();
    myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
    myservice.Url = "http://merdev-moss:5050/testsara/_vti_bin/Lists.asmx";
    try
    {
        /* Assign values to pass the GetListItems method*/
        string listName = "{5C65CB1A-2E1B-488A-AC07-B115CD0FC647}";
        string viewName = "{75E689B4-5773-43CB-8324-58E42E1EB885}";
        string rowLimit = "100";

        // Instantiate an XmlDocument object
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
        System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
        System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");

        /*Use CAML query*/
        query.InnerXml = "<Where><Gt><FieldRef Name=\"ID\" />" +
        "<Value Type=\"Counter\">0</Value></Gt></Where>";
        viewFields.InnerXml = "<FieldRef Name=\"Title\" />";
        queryOptions.InnerXml = "";

        System.Xml.XmlNode nodes = myservice.GetListItems(listName, viewName, query, viewFields, rowLimit, null, null);

        foreach (System.Xml.XmlNode node in nodes)
        {
            if (node.Name == "rs:data")
            {
                for (int i = 0; i < node.ChildNodes.Count; i++)
                {
                    if (node.ChildNodes[i].Name == "z:row")
                    {
                        Response.Write(node.ChildNodes[i].Attributes["ows_Title"].Value + "</br>");
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
}
In the above code I have use CAML queries to get the result. It will return all the result because I’m searching for Items which has ID greater than 0. It is always true. If you want to know how to write CAML quires easily please refer my article on CAML & SPQuery in SharePoint.

Ads