Showing posts with label Tutorials. Show all posts
Showing posts with label Tutorials. Show all posts

Dec 11, 2012

Basics of Web Services

Introduction:
In this article, we aim at learning the basics of web services and understand how does web service works.
WebService:
1.   Web services are the easy way to create communications between different applications of different platform.
2.  Web Services extend these models a bit further to communicate with the Simple Object Access Protocol (SOAP) and Extensible Markup Language (XML) to eradicate the object-model-specific protocol barrier.

Components of Web Service:
All the standard Web Services works using following components
  1. SOAP (Simple Object Access Protocol)
  2. UDDI (Universal Description, Discovery and Integration)
  3. WSDL (Web Services Description Language)
SOAP (Simple Object Access Protocol):
SOAP is an XML-based protocol to let applications exchange information over HTTP. Simply, SOAP is a protocol for accessing a Web Service.
  1. It is a communication protocol and it is a format for sending messages.
  2. It is designed to communicate via Internet (W3C standard)
  3. It is platform and language independent
  4. SOAP allows you to get around firewalls
WSDL (WebServices Description language):
It is a W3C standard used to describe and locate the web service in XML language format.
UDDI (Universal Description, Discovery and Integration):
  1. It is a directory for storing information about web service
  2. It communicates via SOAP
  3. It is built on .NET platform
Why web service?
  1. Interoperability
  2. Usability
  3. Deployability
  4. Reusability
For more details on the advantages and disadvantages refer this MSDN article: http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/435f43a9-ee17-4700-8c9d-d9c3ba57b5ef

To know about creating a web service using ASP .NET read this article.
To know about consuming a web service using ASP .NET read this article.

Captcha using Java Script

Background:
Now a days, all the web sites requires inputs (contact us, feedback, etc.) from the end users. But many sites face a problem of spam or unwanted or junk messages. To avoid this we have a java script code which will generate the random codes which should be entered by the users manually.
This avoids the spam being automated or entered by the unwanted users being entered in to the site.

Solution:
Below is the code which consists of Java script implemented in HTML page for reference.

Random Message



Below is the screenshot of the same:
Here is the link to download the image and hmtl file. Captcha using JavaScript.
Hope this component helps using it in your website to avoid spam and unwanted messages.

Jul 1, 2012

Visual Studio Workflow in SharePoint

Part II
To know about the Basics and Advantages of using Visual Studio Workflow
read this article.
In this article, we will how to Create a Simple Sequential Workflow Console Application.
Steps:
1. Open Microsoft Visual Studio -> File -> New Project -> Select Visual C# -> SharePoint -> Workflow -> SequentialWorkflowConsoleApplication

2.  You can see the required DLL’s added in the solution for running the work flow in the Solution Explorer

3.  From the Toolbox -> Select Code -> drag and drop inside the designer view as shown below. Double Click on the codeActivity1 -> you will be navigated to Code behind page of the solution.


4. I have initialized a variable with get and set methods and activity for the code1 as shown below:

5. Now, go to the Design view -> From Toolbox -> Drag and drop IF ELSE activity and the code activity for IF and ELSE branch

6. Right click on codeActivity2 and click Generate handlers to create handlers the activity and do the same for codeActivity3
7. Now, we will set the condition for the ifElseActivity1 and 2. Right Click on ifElseActivity1 -> Properties -> Condition -> Select Declarative Rule Condition


8. Give the Condition Name and then Click on Expression for setting the condition:
9. Following are the conditions set for both the activities:


10.Now,if you click on any one of the activity -> properties -> select the name
then -> you can see the two conditions being used in the solution as shown:

11. Finally, I have added the message to be returned for the both activities

12. Now build the solution and then execute the code:

Here is the full solution. Click to download. Happy Sharing!
Hope, you have enjoyed this article.
Please free to comment and share this article, if it helps you!
Happy Coding!!

Visual Studio Workflow in SharePoint

