SharePoint Web Part Debugging
Posted: 20/01/2012 Filed under: SharePoint, Visual Studio | Tags: Debugging, Web Part Leave a comment »NOTE: This applies to going through the steps manually using Visual Studio 2010. And the issue in concern, is breakpoints not being hit.
Debugging web parts in SharePoint are not difficult, but they can be annoying. This article on MSDN, (albeit an old one) describes how this can be achieved.
Essentially, ensure that the web part assembly is part of your web.config safe control list. Then, from Visual Studio, select Debug –> Attach to Process. This is where you will need to select the application pool IIS Process, which will be w3wp.exe.
Now you can set your breakpoint and begin debugging….right? Well not exactly, chances are you will run into a problem in which, the breakpoint will currently not be hit.
This is because we are trusting Visual Studio 2010 to determine the type of code being debugged. We’ll have to change this, by selecting Debug –> Attach to Process, then under Attach To, click Select.
Note the option, Automatically determine the type of code to debug
Click and Select Debug these code types option. The tick and select Managed (v2.0, v1.1, v1.0), click on OK, then attach the w3wp.exe process.
Now set you breakpoint and begin debugging your web part. The issue of not hitting a breakpoint will not occur again.
C# Working with Timer Object
Posted: 13/01/2012 Filed under: Programming | Tags: C# Leave a comment »A timer object can be really helpful when there is a need of some form of scheduling. For example, writing entries into a log file hourly. MSDN defines the Timer class as an object that generates recurring events in an application.
The code snippet below shows a simple example using Timer to write out a line every 5 seconds (console application).
1: using System;
2: using System.Timers;
3:
4: static void Main(string[] args)
5: {
6: BeginSchedule();
7: Console.ReadKey();
8: }
9:
10: private static void BeginSchedule()
11: {
12: var timer = new Timer
13: {
14: // Gap between each event execution
15: // set to 5 seconds in miliseconds.
16: // Then timer is started.
17: Interval = 5000,
18: Enabled = true
19: };
20:
21: // Event that is called after each timer interval.
22: timer.Elapsed += new ElapsedEventHandler(TimerElapsedEvent);
23: }
24:
25: static void TimerElapsedEvent(object sender, ElapsedEventArgs e)
26: {
27: Console.WriteLine("5 seconds later.");
28: }
Code well.
C# Creating a CSV File
Posted: 13/01/2012 Filed under: Programming | Tags: C# Leave a comment »If you need to create a comma-separated values (CSV) file, then the code snippet below shows you how, quickly and easily.
1: using System;
2: using System.Collections.Generic;
3: using System.IO;
4: using System.Text;
5:
6: private static void CreateCsvFile()
7: {
8: var filePath = @"C:\Books.csv";
9:
10: // Initialise stream object with file
11: using (var wr = new StreamWriter(filePath, true))
12: {
13: // Collection of book titles
14: var row = new List<string>
15: {"A Game of Thrones", "A Clash of Swords", "A Feast for Crows", "A Dance with Dragons"};
16:
17: var sb = new StringBuilder();
18:
19: foreach (string value in row)
20: {
21: // Add a comma before each string
22: // this adds a comma before the book title
23: if (sb.Length > 0)
24: sb.Append(",");
25:
26: sb.Append(value);
27: }
28:
29: // write output to file
30: wr.WriteLine(sb.ToString());
31: }
32: }
Hope this helps, happy coding.
C# Sending and Receiving Information through URL
Posted: 11/01/2012 Filed under: Programming | Tags: C# Leave a comment »Imagine if you had an application that is not a web application but interacts with one. If this is your scenario, then we can use the WebClient class. As it states on MSDN, this class provides common methods for sending data to and receiving data from a resource identified by a URI.
Code snippet below shows a very basic example in accomplishing this.
1: using System.IO;
2: using System.Net;
3:
4: static void Main(string[] args)
5: {
6: // Initialise new WebClient object to send request
7: var client = new WebClient();
8:
9: // Add the QueryString parameters as Name Value Collections
10: // that need to go with the HTTP request, the data being sent
11: client.QueryString.Add("id", "00001");
12: client.QueryString.Add("author", "Harish Mathanan");
13: client.QueryString.Add("tag", "Programming");
14:
15: // Prepare the URL to send the request to
16: string url = "http://somerandomsite.com";
17:
18: // Send the request and read the response
19: var stream = client.OpenRead(url);
20: var reader = new StreamReader(stream);
21: var response = reader.ReadToEnd().Trim();
22:
23: // Clean up the stream and HTTP connection
24: stream.Close();
25: reader.Close();
26: }
2011 in review
Posted: 01/01/2012 Filed under: Uncategorized Leave a comment »The WordPress.com stats helper monkeys prepared a 2011 annual report for this blog.
Here’s an excerpt:
The concert hall at the Syndey Opera House holds 2,700 people. This blog was viewed about 14,000 times in 2011. If it were a concert at Sydney Opera House, it would take about 5 sold-out performances for that many people to see it.
Click here to see the complete report.
C# Reading XML Files
Posted: 19/12/2011 Filed under: Programming | Tags: C#, XML 2 Comments »This post is written with the intention of showing you very quickly how to read an XML document through code.
Listed below is my XML file that I will be working on, filled with fictional data. It’s essentially a listing of books, with their Title, Publisher and Author.
1: <?xml version="1.0" encoding="utf-8" ?>
2: <!-- Listing of all Books -->
3: <Books>
4: <Book>
5: <Title>Master ASP.NET Development</Title>
6: <Publisher>MS Press</Publisher>
7: <Author>Scott Guthrie</Author>
8: </Book>
9: <Book>
10: <Title>Deep Dive Web Programming</Title>
11: <Publisher>MS Press</Publisher>
12: <Author>Scott Hanselman</Author>
13: </Book>
14: <Book>
15: <Title>ASP.NET Good Sense</Title>
16: <Publisher>MS Press</Publisher>
17: <Author>Jon Galloway</Author>
18: </Book>
19: </Books>
The simplest approach to reading this file would be to use the XmlTextReader class (part of the System.Xml namespace). The code snippet below shows you how to put this class into action.
1: // Initialise object by passing in a known path to XML file.
2: // This can also be an URL.
3: XmlTextReader xml = new XmlTextReader(@"C:\Projects\ConsoleReadXML\ConsoleReadXML\Books.xml");
4:
5: while (xml.Read()) // Ensure there is content.
6: {
7: if (xml.NodeType.Equals(XmlNodeType.Element)) // Find all nodes that are elements.
8: {
9: switch (xml.Name) // Evaluates each element by its name.
10: {
11: case "Title":
12: Console.WriteLine();
13: Console.WriteLine(xml.ReadElementString("Title")); // Reads the value of the element.
14: break;
15: case "Publisher":
16: Console.WriteLine(xml.ReadElementString("Publisher")); // Reads the value of the element.
17: break;
18: case "Author":
19: Console.WriteLine(xml.ReadElementString("Author")); // Reads the value of the element.
20: break;
21: default:
22: break;
23: }
24: }
25: }
My output for the above would be as below:
Master ASP.NET Development
MS Press
Scott Guthrie
Deep Dive Web Programming
MS Press
Scott Hanselman
ASP.NET Good Sense
MS Press
Jon Galloway
Press any key to continue . . .
Note, in the snippet above, I’ve used a pre-defined path to my XML document. The use the ReadElementString() method to get the value of the elements.
Although this approach is quick, there is a small annoyance with it. For example, what if I have a I would like to enumerate through all elements that belong to each book element? You could still achieve this but it’s gets messy, especially when you need to used the data from each book element.
The code snippet below shows you how to achieve this by using the XmlDocument class instead.
1: // Initialise and load Xml document from pre-defined path.
2: XmlDocument xml = new XmlDocument();
3: xml.Load(@"C:\Projects\ConsoleReadXML\ConsoleReadXML\Books.xml");
4:
5: // Retrieve the parent node of the document <Book>
6: XmlElement parent = xml.DocumentElement;
7: XmlNodeList children = parent.ChildNodes;
8:
9: for (int i = 0; i < children.Count; i++)
10: {
11: // Retrieve child nodes under parent
12: // as defined in xml document.
13: XmlNode title = children[i].FirstChild;
14: XmlNode publisher = title.NextSibling;
15: XmlNode author = publisher.NextSibling;
16:
17: Console.WriteLine();
18: Console.WriteLine(title.InnerText);
19: Console.WriteLine(publisher.InnerText);
20: Console.WriteLine(author.InnerText);
21: }
The output for the above will remain the same. Note however, I am looking for all elements within a parent element, in this case <Book> then listing them out. The reason I’ve used the XmlNode object is simply to keep things clean.
Why didn’t I just used NextSibling? Things would have got quite silly if I have more child elements involved. Imagine having something like this:
children[i].NextSibling.NextSibling.NextSibling.NextSibling.InnerText
You get the picture.
Happy coding.
SPField Determining a Field Type
Posted: 12/12/2011 Filed under: SharePoint | Tags: Programming, SPField Leave a comment »What if you needed to find all “People or Group” field from a particular list? The code snippet below shows you how easily.
1: using (SPSite oSite = new SPSite("http://mysitecollection"))
2: {
3: using (SPWeb oWeb = oSite.AllWebs["myweb"])
4: {
5: SPList oList = oWeb.Lists["mylist"];
6:
7: foreach (SPField oField in oList.Fields)
8: {
9: if (oField.TypeDisplayName.ToString() == "Person or Group")
10: {
11: Console.WriteLine(oField.Title);
12: Console.WriteLine();
13: }
14: }
15: }
16: }
Note the bit where I used the TypeDisplayName property, this is where I specify the field type I want, and in this case it’s “People or Group”. If I wanted the “Date and Time” field, I’ll just specify “Date and Time”.
How do I get these values? When you create a new column they are listed under Name and Type.
Hope this helps.
Understanding IsPostback
Posted: 17/11/2011 Filed under: Development | Tags: ASP.NET Leave a comment »The IsPostback is probably one of the most commonly used property in ASP.NET development.
But what is it exactly?
It is a property that belongs to the Page class under the System.Web.UI namespace. Essentially it returns a boolean value indicating if a page is being requested for the first time or if is being loaded in respond to a postback.
Please elaborate?
Well, when we talk on the web, we use the HTTP protocol. The communication or exchange of information between a client (web browser) and an application or site (web browser) is initiated when we type in a site URL or click on a hyperlink. This is known as a Request (GET), the site or application then Responds to the client. This process is known as a round-trip.
However, we the client, also interact with a site or application through the execution of a particular web control (such as a button click). This is when data is sent to the site or application, a POST is made, and this process is known as a postback.
Important! – We can send data back using a GET as well, but this is not discussed here.
So, the IsPostback property on a ASP.NET page essentially checks if the request is either a GET or POST.
Example
The code snippet below basically shows an array is bound to a drop-down list when a page loaded.
1: string arrPets = new string[] {"Dog", "Cat", "Bird", "Fish"};
2:
3: public void Page_Load(object sender, EventArgs e)
4: {
5: // The pet values from the array is not bound here.
6: // This is because the when the page is requested
7: // for the first time, it is not a postback
8: // There will be no values on the drop-down
9: // list control.
10: // =================================================
11: // COMMENTED OUT
12: //if(this.Page.IsPostback)
13: //{
14: //this.dropDownList.DataSource = arrPets;
15: //this.dropDownList.DataBind();
16: //}
17:
18: // The pet values from the array will be bound here.
19: // The values will be available on the drop-down
20: // list control.
21: // ====================================================
22: if(!this.Page.IsPostback)
23: {
24: this.drownDownList.DataSource = arrPets;
25: this.dropDownList.DataBind();
26: }
27: }
C# Saving and Retrieving Image from Database
Posted: 14/11/2011 Filed under: Programming | Tags: C# Leave a comment »This post simplifies the whole approach to saving and retrieving of images from a database. In the real-world, it is highly recommended that your application be separated into separate layers and that validation be implemented for incoming and outgoing data.
The User Interface
A simple markup for uploading the image and displaying the image.
The Database
A table to store the image using the image sql db type.
2 stored procedures, one for Inserting a new image. And another for selecting an existing image based on it’s id.
The Code
I have my database connection string stored in my web.config with the name “SampleDB”.
Saving the image to the database is performed on the Upload button click event btnUpload_Click.
1: public void btnUpload_Click(object sender, EventArgs e)
2: {
3: string conn = ConfigurationManager.ConnectionStrings["SampleDB"].ConnectionString;
4:
5: // FIRST PART:
6: // get the uploded picture into a byte[] array
7: // from the FileUpload control (photoUpload)
8: byte[] content = new byte[this.photoUpload.PostedFile.InputStream.Length];
9: this.photoUpload.PostedFile.InputStream.Read(content, 0, content.Length);
10:
11: // SECOND PART:
12: // save the byte[] into the database image type
13: using (SqlConnection dbConn = new SqlConnection(conn))
14: {
15: dbConn.Open();
16: using (SqlCommand cmd = new SqlCommand("InsertNewPhoto", dbConn))
17: {
18: cmd.CommandType = CommandType.StoredProcedure;
19: cmd.Parameters.Add("@photo", SqlDbType.Image);
20: cmd.Parameters["@photo"].Value = content;
21:
22: cmd.ExecuteNonQuery();
23: }
24: }
25: }
Retrieving the image from the database is performed on the Page_Load event through the use of a Generic HTTP Handler created Photo.ashx
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: if (!this.Page.IsPostBack)
4: {
5: this.photoImage.ImageUrl = "Photo.ashx";
6: }
7: }
ProcessRequest method modified on the Photo.ashx Generic HTTP Handler.
1: public void ProcessRequest(HttpContext context)
2: {
3: // REAL WORLD:
4: // Retrieve an id that has been passed into a querystring.
5: // the id is then passed to the database to retrieve the relevant
6: // photo.
7:
8:
9: // This example passes in just the one particular value all the time.
10: byte[] content = null;
11: context.Response.ContentType = "image/jpeg";
12: context.Response.Clear();
13:
14: string conn = ConfigurationManager.ConnectionStrings["SampleDB"].ConnectionString;
15:
16: using (SqlConnection dbConn = new SqlConnection(conn))
17: {
18: dbConn.Open();
19: using (SqlCommand cmd = new SqlCommand("SelectPhotoById", dbConn))
20: {
21: cmd.CommandType = CommandType.StoredProcedure;
22: cmd.Parameters.Add("@photoId", SqlDbType.Int);
23: cmd.Parameters["@photoId"].Value = 1; // constant value being passed in
24:
25: using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SingleResult))
26: {
27: while (rdr.Read())
28: {
29: content = (byte[])rdr["Photo"];
30: }
31: }
32:
33: }
34: }
35:
36: context.Response.BinaryWrite(content);
37:
38: }
Easy Progress Indicator using jQuery
Posted: 11/11/2011 Filed under: Development | Tags: jQuery Leave a comment »This is a truly simplified approach to providing end-users with an indicator that an operation is in progress.
The page markup:
The script: