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 23, 2012

Error: The language-neutral solution package was not found.

While using Visual Studio, you may get the following error
“The language-neutral solution package was not found.”
Solution:
There are three ways you can fix this problem:
1. This may be caused due to the CACHING issue in the Visual Studio and hence restarting the Visual Studio will help you in fixing the issue.
2. Sometimes the solution you are trying to update will not get updated properly. Hence delete the following folders (By navigating to In Visual Studio   -> Right click on project in Solution Explorer window -> Select Open folder in Windows Explorer)  bin, obj and package.
After deleting these folders, rebuild and deploy the solution which will work out.
3. Or finally, you can retract the solution from the Central Admin (in case of SharePoint related issues) and then uninstall the solution dll from the assembly folder. Then try to deploy the solution.
Please free to comment and share this post, if this helps you!

May 16, 2012

Chart Controls in ASP.Net

I was looking at creating chart controls for implementing in the .Net web applications. I didn’t like to use the 3rd party tools or any freeware tools. Well, while browsing found a cool feature provided by MICROSOFT for the same.
In this article, we will have a look at the CHART CONTROLS in .Net applications.
Pre-requisites
Ø  Visual Studio 2008 SP1, Link to download
Ø  .NET Framework 3.5 SP1, Link to download
Ø   Microsoft Chart Controls, Link to download
Ø  Visual Studio 2008 Add-on for the Chart Controls, Link to download
Ø  Documentations by Microsoft, Link to download
Ø  Web and Windows Application Samples, Link to download
Types of Charts
Ø  Area Charts
Ø  Bar column Charts
Ø  Circular Charts
Ø  Combination Charts
Ø  Data Distribution Charts
Ø  Error Bar
Ø  Financial Charts
Ø  Line Charts
Ø  Pie Doughnut Charts
Ø  Point Charts
Ø  Price Range Financial Charts
Ø  Pyramid Funnel Charts
Ø  Range Charts
Examples
The examples provided by Microsoft are very clear and easy. Hence you can download and try the samples. Also, the control is easy to use, just drag and drop the control and start using it.
Namespace
The namespace which we use here is System.Web.UI.DataVisualization.Charting.
More about Chart Controls
Ø  This control is not available for Visual Studio 2005.
Ø  It is available as a native component in Microsoft Visual Studio 2008 SP1.  First you have to install the Chart Controls provided by Microsoft and then the add-ons for using the control.
Ø  But in Visual Studio 2010, it is present as inbuilt component. We can just use it!
More Useful Reference Links
Installing and using Chart Controls in Visual Studio 2010, here.
Using Chart Controls in Visual Studio 2005, here.
Happy Sharing!

Windows System Shows Blank Screen after logging in

Scenario:
I have faced many situations like after logging into the Windows Operating system machine (Especially Windows 7 and Windows Server which I have faced); it takes more hours showing a BLANK SCREEN without showing the desktop. It wasted my time more. So I was searching for a solution which would help in fixing the issue.
Solution:
1. Press CTRL + ALT + DEL
2. Select Start Task Manager from the list
3. In the Task Manager Select -> File -> New Task (New Task (Run...)) – I have Win 7 as shown below:
4. Type “Explorer” in the text box and click OK.
5. Now, you will see the explorer opening suddenly and also your desktop is ready to use.
Hope this helps some one’s time. Happy Sharing!

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!