Part I
To know about the Basics of Workflow in SharePoint, read this article.
To know about the Creating a Designer Workflow, read this article.
To know about the New Features added in SharePoint Designer 2010, read this article.
In this we will learn about Basics of Visual Studio Workflows in SharePoint.
Windows Workflow Foundation -WWF:
Windows Workflow Foundation (WF) is a Microsoft technology for defining, executing, and managing workflows.
Why Visual Studio Workflow is necessary?
From the business perspective, we need some custom workflows to be designed and developed in order to meet the requirements. By using designer, we cannot achieve all the custom actions and hence Visual Studio workflows are necessary.
Moreover, Visual Studio is a known environment to the developers (working with Microsoft Software’s) and hence the design and development is very easy.
Software Requirements
  Ø  Windows Server 2003 R2 Download
  Ø  Microsoft .NET framework 3.0 Download
  Ø  Windows SharePoint Services 3.0 Download
  Ø  Microsoft Visual Studio 2005 with SP1 Download
  Ø  Windows SharePoint Services 3.0 SDK Download
  Ø  Visual Studio 2005 Extensions for Windows Workflow Foundation Download
   Limitations of using Designer Workflow:
  Ø  A major disadvantage is that, you can create only Sequential Workflows using designer and not the State Machine workflows.
  Ø  We cannot write custom code and custom activities for workflows while creating using designer.
  Ø  Maintenance and upgradeable methods are very less.
To know how to create a sample Sequential Workflow using Visual Studio, read this article Visual Studio Workflow in SharePoint.

Jun 9, 2012

Hiding Default Title Column in a list in SharePoint

In this article, we will know about a small tip, How to hide the default title column which is created by default whenever a list is created in a SharePoint list.
Steps:
1. Whenever a list is created, you will see a default column “Title” in the list.
2. In Some cases, we do not need this and needs that to be hidden.
3. Go to Settings -> List Settings -> Advanced Settings (General Settings) -> Change Allow Management of Content Types to YES
4. Now List Settings page -> Click on ITEMS
You will see the list of columns in the list. Now we want to hide the Title Column and hence click on the Title column
There will be option for permanently hiding the column. Select the option “Hidden will not appear in forms” and click OK. 
5. We have hid the column in the form but it will appear in the VIEW. So, we have to hide the column in the view. Click on the View in the List.
In the Columns Deselect the Title and click OK.
6. When you click on New for adding a new item in the list, then you will not see the Title column in the form or when you view the list, you will not see the Title column in the view.

Jun 4, 2012

Creating and Deploying Custom Web Part in SharePoint

In this article, we will learn how to create a Custom Web Part in SharePoint using Visual Studio.
After reading this article, you will learn the following:
  Ø  Creating custom web part using visual studio
  Ø  How to use Labels, Rich text box and Buttons (with events) and validation   
        controls in the custom web part?
  Ø  How to validate the fields in custom web part in SharePoint?
  Ø  How to deploy the web part in SharePoint site?

Scenario:
Suppose that in a SharePoint page, you want the users to comment about the page or send some feedback, and then you can use this web part.

