Archive for the ‘Uncategorized’ Category

WCF (Windows Communication Foundation)

WCF, a feature of .NET 3.5, has simplified the method of creating web services by providing an alternative to the Interface Contract method. The alternative method involves the application of the Service Contract Attribute to the class as well as Operation Contract Attribute to each of the methods to be exposed by the Service Component.

The following is an example Class made available via WCF declared using Service & Operation Contract attributes.

<%@ ServiceHost Language="C#" Service="TS.ToplineService" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using TS.ModelTypes;

namespace TS
{
    [ServiceContract(Namespace = "http://www.toplinestrategies.com/wcf")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ToplineService
    {
        [OperationContract]
        [WebInvoke(ResponseFormat = WebMessageFormat.Json)]
        public Person GetEmployeeInfo(int empNum)
        {
            Person result = new Person();

            Person employeeA = new Person();
            employeeA.Id = 1;
            employeeA.Name = "Daniel";
            employeeA.Experience.Add("MS CRM 2 Yrs");
            employeeA.Experience.Add("LINQ 1 Yr");
            employeeA.Experience.Add("C# 3 Yrs");
            employeeA.Experience.Add("VB 2 Yrs");

            Person employeeB = new Person();
            employeeB.Id = 2;
            employeeB.Name = "Siva";
            employeeB.Experience.Add("MS CRM 5 Yrs");
            employeeB.Experience.Add("C# 2 Yrs");
            employeeB.Experience.Add("VB 2 Yrs");

            Person employeeC = new Person();
            employeeC.Id = 3;
            employeeC.Name = "Anuj";
            employeeC.Experience.Add("PMP 10 Yrs");
            employeeC.Experience.Add("BA 5 Yrs");

            switch (empNum)
            {
                case 0:
                case 1:
                    result = employeeA;
                    break;
                case 2:
                    result = employeeB;
                    break;
                case 3:
                default:
                    result = employeeC;
                    break;
            }

            return result;
        }
    }
}

 
Classes not encapsulated within the service must include the Data Contract attribute, and fields must adopt the Data Member attribute.

using System.Collections.Generic;
using System.Runtime.Serialization;
namespace TS.ModelTypes
{
    [DataContract]
    public class Person
    {
        private List<string> _experience = new List<string>();
        [DataMember] public int Id { get; set; }
        [DataMember] public string Name { get; set; }
        [DataMember]
        public List<string> Experience
        {
            get { return _experience; }
            set { _experience = value; }
        }
    }
}

Below is the code to call the WCF service via JavaScript/AJAX.

    <script type="text/javascript">
        function onGetEmpDetail() {
            var empNum = $get("txtWCF").value;

            // Web Service Call
            www.toplinestrategies.com.wcf.ToplineService.GetEmployeeInfo(empNum, onSucess, onFailed);
        }
        function onSucess(result) {
            var experience = "";
            for (var i = 0; i < result.Experience.length; i++) {
                experience += result.Experience[i] + "<br>";
            }
            $get("resultsDiv").innerHTML = "Employee Detail" + "<br>"
                                                + "Name: " + result.Name + "<br>"
                                                + "Experience: " + experience;
        }
        function onFailed(err) {
            alert('Some error has occured: ' + err.get_message());
        }
    </script>

The attached code is an example of WCF in action which compares the use of an update panel to JavaScript & WCF to interact with the server.

TLS_WCF

Tags: , ,


Sort a Generic List

A few months ago one of my coworkers wrote about Generic list. Ever since, we have not talked about it so that’s why I’ve decided to write about Generic lists and how to sort them using Lambda expressions, Linq or IComparable Interface.

First of all, a small definition: According to Microsoft “[The] List Class represents a strongly typed list of objects that can be accessed by index”. In essence we can store any variable type or object on a list.
The lists are flexible because you can use them as objects or regular arrays. You can use Sort, ForEach, Find, Contains, Remove or any other method listed on the list Class. You can implement interfaces and most of it with “one” line of code.

In order to demonstrate how powerful a List can be, let’s take a look at the code below.
The first thing we have to do is create a Class so, we can use it with the list.

//Note that the Class implements the IComparable Interface.
//We need that interface to sort the list. I will show how later.
public class Employee : IComparable
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public double WorkedHours { get; set; }
	public double payRate { get; set; }

//Class constructor
	public Employee(string name, string last, double wh, double pR)
	{

		this.FirstName = name;
		this.LastName = last;
		this.payRate = pR;
		WorkedHours = wh;
	}

