What are Extension Methods?
Extension methods allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performace and compile-time validation of strongly-typed languages. This is a cool feature of C# 3.0
Extension Method Example:
Lets say you want to check if a variable string is a valid telephone number. In this example, our valid telephone number must start with a zero and followed by 9 more digits or start with a zero followed by two digits a space three digits a space and four digits (0787845122 or 078 784 5122). You would normally implement this by calling a separate class (most likely a static method) to check to see whether the string is valid, for instance:
string telephone = txtTelephone.Text;
if ( MyValidator.IsValidTelephone(telephone) ) {
}
Now using extension method, i can add a useful IsValidTelephone() method onto the string itself, which returns whether the string instance is a valid string or not. I can then re-write the above code to be cleaner and more informative like:
Note that the static method above has a "this" keyword before the first parameter argument of type string. This tells the compiler that this particular Extension method should be added to objects of type "string". Within the IsValidTelephone() method implementation i can then access all of the public properties/methods/events of the actual string instance that the method is being called on, and return true/false depending on whether it is a valid telephone or not.
Hope you enjoyed this post, will add some example in the next post.
As a software developer, I encounter different challenges and resolve them the best way I can. This is my experience I want to share with other hackers so that we can help each other. Hope to contribute and to learn from the hacker's community.
Thursday, 29 September 2011
Thursday, 15 September 2011
Linq equivalent to SQL Select Count and Group by
In this post i want to show you how you can do a select count and group by using LINQ that is equivalent to SQL's.
We have our object Student and we are going to create a list of Students. Now we want to return a list of Students who are in a certain Class and the number of Students in that Class. To do that we are going to use the GroupBy method and use a lambda expression to return the group of Students in a Class as a list. From the list we can then select the Class name and the Count. Take note that I used an anonymous type in the Select method.
Now if we want to group by more than one field, for instance, Subject in this case here is how we can do it:
Results:
Hope you found this post useful. Like to hear from you for suggestions or questions.
We have our object Student and we are going to create a list of Students. Now we want to return a list of Students who are in a certain Class and the number of Students in that Class. To do that we are going to use the GroupBy method and use a lambda expression to return the group of Students in a Class as a list. From the list we can then select the Class name and the Count. Take note that I used an anonymous type in the Select method.
Now if we want to group by more than one field, for instance, Subject in this case here is how we can do it:
Results:
Hope you found this post useful. Like to hear from you for suggestions or questions.
What are lambda expressions
In this post i want to talk about lambda expressions. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, which is read as "goes to". In other words, lambda expression can be broken down into parameters followed by execution code:
Parameter => executioncode.
The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block. The lambda expression x=> x * x is read " x goes to x times x". In other words we want to square any given number and to do this we are going to assign to a delegate type as follows:
Result: The square of 5 is 25.
The => operator has the same precedence as assignment (=) and is right-associative.
Lambdas can be used in method-based LINQ queries as arguments to standard query operator methods such as Where. Let us look at the following pratical example:
I have my object Person that i can model into a list of anything that represents a person, for instance, in this case i have modeled it to give me a list of Students. Now that we have our Students, we can go ahead and filter the Students by their Age, in this example i want to return teenagers or independents.
Both "getTeenagers()" and "getIndependents()" uses a lambda expression as a predicate to compare each Student's Age and return a new collection of Students in their respective Age group.
For more on Lambda expressions you can read this article.
Parameter => executioncode.
The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block. The lambda expression x=> x * x is read " x goes to x times x". In other words we want to square any given number and to do this we are going to assign to a delegate type as follows:
Result: The square of 5 is 25.
The => operator has the same precedence as assignment (=) and is right-associative.
Lambdas can be used in method-based LINQ queries as arguments to standard query operator methods such as Where. Let us look at the following pratical example:
I have my object Person that i can model into a list of anything that represents a person, for instance, in this case i have modeled it to give me a list of Students. Now that we have our Students, we can go ahead and filter the Students by their Age, in this example i want to return teenagers or independents.
Both "getTeenagers()" and "getIndependents()" uses a lambda expression as a predicate to compare each Student's Age and return a new collection of Students in their respective Age group.
For more on Lambda expressions you can read this article.
Thursday, 1 September 2011
How to get a SharePoint list using SharePoint object model
In this post i want to discuss how you can get a SharePoint list using SharePoint object model. To do this make sure you have SharePoint installed on your PC. Now create a new console project in Visual Studio 2010. Make sure that the platform target for your project is 64 bit and that you added the SharePoint dll as a reference.
Now, i have already added a custom list to my site and it is called My List. It has two columns, Name and Surname. So this is just a small list of random Names and Surnames.
If you are done with your list, lets get the same list and display it from the Console application.
If you run the code you will get the list you just created from SharePoint.
So this how you can simply get a SharePoint list using SharePoint object model.
Now, i have already added a custom list to my site and it is called My List. It has two columns, Name and Surname. So this is just a small list of random Names and Surnames.
If you are done with your list, lets get the same list and display it from the Console application.
If you run the code you will get the list you just created from SharePoint.
So this how you can simply get a SharePoint list using SharePoint object model.
Thursday, 25 August 2011
How you can log errors Part 1
In this post, which is in two parts, i would like to discuss about ways you can handle and log errors. It is really important to think about the strategy you are going to use to handle errors at an early stage. Why? Let us take a look at a simple example:
This is a simple try catch statement whereby the error is shown in a message box. If the application start to grow and there has't been a proper infrastucture layed out on how to cater for errors, there is going to be a lot of try catch statements as the one above, hence there will be a lot of duplication. You are going to need help with the project, and you are going to employ other developers to help. There are higher chances that the developers are going to employ their own ways of handling the errors and hence there is going to be inconsistency as far as handling errors is concerned.
From the above example, there is an important piece of information that is missing, the stack trace. It is not advisable to show the whole error to the user, but there should be a way of logging the error details so that it will be easy to trace the error, maybe to log to a file or send an email. Hence if you don't plan ahead there can be information loss concerning bugs that can occurr within the application. It is, therefore, important to plan on how you are going to handle errors at an early stage of development due to the facts i mentioned and others that you might have come across.
How can i handle errors?
There are different ways you can handle errors depending with the development environment you are in. But as you plan on how you are going to do it, one thing you must bear in mind is that it must be easy for maintenance, to use and to configure. Here are some of the tools you can use depending with your needs:
This is a simple try catch statement whereby the error is shown in a message box. If the application start to grow and there has't been a proper infrastucture layed out on how to cater for errors, there is going to be a lot of try catch statements as the one above, hence there will be a lot of duplication. You are going to need help with the project, and you are going to employ other developers to help. There are higher chances that the developers are going to employ their own ways of handling the errors and hence there is going to be inconsistency as far as handling errors is concerned.
From the above example, there is an important piece of information that is missing, the stack trace. It is not advisable to show the whole error to the user, but there should be a way of logging the error details so that it will be easy to trace the error, maybe to log to a file or send an email. Hence if you don't plan ahead there can be information loss concerning bugs that can occurr within the application. It is, therefore, important to plan on how you are going to handle errors at an early stage of development due to the facts i mentioned and others that you might have come across.
How can i handle errors?
There are different ways you can handle errors depending with the development environment you are in. But as you plan on how you are going to do it, one thing you must bear in mind is that it must be easy for maintenance, to use and to configure. Here are some of the tools you can use depending with your needs:
- Trace.axd
- Log4net - logging.apache.org/log4net/index.html
- ELMAH - code.google.com/p/elmah/
- PostSharp - www.postsharp.org
Apart, from these tools, you can create your own custom error handling tool or library. I personally have used Log4net. It is easy to configure and there is support for it from the community, though it is now looking like there aren't any upgrades being done. However, despite that fact, you have a wide range of tools to choose from that you can use to handle you errors.
Therefore, as you plan your architecture, you might want to consider which tool you can use that can complement with what you want to achieve. For instance, apart from, showing friendly errors to users, you might want to receive emails concerning critical operations that might have failed to execute, and that they would need your immediate attention. In this case, i would go for Log4net as an example.
If you have used any one of the tools that i have mentioned, i would like to hear about your experience. Or if you have used another tool apart from these ones, please do share. In the next part, i will go ahead and show you how you can address the problems that i mentioned earlier on if you don't plan on handling errors.
Tuesday, 16 August 2011
How do JavaScript Closurers Work
Closure
A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after that function has returned. A closure is a special kind of object that combines two things:
- · A function
- · A local variable that is in scope at the time that the closure was created.
In other words a closure is the local variables for a function kept alive after the function has returned or a closure is a stack-frame which is not deallocated when the function returns.
For instance:
function myFullName(){
var firstname = “Tendai”;
function getName(){
alert(firstname);
}
getName();
}
myFullName();
The function myFullName() creates a local variable called firstname, and then defines a function called getName(). Function getName() is an inner function – it is defined inside myFullName, and is only available within the body of that function. As you can see, the function getName() has no local variables of its own, but reuses the name variable declared in the outer function, myFullName().
If you run the code, you are going to notice that it is going to show ‘Tendai’. This is an example of functional scoping, whereby the scope variable is defined by its location within the source code, and the nested functions have access to variables declared in their outer scope.
Let us look at another example:
function myFullName(){
var firstname =”Tendai”;
function getName(){
alert(firstname);
}
return getName;
}
var myName = myFullName();
myName();
This code will have the same result as before. The difference here is that, getName() is an inner function that was returned from the outer function before being executed. Under normal circumstances the local variables within a function only exist for the duration of that function’s execution. Once myFullName() has finished executing, it is reasonable to expect that the firstname variable will no longer be necessary, which is not the case here.
The reason behind this is that myName has become a closure. Remember that a closure combines two things:
myName is a closure that incorporates both the getName function and the local variable, string “Tendai”, that was in scope at the time the closure was created.
Now the complete example:
function myFullName(firstname){
return function(surname){
return firstname + surname;
};
}
var myFullNameTendai =myFullName(‘Tendai’);
var myFullNamePeter =myFullName(‘Peter’);
print(myFullNameTendai (‘Bepete’)); // Tendai Bepete
print(myFullNamePeter (‘Jacobs’));// Peter Jacobs
Here, the function myFullName(firstname) takes a single argument firstname and returns a new function. The function it returns takes a single argument surname, and returns a concatenation of firstname and surname.
Both myFullNameTendai and myFullNamePeter are closures. They share the same function body definition, but store different environments. In myFullNameTendai’s environment, firstname is Tendai and that in myFullNamePeter it is Peter.
Both myFullNameTendai and myFullNamePeter are closures. They share the same function body definition, but store different environments. In myFullNameTendai’s environment, firstname is Tendai and that in myFullNamePeter it is Peter.
Hope after reading this you had a better understanding on what closurers are and how they work. For further reading you can read this article.
Wednesday, 10 August 2011
How to do an Ajax post with client side validation using JQuery
In this post I want to explain how to do an Ajax post with client side validation using JQuery. The idea here is to have an object that can validate itself and once it is valid the data is sent through to the server.
JQuery Syntax for Ajax Post
The syntax for doing an Ajax post is fairly easy to understand and it is as follows:
$.post(url,data,success,dataType)
Issue to be resolved
Now assuming that you want to register a person and you only have three fields, Name; SecondName and Surname. And that the only required fields are Name and Surname. The expected outcome is as follows:
If not valid:
If valid:
Html:
<div id="result">
</div>
<form id="frmAdd" class="frmAdd" action="">
<div>
<label id="lblName">Name</label><br />
<input type="text" id="Name" class="data required" /></div>
<div>
<label id="lblSecondName">SecondName</label><br />
<input type="text" id="SecondName" class="data" /></div>
<div>
<label id="lblSurname">Surname</label><br />
<input type="text" id="Surname" class="data required" /></div>
<input type="button" id="btnAddPerson" value="Add Person" />
</form>
Now take note that for the inputs, i have two classes, data and required. Data is to get the data that needs to be sent through and required is to mark the fields that need to be filled in.
Data object
The first part of my data object is the data itself that is going to be sent through and its properties. Take note that the names of the properties are identical to the input fields id that have class data.
var myObject = {
// data to be sent
data: {
Name: "",
SecondName: "",
Surname: ""
},
The second part of the object is to reset if there were any errors that were flagged
// removes any errors
reset: function () {
$(".error").remove();
},
The third part is to assign the data's properties with values from the input fields will the class data.
assign: function ($element) {
//get the element id
var id = $element.attr("id");
// match the property with the element
for (var prop in myObject.data) {
if (myObject.data.hasOwnProperty(prop) && prop === id) {
// get the value and assign it to the property
myObject.data[prop] = $element.val();
return false;
}
}
},
The last part is the validation. Take note that the first call is to reset, that is, remove any errors that were flagged so that if there errors persist they can be shown else there are no errors to flag.
valid: function () {
myObject.reset();
var valid = true;
// validate
if ($("input.required").length) {
$(".required").each(function (index, obj) {
if ($(this).val() === "") {
$(this).parent().append("<span style='color:red;' class='error'>This is a required field</span>");
valid = false;
}
});
}
// assign
if ($("input.data").length) {
$(".data").each(function (index, obj) {
myObject.assign($(this));
});
}
return valid;
}
};
Now the last part is the event itself when a user clicks the button AddPerson.
$("#btnAddPerson").click(function (e) {
e.preventDefault();
if (myObject.valid()) {
$.post(
"ajax-calls.aspx", url
myObject.data, data
function (data) { success
if (data.success) {
$("#result").append("<span style='color:green;' class='error'>Person added successfully</span>");
} else {
$("#result").append("<span style='color:red;' class='error'>Person wasn't added successfully</span>");
}
},'json' dataType
);
};
});
Take note that i have highlighted the parts that makes up the syntax used to do an Ajax post, that we discussed in the first part of this article, in red. Therefore, before we do the Ajax post, the data must be valid first and if it is valid then the data is sent through.
One thing that i like about this method is that, if for instance the username or password are fields that need to be added and are also required fields, all you have to do is modify the html and add the username and passwords to the data as properties and you are done. And you can also go ahead and add more functionality to validate if the data sent is of the right type on the client side.
I hope this will be useful to those who enjoy playing around with jquery. Any comments and suggestions are welcomed.
JQuery Syntax for Ajax Post
The syntax for doing an Ajax post is fairly easy to understand and it is as follows:
$.post(url,data,success,dataType)
- The url is the URL to which the request is sent.
- Data is the information that is sent to the server with the request.
- Success is a callback function that is executed if the request succeeds.
- DataType is the type of data expected from the server and it can be either xml, json, script or html.
Issue to be resolved
Now assuming that you want to register a person and you only have three fields, Name; SecondName and Surname. And that the only required fields are Name and Surname. The expected outcome is as follows:
If not valid:
If valid:
Html:
<div id="result">
</div>
<form id="frmAdd" class="frmAdd" action="">
<div>
<label id="lblName">Name</label><br />
<input type="text" id="Name" class="data required" /></div>
<div>
<label id="lblSecondName">SecondName</label><br />
<input type="text" id="SecondName" class="data" /></div>
<div>
<label id="lblSurname">Surname</label><br />
<input type="text" id="Surname" class="data required" /></div>
<input type="button" id="btnAddPerson" value="Add Person" />
</form>
Now take note that for the inputs, i have two classes, data and required. Data is to get the data that needs to be sent through and required is to mark the fields that need to be filled in.
Data object
The first part of my data object is the data itself that is going to be sent through and its properties. Take note that the names of the properties are identical to the input fields id that have class data.
var myObject = {
// data to be sent
data: {
Name: "",
SecondName: "",
Surname: ""
},
The second part of the object is to reset if there were any errors that were flagged
// removes any errors
reset: function () {
$(".error").remove();
},
The third part is to assign the data's properties with values from the input fields will the class data.
assign: function ($element) {
//get the element id
var id = $element.attr("id");
// match the property with the element
for (var prop in myObject.data) {
if (myObject.data.hasOwnProperty(prop) && prop === id) {
// get the value and assign it to the property
myObject.data[prop] = $element.val();
return false;
}
}
},
The last part is the validation. Take note that the first call is to reset, that is, remove any errors that were flagged so that if there errors persist they can be shown else there are no errors to flag.
valid: function () {
myObject.reset();
var valid = true;
// validate
if ($("input.required").length) {
$(".required").each(function (index, obj) {
if ($(this).val() === "") {
$(this).parent().append("<span style='color:red;' class='error'>This is a required field</span>");
valid = false;
}
});
}
// assign
if ($("input.data").length) {
$(".data").each(function (index, obj) {
myObject.assign($(this));
});
}
return valid;
}
};
Now the last part is the event itself when a user clicks the button AddPerson.
$("#btnAddPerson").click(function (e) {
e.preventDefault();
if (myObject.valid()) {
$.post(
"ajax-calls.aspx", url
myObject.data, data
function (data) { success
if (data.success) {
$("#result").append("<span style='color:green;' class='error'>Person added successfully</span>");
} else {
$("#result").append("<span style='color:red;' class='error'>Person wasn't added successfully</span>");
}
},'json' dataType
);
};
});
Take note that i have highlighted the parts that makes up the syntax used to do an Ajax post, that we discussed in the first part of this article, in red. Therefore, before we do the Ajax post, the data must be valid first and if it is valid then the data is sent through.
One thing that i like about this method is that, if for instance the username or password are fields that need to be added and are also required fields, all you have to do is modify the html and add the username and passwords to the data as properties and you are done. And you can also go ahead and add more functionality to validate if the data sent is of the right type on the client side.
I hope this will be useful to those who enjoy playing around with jquery. Any comments and suggestions are welcomed.
Subscribe to:
Posts (Atom)