Solution:
It is created the following solution using Visual Studio 2005.
Steps:
1. Open the Visual Studio -> Click File -> New project -> Select Visual C# from Project types -> SharePoint -> web Part (Use this link for downloading the Visual Studio Extensions for SharePoint for creating SharePoint solutions in the Visual Studio 2005)
2. Once created, delete the web part present in the solution named webpart1. Now click on the Project Solution -> Add -> New Item -> SharePoint -> Web Part -> Give the name as CommentWebPart -> Click Add to create a web part file in the project solution
3. Now, we will create controls and add in the web part. See the following code which is used for creating this web part.
Program.cs:
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace CommentWebPart
{
    [Guid("745a216c-1126-4000-a189-02ebc60d7e67")]
    public class CommentWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        TextBox txtContactName;
        TextBox txtEmailAddress;
        InputFormTextBox txtBox;
        Button btnSubmit;
        Button btnCancel;
        Label lblSpace;

                                     
        public CommentWebPart()
        {
            
        }

        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();

                Table t;
                TableRow tr;
                TableCell tc;

                // Creating a table to add the controls in it
                t = new Table();

                // Label for contact name
                tr = new TableRow();
                tc = new TableCell();
                tc.Style["padding-top"] = "5px";
                tc.VerticalAlign = VerticalAlign.Top;
                Label lblConatctName = new Label();
                lblConatctName.Text = "Conact Name";
                tc.Controls.Add(lblConatctName);
                tr.Controls.Add(tc);


                // Text box for contact name
                tc = new TableCell();
                tc.VerticalAlign = VerticalAlign.Top;
                txtContactName = new TextBox();
                txtContactName.ID = "txtContactName";
                txtContactName.Width = Unit.Pixel(250);
                tc.Controls.Add(txtContactName);

                /* Creating required field validator for Contact Name. 
                * If the value is empty, then should throw error on clicking button Submit*/

                RequiredFieldValidator objName = new RequiredFieldValidator();
                objName.ControlToValidate = "txtContactName";
                objName.ErrorMessage = "Conatct Name cannot be empty";
                tc.Controls.Add(objName);
                tr.Controls.Add(tc);

                t.Controls.Add(tr);
                
                // Label for email id
                tr = new TableRow();
                tc = new TableCell();
                tc.VerticalAlign = VerticalAlign.Top;
                Label lblEmailId = new Label();
                lblEmailId.Text = "Email ID";
                tc.Controls.Add(lblEmailId);
                tr.Controls.Add(tc);

                // Text box for email id
                tc = new TableCell();
                tc.VerticalAlign = VerticalAlign.Top;
                txtEmailAddress = new TextBox();
                txtEmailAddress.ID = "txtEmailAddress";
                txtEmailAddress.Width = Unit.Pixel(250);
                tc.Controls.Add(txtEmailAddress);

                /* Creating required field validator for Email ID. 
                * If the value is empty, then should throw error on clicking button Submit*/

                RequiredFieldValidator objEmailID = new RequiredFieldValidator();
                objEmailID.ControlToValidate = "txtEmailAddress";
                objEmailID.ErrorMessage = "Email Id cannot be left empty";
                tc.Controls.Add(objEmailID);
                tr.Controls.Add(tc);

                /* Creating Regular Expression validator for Email ID. 
                * If the value is empty or not in a regular Email ID format,
                * then should throw error on clicking button Submit*/

                RegularExpressionValidator objEmail = new RegularExpressionValidator();
                objEmail.ControlToValidate = "txtEmailAddress";
                objEmail.ErrorMessage = "Email Id is not in the correct format";
                objEmail.Display = ValidatorDisplay.Dynamic;
                objEmail.ValidationExpression = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-
                Z]\.)+[a-zA-Z]{2,9})$";
                tc.Controls.Add(objEmail);
                tr.Controls.Add(tc);

                t.Controls.Add(tr);

                // Label for text box
                tr = new TableRow();
                tc = new TableCell();
                tc.VerticalAlign = VerticalAlign.Top;
                Label lblComments = new Label();
                lblComments.Text = "Comments";
                tc.Controls.Add(lblComments);
                tr.Controls.Add(tc);
                               
                            
                // Creating a rich text box for comments
                tc=new TableCell();
                tc.VerticalAlign=VerticalAlign.Top;
                txtBox=new InputFormTextBox();
                txtBox.ID="txtBox";
                txtBox.RichText = true;
                txtBox.RichTextMode=SPRichTextMode.FullHtml;
                txtBox.TextMode=TextBoxMode.MultiLine;
                txtBox.Rows=10;
                txtBox.Width=Unit.Percentage(100);
                txtBox.Height = Unit.Percentage(30);
                tc.Controls.Add(txtBox);
                tr.Controls.Add(tc);

                t.Controls.Add(tr);

                // Creating empty cell for spacing
                tr = new TableRow();
                tc = new TableCell();
                lblSpace = new Label();
                lblSpace.Text = "   ";
                tc.Controls.Add(lblSpace);
                tr.Controls.Add(tc);

                tc = new TableCell();

                // Creating button submit event
                btnSubmit = new Button();
                btnSubmit.ID = "btnSubmit";
                btnSubmit.Text = "Submit";
                btnSubmit.Click +=new EventHandler(btnSubmit_Click);
                tc.Controls.Add(btnSubmit);
                
                // Creating button cancel event
                btnCancel = new Button();
                btnCancel.ID = "btnCancel";
                btnCancel.Text = "Cancel";
                btnCancel.Click +=new EventHandler(btnCancel_Click);
                
                lblSpace = new Label();
                lblSpace.Text = "   ";
                tc.Controls.Add(lblSpace);
                tr.Controls.Add(tc);
                tc.Controls.Add(btnCancel);
                
                tr.Controls.Add(tc);

                t.Controls.Add(tr);

                this.Controls.Add(t);

            }
            catch (Exception ex)
            {
                string err = "Error Occured while loading the web part" + ex.Message;
            }
      }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                // Creating the EMail message 
                System.Text.StringBuilder txtMessage = new System.Text.StringBuilder();
                txtMessage.Append("Contact Name: ");
                txtMessage.AppendLine(txtContactName.Text);
                txtMessage.Append("Email Address: ");
                txtMessage.AppendLine(txtEmailAddress.Text);
                txtMessage.AppendLine();
                txtMessage.AppendLine("Comment:");
                txtMessage.AppendLine(txtBox.Text);

                // Creating the Email subject message
                System.Text.StringBuilder txtsubject = new System.Text.StringBuilder();
                txtsubject.Append("Comment from");
                txtsubject.Append(txtContactName.Text);

                // Cerating the message header
                System.Collections.Specialized.StringDictionary txtmessageHeader = new
                System.Collections.Specialized.StringDictionary();
                
                // To whom the mail should be sent
                txtmessageHeader.Add("to", "MAIL ID OF THE USER TO WHOM THE COMMENT HAS TO BE SENT");

                // From whom the comment is being sent
                txtmessageHeader.Add("from", txtEmailAddress.Text);
                txtmessageHeader.Add("subject", txtsubject.ToString());
                txtmessageHeader.Add("content-type", "text/RichText");

                // Send the email with the comment from the user
                Microsoft.SharePoint.Utilities.SPUtility.SendEmail(SPContext.Current.Web, txtmessageHeader,               
                txtMessage.ToString());

                // Clear the fields after sending the mail
                txtContactName.Text = "";
                txtEmailAddress.Text = "";
                txtBox.Text = "";
                
            }
            catch (Exception ex)
            {
                string str= "Unable to send mail:" + ex.Message;
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            // Clear the fields on clicking cancel
            txtContactName.Text = "";
            txtEmailAddress.Text = "";
            txtBox.Text = "";
        }

   }
}
4. Build the web part and check for errors.
5. Now, to deploy the solution Right Click on the project solution -> Select Deploy to add the solutions in the Solution Gallery.