	public double Salary()
	{
		return WorkedHours * payRate;
	}

//The Sort method of the list will call this method.
	int IComparable.CompareTo(Employee other)
	{
		int value;
		value = this.FirstName.CompareTo(other.FirstName);
		return value;
	}
}

Now that we already have our base Class created, let’s make this a little bit more interesting.
Let’s create another Class called Employees. Employees Class will inherit from Employee.
It will have a property called “employeeList” which is going to be our List of employees.


public class Employees : Employee
{
	public List employeeList { get; set; }

//The constructor is instantiating the list.
	public Employees()
	{
		this.employeeList = new List();
	}

//This can return a list or void. It is up to you what to return
	public void SortICompare()
	{
        //The Sort calls the IComparable Interface written on the base class.
        //The inheritance from IComparable on base makes this possible.
		employeeList.Sort();
	}

//Version using Lambda expressions. The code inside the sort parentheses
//compares the names and returns their relative position in the list.
	public void SortLambda()
	{
		employeeList.Sort((e1, e2) =>
						   string.Compare(e1.FirstName, e2.FirstName));
	}

//Here we are sorting the list using Linq.
//Look how easy it is using "Orderby".
//However it requires re-assign the result back to the original list.
	public void SortLinq()
	{
	    var empList = from emp in employeeList
                      orderby emp.FirstName select emp;
	    employeeList = empList.ToList();
	}

This last Method is an “extra” method I created to show how useful a list can be. Basically it sorts the list comparing 3 different elements, FirstName, Last Name and Salary. It is using FirstName as the first element compared, if the names are the same then it will compare LastName as a second element and Salary as 3rd.

Note that the code here is really only 1 line of code. Something interesting is that Salary is not a property, it is a Method which returns an Int value. Also, I’m not using an IF statement to evaluate the condition however, I’m using a conditional operator “?:” you can find more information about it clicking here

	public void SortNameLastSalary()
	{

	   employeeList.Sort((emp1, emp2) =>
                        emp1.FirstName.CompareTo(emp2.FirstName) == 0 ?
                        (emp1.LastName.CompareTo(emp2.LastName) == 0 ? emp1.Salary().CompareTo(emp2.Salary())
                        :emp1.LastName.CompareTo(emp2.LastName)) : emp1.FirstName.CompareTo(emp2.FirstName));
	}
}

The last part would create the object and run the code from the UI. However, I think you can handle that. Nevertheless, if you need any help I invite you to reply back. I will be glad to respond as soon as possible.

If you need more information about:
Lambda Expressions click Here
Linq click Here
ICompare Interface click Here
Delegates click Here

Tags: , , , , , , , , , , , , ,


Date Comparison Methods

A few days ago, I was asked to look into one of the biggest stored procedures we have here at work.

It copies the information from the main database, storing it into the archive database, according to the dates in which the data was originally stored.
But I better not say anymore, otherwise this could be my last blog.

However, I will risk a little for the benefit of the blog.
On top of all the private and ultra-secret commands, the stored procedure is comparing dates. Something I noticed is that it was doing the dates comparison in different ways along the whole SProc.

That made me think, what would be a good method to compare the database Dates against the data that the Sproc receives? Would the data be well formatted always? These questions led me to decide the topic for my blog.

So let’s start, in order to create our first comparison, we will need a fake table. Our table can be something such as:


Create Table #CompareTable
(CompareID   int pk
 ,Description varchar (20)
 ,StartDate   datetime
 ,EndDate     datetime
 ,Notes       varchar (10)
)

Now, let’s say that we need to retrieve CompareID and Description for all the StartDates between 01/01/2010 and 12/31/2010. The most logical way to do it would be:

Select CompareId, Description
From #CompareTable
Where StartDate between '01/01/2010' and '12/31/2010'

We have to remember that “between” is an inclusive expression in TSQL, that means that it will return True if the value of StartDate is greater or equal than ’01/01/2010′, and less than or equal to ’12/31/2010′.

In order to avoid the inclusion when we are searching for a specific date range, we will have to use the “<” less than and the “>” greater than operators. These operators are not inclusive so, you can use them to do your search more efficiently.

Something else done on the previous search is that we are using a date on mm/dd/yyyy format which is basically a string. There are better ways to do that comparison. But would it happen if we received the string quite differently?

In order to prevent that, lets continue with the following example: Now, I would like to see all the CompareIDs, Descriptions and notes, when the start date is not less than ’01/01/2010′ and the end date is not older than ’04/15/2010′. In order to retrieve the data I would type something like this:

Select CompareID, Description, Notes
From #CompareTable
Where Cast(convert(varchar(10), StartDate,101) as datetime) =>
         Cast( convert (varchar(10), '01/01/2010', 101) as datetime)
And Cast( convert(varchar(10), EndDate ,101)as datetime) =<
      Cast( convert (varchar(10), '04/15/2010', 101) as datetime)

In the previous example we are not assuming anything, the use of Convert and Cast functions working together in the same statement can be very powerful. They can even be used for many different purposes, in this case we use them to give format to the values and then casting it back to Datetime.

Let’s analyze the statement for a moment.

The CONVERT() function is a general function for converting data into a new data type. The convert function can return the values on a specific format. In my previous example, I use 101 format which is USA standard. The output would be ‘mm/dd/yyyy’. You can use any one of those, but take into consideration that you should use the same at each side of the comparison.

For more information about how it works you can visit Microsoft MSDN website

The CAST() function converts data from one data type to another. It is supported inside functions that support expressions including aggregate functions. CAST() also takes general expressions including nested functions as input.

When you are pulling information out of a table and you are comparing that against a specific format, you should convert those values to the same format. That “data manipulation” would make a better statement; it would return more accurate information as well.

Remember that neither the Cast nor the Convert functions change the data, just the format and the type of the output that the SQL engine would analyze.

One can avoid a lot of headaches by using Cast() and Convert() together.

Even when application code allows you to perform culture-sensitive operation on datetime types, you shouldn’t assume that every developer is going to send you the data, using the same format found on the database. We as SQL developers cannot trust in our application developer friends. (My co-workers may hit me after that).

Everything we have discussed here have been all suggestions, the way in which you decide to apply these concepts is strictly up to you.
As always , there many other ways to do date comparison. I hope you can find the best way to do your statements.

Some other website you can visit are:
SQL Helper


ACID Rules

A few days ago, I had to look for some information regarding the ACID rules and I didn’t really find anything relevant that helped me understand the topic very well. I even checked many SQL Books because I thought I would be able to find good information in them, but even though they were supposed to be “good books” , I still found nothing good . So I decided to put together all the information I found and a little bit about the topic.

First of all we need to understand what the letters A.C.I.D. stand for and what the idea behind it is. The A.C.I.D. letters stand for atomicity, consistency, isolation and durability. The meaning of those words will be discussed with more detail in order to have a better understanding and give us a better idea of the topic as a whole.

Atomicity

When we deal with data, we want to be sure that if one thing is happening, another thing will happen as well. In other words atomicity means that something has to happen or nothing will happen at all.

To illustrate the principle of Atomicity, imagine writing an Insert statement. If you have not written any yet, you can do it by typing something like this:

 INSERT INTO table_name
 VALUES (value1, value2, value3,...)

The statement would insert the values in the database. But let’s also imagine that the Server has a problem and at that precise moment something unexpected happened? Would we lose the information? Would the system crash cause the data to be damaged or lost? In order to follow the principle of atomicity, the database engine would never insert that information into the table. Therefore the information that the table had, before you ran the insert, would remain intact and none of the changes would have taken place. That serves the Atomicity principle.

Another option to prevent those problems and to follow the Atomicity principle correctly, the database engines have some features such as Transaction Management, Locks and Concurrency.

Consistency

This may be the most important principle of the ACID model. As we know, the data has to be consistent. Every time we run a transaction on the data base, the data may change. If that happens, the data has to transform from one consistent state of data into another consistent state of data. If something happens that breaks down the principle, the transaction has to be rolled back. How Data Base engines roll back transactions is another topic that we may explore some other day however I think it’s fair enough to mention that we can also control how the Data base server rolls back the transactions.

Let’s remember that Rollback basically goes back to the last committed transaction known by the data base. It restores that information on the rows affected by the update that failed. This behavior provides consistency and atomicity to the data.

Isolated

To better explain this term, let us imagine that we have a busy data base server receiving multiple transactions on the same table. Those transactions could be affecting one or multiple records. The ability to keep those transactions separated one from another and the data consistent is what we call Isolated. In other words, this term requires that multiple transactions occur at the same time and not impact each other’s execution. This is something that we have to take into consideration especially from the Data Base Administration point of view.

To avoid that from happening, SQL server uses a locking mechanism. This mechanism arbitrates when a process is allowed to modify data as well as insuring the read are consistent. Locks occur at three different levels and there are three different types. They can be applied in a row, page or table level.

Durability