6. Now the solution will be present in the Solution Gallery (Central Administration-> Operations -> Solution Management) in the SharePoint site and we have to add it to our site.
7. Go to the SharePoint site -> Site Actions -> Site Settings -> galleries -> web parts

8. Now, Click on New -> You will see the list of deployed web parts and click on Comment Web part and then Click Populate Gallery


9. Now the web part is available in the SharePoint site but we have to add Safe control entry in the web.config of the site. Add the following in the web.config in the SAFE CONTROLS tag section 


10. Now you can add the created custom web part in your SharePoint site. This will look as follows:
According to the required field validation, if the name and email id is field is left empty then the following screen should be seen:
If the Email ID is given in the wrong format then according to the regular expression validation, the following screen should be seen:
If the input fields are correctly given, then you will be able to submit the 
comment to the described mail ID in the code as shown below:
HAPPY SHARING J
Also, to know about the Basics of Visual Web Part read this article.
To know about Creating and Deploying a Visual Web Part using Visual Studio 2010 read this article.
Please free to share your thoughts and share this post if this helps you!

May 14, 2012

Change the Color of a Column in a List in SharePoint

In this article, we will know how to change the color of a column based upon the values in the column. It is something like “Color Indicator” in SharePoint.
Scenario:
We have a custom list used for Project Tracking. In the list, we have column named STATUS for tracking the project.
Whenever an item in the list is updated with the status in the column, then the background color of the status column should automatically change depending upon the status. Hence it gives a better UI for tracking the status.
Solution:

1. Create a custom list named “Project Tracking System” with the columns such as “Title”, “Description” and Status with the data type as shown below:

Columns with the data types to be created:

2. Now, we will insert 4-5 items in the list created. 
In the above list, we can see that the status column is updated, but it would be good when we have background color of the each status separately. It is gives easy tracking to the users.
3. We can achieve this through JAVA SCRIPT
4. Add a Content Editor Web part below the list as shown below:
5. Now in the content editor web part, add the below java script code (Open the tool pane->Source Editor->Place the Java Script->Click Ok) and save the page.
Add the below code in the script JavaScript tag
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var colorCode = document.getElementsByTagName("td")// finding all the TD tags
var i=0; 
for (i=0;i
{
if (colorCode[i].className=="ms-vb2")  
{ 
if (colorCode[i].innerHTML=="Not Started")//finding the word to which the color has to be set
{ 
colorCode[i].style.backgroundColor='lightblue'; // setting the color depending upon the value
colorCode[i].style.color='Black'; // setting the color of the words inside the content                                     
} 
if (colorCode[i].innerHTML=="Started")  
{ 
colorCode[i].style.backgroundColor='Brown';
colorCode[i].style.color='Black';
} 
if (colorCode[i].innerHTML=="In Progress")  
{ 
colorCode[i].style.backgroundColor='Orange';
colorCode[i].style.color='Black'; 
} 
if (colorCode[i].innerHTML=="Completed")  
{ 
colorCode[i].style.backgroundColor='green';
colorCode[i].style.color='Black'; 
} 
if (colorCode[i].innerHTML=="Deffered")  
{ 
colorCode[i].style.backgroundColor='Red'; 
colorCode[i].style.color='Black'; 
} 
} 
}

6. Now, you can see the status column background is changed depending upon the status inserted for each item as shown below:
It gives good interface to the users and also we can categorize the status easily.
Please free to comment and share the post, if it helps you!

May 9, 2012

CAML Query to Get Data from SharePoint List

To know about the Basics of the CAML query read this article.
To know about using CAML query builder to create CAML queries, read this article.
In this article, we will learn how to use CAML query in Microsoft Visual Studio
Scenario:
I have a custom list named “Product List” with the columns named Title, Price, Quantity and Is Available.
I want to retrieve the products with price greater than 1000 and lesser than 10000. Then I have to order the results depending upon the quantity in descending order.
Using the CAML query builder, I have created a CAML query for the above scenario and the query is as follows:
<Query><Where><And><Gt><FieldRef Name="Price" /><Value Type="Number">1000</Value></Gt><Leq><FieldRef Name="Price" /><Value Type="Number">10000</Value></Leq></And></Where><OrderBy><FieldRef Name="Price" Ascending="False" /></OrderBy></Query>

Implementing CAML Query in Microsoft Visual Studio
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace UsingCAMLQuery
{
    class Program
    {
        static void Main(string[] args)
        {
            const string camlQuery = @"100010000";
            try
            {
                using (SPSite objSite = new SPSite("sitename"))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        // Building a query
                        SPQuery query=new SPQuery();
                        query.Query=camlQuery;
                     
                        // Retrieving the data from the List
                        SPList objList=objWeb.Lists["Product List"];
                        SPListItemCollection items= objList.GetItems(query);

                        // Prinitng the header
                        Console.WriteLine("{0,-25} {1,-20} {2,-15} {3}", "Title", "Price", "Qunatity", "Is Available");

                        foreach (SPListItem objListItem in items)
                        {
                            Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}", objListItem["Title"], objListItem["Price"], 
                                                                             objListItem["Quantity"], objListItem["Is Available"]);
                        }

                    }
                    Console.ReadLine(); 
                }
 
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error Occured:", ex.Message);
            }
            Console.ReadLine();
        }
    }
}
The full solution can be downloaded from the following link
Please free to comment and share this post if it helps you!

Using CAML Query Builder for SharePoint

To know about the Basics of the CAML query read this article.
Download Link
Use the following link to download the CAML Query builder.
How to use CAML Query Builder to create a query
Following are the steps for using the CAML query builder to create a CAML query
1. Open the CAML query builder. Type the URL to connect to the SharePoint site and check Credentials of the current user to login

2. Once clicked connect, you will see the following window SharePoint site with all the lists and libraries in the site in a tree view structure which is shown below: 

3. Now we will create a new query on a list named “Product List” as shown below:

4. We will start creating a new query which is as follows:



5. You will find the query being created depending upon your selection from the list

6. Clicking on Execute, you will see the query being executed and the result is being displayed in the result tab as shown below:

The Query created is:
<Query>
           <Where>
                       <Gt>
                              <FieldRef Name="Quantity" />
                              <Value Type="Number">0</Value>
                      </Gt>
          </Where>
          <OrderBy>
                       <FieldRef Name="Price" Ascending="True" />
          </OrderBy>
</Query>
Hence, CAML Query Builder allows us to create the queries very easily so that it can be used in the SharePoint programming.
Now, we will have a question, how to use this query in the Visual Studio to retrieve the data from a list.
To know how to use CAML query in Visual Studio programming, read this article.