This is the last topic of the ACID model but not less important than the others. When we talk about durability we are not necessarily saying that the information will last forever but the concept means that we have to ensure that the data will remain safe and it won’t be lost even if the server crashes. In order to prevent loss of data, we have to keep backups and transaction logs. They will facilitate the data restoration.

There is no doubt that all the other terms ensure the durability of the data, however we haven’t thought about external problems and situations that the Data base can’t control, such as server crashes or unexpected shut downs. In order to prevent those problems, the data bases provide many different tools to provide durability. The most common way to do this is by doing backups.

There are many different solutions we can currently find. It really doesn’t matter what you implement, the important thing is that you implement some kind of backup.

Tags: , , , , , , , , , ,


LINQ to SQL Connection Strings

Like many developers, after reading several articles on the wonders of LINQ to SQL, I decided to incorporate it into the next project I did.  During the development phase, everything went very well.  I separated each layer of my solution into its own project and when it came time to define my business objects, I created a new .dbml file, opened a connection to my database and dragged the tables I wanted to use onto the designer screen as seen below.

dbml_file

I also added a connection string to the web.config file of my web project, but after the initial setup, I did not give a second thought to how it was that my data layer was connecting to the database.  In all the LINQ to SQL tutorials that I read, all that was necessary to connect to the database was to define a new data context and then use it like so.

public static tbl_page Page_GetByPageID(int pageID)

{

PageDataContext db = new PageDataContext();

var page = from p in db.tbl_pages

where p.PageID == pageID

select p;

What I did not realize, was that Visual Studio had taken the connection string directly from my server explorer and saved it into a file called “app.config” in my Object Model project.  When the solution was compiled, that connection string information was stored directly in the .dll and could not be changed.  As long as I was still working in development and querying the same database this was not an issue, however, when the first deployment was made to a remote production server, all of a sudden the project could not connect to the database specified in the web.config file of my web project.

To compound the problem, the error generated by SQL Server did not seem to point to an incorrect connection string, but instead indicated that there was some issue with the SQL Server installation itself.  The exact error was:

An error has occurred while establishing a connection to the server.  When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server)

Once the project was installed on the remote server, I actually spent a good deal of time trying to troubleshoot issues with SQL Server settings rather than looking at the source of my connection string.  When I finally did realize that my project was still trying to connect to the local database on my laptop, I spent another couple of hours trying to figure out what to do with LINQ to SQL since it, from what I could tell, had stored the local connection string in the code without any intervention from me.

The answer proved to be quite simple in the end.  I read a couple of different blog posts like this one from Rick Strahl and this one from Graham O’Neale.  Both of these posts recommended removing the connection string from the properties of the .dbml file as well as setting the “Application Settings” property to false shown here:

PreviewPane_file

This step is necessary to get the connection string out of your .dll’s and into the config file where it belongs, but their other recommendations dealt with making manual code changes to the datacontext constructor or the designer class of the .dbml file.  While both of those suggestions work, from what I can see, any such manual changes would be overwritten the next time you have to make a database change during development, which would require you to recode the manual changes each time the .dbml file changes.

Not wanting to have to have to recode any such changes every time the .dbml file changed, I kept looking for another solution and I found my answer by mistake.  After removing the connection string and setting “Application Settings” to false, I tried to compile my project and found that the data layer was giving me an error for each data context constructor that I tried to initialize.  The error said:

PageDataContext(string Connection)

Error:

‘PageDataContext’ does not contain a constructor that takes ‘0’ arguments

Clearly, now that no connection was hard coded into the .dbml file by the designer, it was wanting a connection string to be passed in when the data context was initialized.  I thought that would certainly be easy enough to do, so I defined a public variable at the top of each data layer class like so:

public static string conn = ConfigurationManager.ConnectionStrings["myConnectionString"].ToString();

which of course points to the connection string in the web.config file of my web project and I changed each initialization of the data context object to use the new variable as follows:

PageDataContext db = new PageDataContext(conn);

Once that was done, everything compiled and worked like a charm both locally and on the remote server.  What I like about this also, is that I didn’t need to make any changes to base constructors or designer files of any of my object model classes.  (NOTE: In fairness to Rick, he mentioned doing this in the comments section of his post.  In my frustration, I just didn’t catch it the first time).

This is the type of thing that you only need to figure out once, but if you are trying to implement a LINQ to SQL project for the first time, it can be a very perplexing issue.  Most of the LINQ to SQL tutorials I read understandably focus on getting things up and running in your development environment, without a lot said about deployment.  If you are experiencing this issue, I hope this post saves you some and frustration.