Δημοσιεύτηκε στις Τρίτη, 11 Μαρτίου 2014 9:55 μμ από το μέλος k badas :: 0 σχόλια

Value And Reference types

Introduction

 
Every variable created in a .Net application can be either of value or reference type. C#'s value type consist of most basic types such as all numeric types, bools, enums and structs. All other types, such as strings, classes, interfaces etc, are reference types. At first you may guess that value types are simpler than reference types. A class for example can be much more complex than an integer. You may be right. However the actual reason we use this division, is the way such value types are copied, as well as the way they are stored in memory. Let's take a look at the memory part first.
 
 
Memory allocation
 
Supposing we declare an integer.
 
int ValueTypeInteger = 0;
 
What would we need to store its value? Just a single slot in memory where we will store 0 (and the variable's name). Now what if we had a class like this?
 
 
class ReferenceTypeClass
//Random class containing integer value
{
    int _ReferenceTypeClass_Int;
    public int ReferenceTypeClass_Int                 
    {
        get { return _ReferenceTypeClass_Int; }
        set { _ReferenceTypeClass_Int = value; }
    }
}
 
The obvious answer, one slot, would be incorrect. What would happen if a class contained additional classes? That would make things much more complex and difficult to handle. Instead, programming architects have come up with the idea of using a different way to store types. Value types are stored in the stack and reference types are stored in the heap.
 
Stack is simply a stack, a part of the memory which we handle like a LIFO data structure. When we create a value type variable, a part of the stack-memory is fetched in order to store its value. When we create the next variable, the following part is fetched. Remember, the stack is just a stack. Our variables will look somewhat like this.
 
int int1 = 0;
int int2 = 1;
 
View stack.jpeg in slide show
 
The stack can contain no more the 1MB of info. This may seem enough to store thousands of values containing a few bytes of info. But what if there was a class containing other classes? Or what would you do if a simple  string had to fit more than 1MB of info?
 
As a result, the heap was created. The heap is a location in the memory where we store reference types. Actually, there may be occasions where we store value types in the heap as well (for example when a class contains value types), but this is not how it usually works.
 
ReferenceTypeClass object1= new ReferenceTypeClass();
 
To store an object in the heap we would first have to create a reference in the stack, pointing to the heap. In other words, when we create an instance of the class, a place in the stack is used as a guide to the location of the heap where the values of the class are stored. A look in the following image will make things much clearer.

 
When a reference type object is created, a reference is created in the stack. When it is initialized the object is placed in the heap.
 
When the method called is done,  the stack will be released of its unwanted piece of information. On the other hand, the heap will be cleared and organized later on by the garbage collector.
 
Copying values
 
Ok then, we got to know what the stack and the heap are. What does this have to do with actual programming however? Earlier we mentioned that it has to do with the way values are copied. When we copy a value type variable to another, the second variable's value will be a copy of the first one's.
 

    private void ValueTypes()

    {
        //Value types are stored separately
        int int1 = 0;
        int int2 = int1;
        int1 = 1;
        int2 = 2;
    }
 
At the end of the method, int1 will be 1 and int2 will be 2. Integer is a value type. Let's check out the stack.
 
image3.jpeg (212×96)

 

Now, it's time to try out the same thing in a reference value, a class.

 

    private void ReferenceTypes()
    {
        //Reference types will be stored in the same location in the heap
        ReferenceTypeClass object1 = new ReferenceTypeClass();
        ReferenceTypeClass object2 = object1;
        object1.ReferenceTypeClass_Int = 1;
        object2.ReferenceTypeClass_Int = 2;
       
    }
 
At the end of the method, both object1's as well as object2's ReferenceTypeClass_Int will be 2.Why is that? When copying object1 to object2 we do not copy each value, we just copy the reference in the stack. So now we have two points in the stack aiming at the same point in the heap. Every change in the first object will change the heap. However the second object is also looking at the same memory part. So, at the moment the command  object1.ReferenceTypeClass_Int = 1; is run, both object1.ReferenceTypeClass_Int and object2.ReferenceTypeClass_Int will become 1. Running object2.ReferenceTypeClass_Int = 2; will result in their turning into 2.

 

 

Now, we will try to nullify the second object and see what will happen to the first copied object.

 

    private void ReferenceTypesNull()
    {
        //Setting object2 to null will not affect object1
        ReferenceTypeClass object1 = new ReferenceTypeClass();
        ReferenceTypeClass object2 = object1;
        object2 = null;
    }
 
At the end of the method, object2 will be null, but object1 won't. When nullifying object2 what we actually do, is to set the stack reference to null. Object2 no longer points to the heap object. However object1 is not affected at all by this. It is still pointing to the heap. If there was only one slot in the stack pointing at the heap, and we turned that into null, then the object in the heap would be useless, as we would not be able to access it. In that case the garbage collector would show up and release that heap location.

image5.jpeg (556×214)

 

 
Call by value
 
The default way of applying arguments to a method is calling by value. Arguments applied this way will not be subject to changes; instead a copy will be created to the stack, containing the argument's value. If the argument is of value type, a complete copy will be created and whatever changes may happen will affect the copy. If the argument is of reference type, a reference copy will be created in the stack pointing to the object in the heap. So we will have two objects pointing to the same values. As a result, changes applied to the second object will affect the original copy as well.
 
We now have a value type integer and a reference type class and a method that uses call by value.
 
        int valueTypeInteger = 0;
        ReferenceTypeClass referenceObject = new ReferenceTypeClass();
 
    private void CallByValue(int int1, ReferenceTypeClass object1)
    {
       //Integer will remain intact while class value will change
        int1 = 1;
        object1.ReferenceTypeClass_Int = 1;
    }
 
 
Prior to calling CallByValue we have
valueTypeInteger = 0
referenceObject.ReferenceTypeClass_Int = 0
 
After calling CallByValue(ValueTypeInteger, referenceObject) we have
valueTypeInteger = 0
referenceObject.ReferenceTypeClass_Int = 1
 
The integer is unaffected by the call, while the class' property has changed. The following image makes things clearer.
 
 
 
 
However the next method will not affect the argument ReferenceTypeClass object.
   
private void ClassByValueToNull(ReferenceTypeClass object1)
    {
        //Argument will remain intact
        object1 = null;
    }
 
Turning the new object into null will not affect the heap but rather remove the stack copy pointing to the heap.
 
 
 
Call by reference
 
We've just examined how calling by value works. Now it's time to check out call by reference. When calling a method this way we do not create a copy, rather than a reference to the stack value, whatever it may be. So, using call by reference to a value type will create a reference to the value in the stack, thus making it possible to change its value. Call by reference to a reference value will result in being able to change the reference in the stack, thus allowing us to change the object's value as well as its reference.
 
    private void CallByReference(ref int int1, ref ReferenceTypeClass object1)
    {
        //Both value and reference types will change
        int1 = 1;
        object1.ReferenceTypeClass_Int = 1;
    }
 
Prior to calling CallByReference we have
valueTypeInteger = 0
referenceObject.ReferenceTypeClass_Int = 0
 
After calling CallByReference(ValueTypeInteger, referenceObject) we have
valueTypeInteger = 1
referenceObject.ReferenceTypeClass_Int = 1
 
 
Let's try again the previous example. We tried to delete a reference type object using call by value. However, we will now use call by reference.
 
    private void ClassByReferenceToNull(ref ReferenceTypeClass object1)
    {
        //Argument will be null
        object1 = null;
    }
 
After calling this method, the argument object will become null.  Removing the reference, there are no object values associated with it any longer.
 
 
Conclusion
 
There are two kinds of type in .Net applications. Value and reference types. Value types point straight to their values while reference types contain an indirect reference and use different approach when copying values. Typically value types are stored in the stack, while reference types are held in the heap. Arguments in a method can be either called by value or by reference causing different effects depending on their nature.

 

 

Reference DotNetHints

Δημοσιεύτηκε στις Δευτέρα, 3 Μαρτίου 2014 3:54 μμ από το μέλος k badas :: 0 σχόλια

A simple guide to Unit Testing

Testing is a part of every developers life. No matter how experienced a programmer you are, there are always times when, out of pressure or by mistake, something will go wrong. Sooner or later you will have to test your code to ensure that everything works according to plan. So, how can unit testing make our lives easier? Unit Testing is a tool that allows developers to easily test their source code and ensure that it works just fine, as if they had actually tested it. We are going to take a look at how it works, all the way from the beginning till you can create simple, yet effective, unit tests on your own.

 

 

unit testing

 

Getting started

 

When testing, we compare the output of our project to what we are actually expecting to see. Supposing we create an application that sums up values. A simple test would be to try it out on two random numbers, 1 and 2. If the output is 3, our test was successful. However, the fact that we successfully got a 3, cannot ensure that by the time the projects is released, we will still get a 3.

 

Such issues and much more, which we will soon mention, are the reason we may choose to use unit testing. For the time being, let's create a simple unit testing example that will help newcomers to get to grips with the idea of unit testing.

 

 

Create the code to be tested

 

Unit tests can be applied to source code. We can use any project type we want, but let's try it out on a website. So, let's create a website and insert in its App_Code file the following file called Customer.cs.

 

What's the point of this class? Supposing a sales person wants to sort his customers depending on how "good" they are. To do so, he needs to know their monthly income, how much money they spent this month as well as their last month bill.

 

GetBalance will return how much monthly money the customer is still holding. A customer that spends all his money is a reckless one.

GetBillRatio will return the ratio of the customer's bill. The larger the ratio, the more generous the client.

IsVIPCustomer returns true if the customer has monthly balance greater than 1000 and ratio larger than 10%. We do not wish to disappoint such customers.

 

This is the class Customer.cs

 

using System;

 

public class Customer

{

    string customerName;

    double income;

    double bill;

    double lastBill;

 

    //These strings will be used as messages when throwing exceptions later on

    public string incomeMessage = "income less than bill";

    public string lastBillMessage = "lastBill equals to zero";

 

public Customer(string _customerName, double _income, double _bill, double _lastBill)

{

        customerName = _customerName;

        income = _income;

        bill = _bill;

        lastBill = _lastBill;

}

 

    public double GetBalance()

    {

        //We do not want to have customers with income less than bill

        if (income < bill)

            throw new ArgumentOutOfRangeException("income", income, incomeMessage);

 

        return (income - bill);

    }

 

    public double GetBillRatio()

    {

        //bill ratio in comparison with last month's

        if (lastBill != 0)

            return (bill - lastBill) / lastBill;

        else

            throw new ArgumentOutOfRangeException("lastBill", lastBill, lastBillMessage);

    }

 

    public bool IsVIPCustomer()

    {

        //returns true when balance is more than 1000 and billRatio more than 10%

        double balance = GetBalance();

        double billRatio = GetBillRatio();

 

        return ((balance > 1000) && (billRatio > 0.1));

    }

}

 

 

A customer, whose income is less than the money he spends, is a lousy one. GetBalance will throw an exception if such condition happen, so we can treat this case properly.

GetBillRatio's value is created by dividing with last month's bill. A new customer's last month's bill will be zero and we definitely do not want to divide by zero. We chose to throw an exception instead.

 

This is the source code we want to test. We will test the way we described earlier, by creating proper input and checking if the output was what we expected it to be.

 

 

 

Creating the unit test

 

To have a unit test we will need to create a new project.

 

Using Visual Studio 2012 go to

File -> New Project -> Installed -> Templates -> (Choose your favorite language eg Visual C#) -> Test -> Unit Test Project

 

Using Visual Studio 2010 or previous versions go to

Test -> New Test... -> Unit Test

 

Regardless of what edition you use, this will create our new Unit Test Project accompanied by its first file UnitTest.cs

 

A unit test file at minimum consists of the following:

  1. A reference to the Microsoft.VisualStudio.TestTools.UnitTesting library
  2. A public class declared as TestClass eg 
        [
    TestClass
    ]
      
     public class 
    UnitTest
  3. A void method declared as TestMethods eg

     [TestMethod]

     public void TestMethod()

 

Each TestMethod we create, provides us with a new test. In other words, to create a new test we will create a new TestMethod.

 

 

Test Methods

 

Earlier, we mentioned that, based on our specifications, GetBalance method should throw an exception in case income is less than the bill.

 

Let's create a new TestMethod that will ensure this will always happen.

 

   [TestMethod]

   public void TestMethod()

   {

      Customer cust = new Customer("Chris", 200, 500, 200);

      double balance = cust.GetBalance();

   }

 

We have just created a Customer object whose income is 200 and bill is 500. This should throw an exception if GetBalance is called.

 

Now we need to run our test and see if this actually happens. Go to Test -> Run -> All Tests. This will run all tests and provide as with our valuable info.

 

 

unit testing failed test

 

In the picture there are four test methods. We can see which ones passed the tests and which didn't. Our method TestMethod seems to have failed the test.

 

This is what we've been expected. The code was correct and the exception was thrown. Yet, there is something odd about it. Even though our test got successful results visual studio sorts it out as a failed test. Yet, we would actually want to think of this test as a successful one. So, what we should do is inform the method of the exception we are expecting to get, like this:

 

  [TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))]

   public void TestMethodForBalance()

   {

     cust = new Customer("Chris", 200, 500, 200);

 

     double balance = cust.GetBalance();

   }

 

 

Running our test once again, we are informed that it passed!

 

Now, we would like to create a test that will ensure that a customer with 2000 income, 500 bill and 200 last month's bill will throw no exception. So, we write

 

   [TestMethod]

   public void TestMethod()

   {

     Customer cust = new Customer("Chris", 2000, 500, 200);

 

     double balance = cust.GetBalance();

     double ratio = cust.GetBillRatio();

     bool isVIP = cust.IsVIPCustomer();

   }

 

That will be a successful test as well.

 

 

Why unit testing?

 

 

You are probably starting to realize why unit testing is important. We have just created a test which ensures that this kind of customer will throw no exceptions. Now, the source code we are testing is likely to be altered in times. However the test will still be there. And then, no matter who is going to be assigned this, the developer may run this unit test and ensure that what he has changed does not interfere with the initial specifications.

 

This is only one test method. Supposing the first developer had created test methods enough to check all possible results. In that case, it would only take a few seconds to the new developer to run the tests and ensure that everything still works fine.

 

Apart from this, unit testings can provide a developer with easy understanding of what the source code is supposed to do and thus keep a major summary of the specifications, without needing tons of paper by his/her side.

 

 

A second look on Test Methods

 

 

So far we have created test methods that can only help us with exception issues. Yet, this is not enough. For example, we may wish to know if our friend Chris is a VIP customer. To answer that we need the IsVIPCustomer method we created earlier. However, right now we are testing. We have done our homework and found out that Chris is a VIP customer. How can we test this?

 

To accomplish that, we are going to use the Assert class that unit testing offers to us. Assert contains many methods such as AreEqual, IsNull and IsTrue. What Assert's methods do, is compare the input with an expected value. For example in the example where we want to test if IsVIPCustomer is true we will use

 

   [TestMethod]

   public void TestMethodWithAssert()

   {

     Customer cust = new Customer("Chris", 2000, 500, 10);

     bool isVIP = cust.IsVIPCustomer();

 

     Assert.IsTrue(isVIP);

     // We may also use this: Assert.AreEqual(isVIP, true);

   }

 

This TestMethod is successful and, this way, we ensure that we get the result we expect. That is to say, Chris is a VIP. However, if Chris was not a VIP (IsVIPCustomer returns false) then our test would have failed.

 

This is the last test method we will examine. A while ago we tested that GetBalance throws an exception if income is less than the bill. However, if we wanted to test both GetBalance and GetBillRatio methods but wanted to check only for GetBalance exception, this would be no good as they both throw the same type of exception. Take a look at the class we are testing. These two methods throw exceptions, however each one has a different message carried within it. So, in order to separate them, we will have to test that message. To do so, this time we will use StringAssert class. This is a class similar to Assert that is mostly fit to string testing. It contains methods such as Contains and EndsWith. This is our code.

 

 

   [TestMethod]

   public void TestMethodWithExceptionAssert()

   {

     Customer cust = new Customer("Chris", 200, 500, 100);

 

     try

     {

       double balance = cust.GetBalance();

       double ratio = cust.GetBillRatio();

       bool isVIP = cust.IsVIPCustomer();

     }

     catch (ArgumentOutOfRangeException e)

     {

       StringAssert.Contains(e.Message, cust.incomeMessage);

     }

   }

 

This test will pass as well. In that case we can tell that either no exception was thrown or an exception was thrown by GetBalance.

 

 

 

TestInitialize and TestCleanup

 

So far we have learned how to create simple test methods. Yet, unit tests offer two more, easy to handle, attributes. TestInitialize and TestCleanup

 

Using TestInitialize on a method we declare that this method will be run before all test methods do.

Using TestCleanup on a method we declare that this method will be run after all test methods do.

 

These methods can be used to create and remove resources that will be used by the test methods. For example we can use TestInitialize in the following way:

 

     [TestClass]

     public  class UnitTest

    {

        Customer cust;

 

        // Use TestInitialize to run code before running each test

        [TestInitialize()]

        public void MyTestInitialize()

        {

            cust = new Customer("Chris", 2000, 500, 200);

        }

 

    [TestMethod]

     public void TestMethod()

     {

       double balance = cust.GetBalance();

       double ratio = cust.GetBillRatio();

       bool isVIP = cust.IsVIPCustomer();

     }

}

 

 

Should I use Unit Testing?

 

 

There is no straight answer to this question. You may choose to use it or not depending on what you feel like. Unit testing, as told already, can be used to create tests that will wait there to be run whenever you want. It can also be used as specs guide.

 

However creating unit tests requires amount of time. Do you always feel you have the time necessary to use unit testing? A script schedule does not allow a developer such comforts. However, a well-organized schedule may offer some time to spend on unit testing and thus helping you keep everything in one place.

 

In general, you should keep in mind that unit testing will give you long-term results and not something that can be seen in a few days time.

 

 

Conclusion

 

Unit testing is a developers testing test. Unit Testing requires a new project consisting of a TestClass class and one or more TestMethod methods. Inside these methods we can test our code for exception handling, parameter and method returning values and much more as if we were testing the code through a user interface. Even though unit testing can be very useful it can also be time consuming so you should take such things into account before starting to use it in your projects.

Reference DotNetHints

 

Δημοσιεύτηκε στις Κυριακή, 23 Φεβρουαρίου 2014 5:48 μμ από το μέλος k badas :: 0 σχόλια

Enter JSON

I have already written some articles concerning AJAX, now it's time to take another step and introduce JSON. Actually JSON is just a format - a standard - not a technique. However it is widely used in combination with AJAX in order to create asynchronous requests resulting in JSON data.

 

 

What is JSON?

 

JSON is a data format, nothing more nothing less. The same way we open a jpeg file and expect it to contain jpeg data, JSON data contains data in predefined form. The simplest example of that form would be

{ "ID": 1 }

Now, JSON is a format used to carry data, the same way XML does but in a more easy-to-read way to a human. Compare the XML with its JSON equivalent.

<ID>1</ID>

{ "ID": 1 }

JSON seems to be like reading a book in comparison to XML. JSON stands for JavaScript Object Notation. As you will see its contains use the form of an object. JSON was at first created for JavaScript, that's the reason this language is mentioned on its name. However, JSON soon became a widely acknowledged standard. Since then most platforms created libraries that support it. As a result it is quite easy to handle it. But we will come back to that later on.

Jason

JSON Syntax

 

JSON is written in a dictionary-like way (name value pair).

"ID": 1 refers to the name "ID" which contains the value 1. Between the name and the value a ':' character should be placed.

 

Keep in mind that the name part should always be contained in double quotes (") while this is not compulsory for the value part. For example numeric and boolean values need not be contained within double quotes.

 

To expand our simple example we will add more name value pairs.

{ "ID": 1,

  "Name": "Spock",

  "Species": "Half-Vulcan" }

Ok, this is a simple, yet nice, JSON expression. Now, let's go and use some JavaScript to handle it.

 

    <script type="text/javascript">

        var JSONData = {

             "ID": 1,

             "Name": "Spock",

             "Species": "Half-Vulcan"

        };

 

        document.write(JSONData.Name + " is a " + JSONData.Species + " character.");

    </script>

 

Running the script we get:

Spock is a Half-Vulcan character.

 

 

Quite simple, now let's create an array of pairs, expanding the one we already have, using brackets to contain the elements.

[ { "ID": 1,

  "Name": "Spock",

  "Species": "Half-Vulcan" },

{ "ID": 2,

 "Name": "Kirk",

 "Species": "Human" }

]

 

In order to use JavaScript to loop through all elements we could use the following code.

    <script type="text/javascript">

        var JSONDataArray = [{

             "ID": 1,

             "Name": "Spock",

             "Species": "Half-Vulcan"

        },

   {

             "ID": 2,

             "Name": "Kirk",

             "Species": "Human"

   }];

 

        document.write("<br/><br/>");

        for (var i = 0; i < JSONDataArray.length; i++) {

            var obj = JSONDataArray[ i];

            document.write(obj.Name + " is a " + obj.Species + " character.<br/>");

        }

    </script>

 

This time we get:

Spock is a Half-Vulcan character.
Kirk is a Human character.

 

Of course, the previous JSON array could be included in pure JSON format by including the whole of the array inside a value, like this.

{"StarTrek", "[ { "ID": 1,

  "Name": "Spock",

  "Species": "Half-Vulcan" },

{ "ID": 2,

 "Name": "Kirk",

 "Species": "Human" }

]}

 

This would be about the same thing for our handling. The only difference would be that we would have to point to the "StarTrek" name instead of handling the array right away.

    <script type="text/javascript">

        var StarTrekJSONDataArray = {"StarTrek" : [{

            "ID": 1,

             "Name": "Spock",

             "Species": "Half-Vulcan"

        },

       {

             "ID": 2,

             "Name": "Kirk",

             "Species": "Human"

            }]};

 

        document.write("<br/><br/>");

        for (var i = 0; i < StarTrekJSONDataArray.StarTrek.length; i++) {

            var obj = StarTrekJSONDataArray.StarTrek[ i];

            document.write(obj.Name + " is a " + obj.Species + " character.<br/>");

        }

</script>

 

The result will still be the same

 

Spock is a Half-Vulcan character.
Kirk is a Human character.

 

 

As you can tell, JSON variables can become much more complex than we just created, but we have already covered the basics. Now, we said that JSON is platform independent as it is just a format and is not limited to certain platforms or languages. Let's see how this can be of help.

json logo

Server side JSON

 

JSON is platform independent. So, its true power does not lie in creating and handling JSON objects using JavaScript, as much as creating them server side and then handling them using JavaScript. Since everything knows what JSON is, we can create it using C#, for example, and then handle it using JavaScript. Here's how to do it.

 

We are going to create a simple class called StarTrekCharacter that represents Star Trek characters. This class will contain a static method called GetStarTrekCharacters() that will return all the data we have. We do not need more than three characters at the moment.

 

Next we create a web form using which we will get data in JSON format concerning Star Trek characters whose name matches the string we are searching. In other words, we will create a simple search engine.

 

Our search query will be passed using the query string. Then we will use LINQ to filter our data and return the ones we want. Finally we need to create a JavaScriptSerializer object which we will use to serialize our data in JSON form. Here's the code.

 

The aspx page should be completely empty as we are not creating html

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="JSON_Search" %>

 

and the code behind file

 

using System;

using System.Linq;

using System.Collections.Generic;

 

public partial class JSON_Search : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if(Request.QueryString.AllKeys.Contains("query"))

        {

            //Get the query and use ToLower so that there is no letter case

            string query = Request.QueryString["query"].ToString();

            string queryToLower = query.ToLower();

 

            List<StarTrekCharacter> searchResults = StarTrekCharacter.GetStarTrekCharacters();

            //Filter results using Linq so they contain our search query

            var filteredSearchResults = searchResults.Where(sr => sr.Name.ToLower().Contains(queryToLower));

 

            //Create JavaScriptSerializer

            var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            jsonSerializer.MaxJsonLength = 2147483647;

            //Return serialized json data

            Response.Write(jsonSerializer.Serialize(filteredSearchResults));

        }

    }

}

 

public class StarTrekCharacter

{

    public int ID {get; set;}

    public string Name { get; set; }

    public string Species { get; set; }

 

    public StarTrekCharacter()

    {

    }

 

    //Get Data

    public static  List<StarTrekCharacter>> GetStarTrekCharacters()

    {

        List<StarTrekCharacter> StarTrekCharacters = new List<StarTrekCharacter>();

        StarTrekCharacters.Add(new StarTrekCharacter() { ID = 1, Name = "Spock", Species = "Half-Vulcan" });

        StarTrekCharacters.Add(new StarTrekCharacter() { ID = 2, Name = "Kirk", Species = "Human" });

        StarTrekCharacters.Add(new StarTrekCharacter() { ID = 1, Name = "Scotty", Species = "Human" });

 

        return StarTrekCharacters;

    }

}

 

 

So, suppose we want to get all StarTrekCharacters whose name contains the string "s". We should request the following url

http://localhost:49808/DotNetHintsBlog/JSON/Search.aspx?query=S

 

The result will be

 

[{"ID":1,"Name":"Spock","Species":"Half-Vulcan"},{"ID":1,"Name":"Scotty","Species":"Human"}]

 

 

That's all. We got ourselves a JSON array, similar to the one we used previously. If we had called this page using JavaScript we would have our JSON data right in our hands. And that's exactly what we are going to do right now.

 

 

JSON and AJAX

 

In previous articles we talked about AJAX and how we can use it to make asynchronous requests in order to get back data such as XML or pure HTML. Similarly, we can use AJAX to request JSON data. Our server control that returns JSON data is ready and set to a file called search.aspx. Now we have to create some piece of JavaScript to make it work.

 

This is the HTML we will use:

       

Keyword: <input type="text" id="KeywordInputID" />

<button onclick="search()">Search</button>

<br />

<span id="ResponseSpanID" />

 

We insert the keyword to the input and press the button. This will call the search method. Here's the script part.

 

<script type="text/javascript">

        function search() {

            var xmlhttp;

            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari

                xmlhttp = new XMLHttpRequest();

            }

            else {// code for IE6, IE5

                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

            }

            xmlhttp.onreadystatechange = function () {

                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

 

                    var JSONDataArray = JSON.parse(xmlhttp.responseText);

                    var text = "";

                    for (var i = 0; i < JSONDataArray.length; i++) {

                        var obj = JSONDataArray[ i];

                        text = text + obj.Name + " is a " + obj.Species + " character. Server info!<br/>";

                    }

                    document.getElementById("ResponseSpanID").innerHTML = text

                }

            }

            var url = "search.aspx?query=" + document.getElementById("KeywordInputID").value;

            xmlhttp.open("GET", url, true);

            xmlhttp.send();

        }

 

   </script>

 

This is what the example looks like:

 

 

JSON.html

JSON Response

 

This is an AJAX request which we already know how to handle. If you need to refresh your memory check out my previous article. The interesting part is this:

 

             var JSONDataArray = JSON.parse(xmlhttp.responseText);

              var text = "";

               for (var i = 0; i < JSONDataArray.length; i++) {

                   var obj = JSONDataArray[ i];

                   text = text + obj.Name + " is a " + obj.Species + " character. Server info!<br/>";

               }

               document.getElementById("ResponseSpanID").innerHTML = text

 

We use JSON.parse(xmlhttp.responseText) to parse our data to JSON format. Then we go through all items in the array the way we did earlier.

 

There are many things around the web asking for JSON data as an argument. As a result it is quite important to know how to ask your server for this kind of data.

 

 

Summary

 

JSON is a data standard used primarily in web applications to carry data in the form of objects. It uses syntax in the form of name value; however a JSON variable can end up in quite a complex form. JavaScript can easily handle JSON data and help us get the values we want. JSON can be combined with AJAX in order to get asynchronous responses carrying JSON data.

 

Reference DotNetHints

Δημοσιεύτηκε στις Κυριακή, 16 Φεβρουαρίου 2014 12:13 μμ από το μέλος k badas :: 2 σχόλια

Asynchronous programming in .NET 4.5

Asynchronous programming has been a part of Microsoft's applications for a long time. However things tend to mature. .NET 4.5, released in August 2012, brought up C# 5 and VB 2012. And along came a new way of creating asynchronous methods. Instead of using multithreading or similar techniques, we now have access to an easier way using the key words async and await. Since a reader asked me, I am going to take a look at how these things work in today's article.

 

What is asynchronous programming?

 

The common way source code is handled, is synchronous (linear). That means that in order to accomplish two or more processes, that have nothing to do with each other (in other words, the sequence of these processes does not affect the result we get) we would have to wait for them all to complete one by one. Now, if the first process needed 10 seconds to complete and the second 5 seconds, the amount of time we would need to get the job done would be a total of 15 seconds. This way is no good because the second process is just sitting there waiting for the first process to complete.

 

waiting_synchronous

 

That's where the asynchronous trick comes in play. When we work asynchronously, everyone is doing their own job at the same time. When the first process begins, the second process begins as well. In the previous example, supposing that the processes do not require the same resources, that will give as a total of 10 seconds. Take a look at the next picture to get a better grip.

synchronous vs asynchronous

 

As mentioned earlier, asynchronous programming has already been developed before .NET 4.5 was released. There were some methods a developer could accomplish this, but in this article I am going to refer only to the new methods introduced in .NET 4.5 using examples from C# 5.

 

 

 

async and await

 

async is a keyword introduced in .NET 4.5. Accompanying a method declaration, it tells the compiler that this method is going to use asynchronous techniques. We can use it like that:

 

async void Call_Async()

{

}

 

That's all about async. There's nothing more to know in order to use it. However, if we tried to build the previous method, compiler would point a warning, stating that our async method is expected to contain the await keyword otherwards it will be considered as synchronous method. That's quite true, we have stated that our method will make use of asynchronous methods, but we are actually implementing none of them. In order for the compiler to be satisfied we should use the await keyword. For example:

 

// State the method as async, so you can use the await keyword

protected async Task Call_Async()

{

  //isOK will be set to false if GetPagesAsync fails

  bool isOK = await GetPagesAsync();

 

  //Inform the user

  if (isOK)

    AsyncLabelID.Text = "Asynchronous methods completed successfully";

  else

    AsyncLabelID.Text = "Asynchronous methods failed to complete successfully";

}

 

This is the method that will run when we press a button in the ASP.NET application we will create later on.

 

OK, what does that piece of code do? The first command calls a GetPagesAsync method like a simple program would. However, the await keyword states that you should wait for this method to complete before we go on. That's what the await keyword does. When you create and run an asynchronous operation, the basic method will still run. When it finds await, it stops till the asynchronous operation stated is complete.

 

Here's our first picture using await.

 

synchronous vs asynchronous await

Before we go on, you may have noticed that we changed the return type from void to Task. Using async in void methods is not a good idea since it is actually pointing to a fire and forget model. As this may lead to unexpected results, methods marked as async avoid should better be avoided.

 

Now, you may say, "Big deal, that's what happens to synchronous programming as well, the second command waits for the first command to complete." and you may be right. However, let's take a look at the GetPagesAsync method.

 

async Task<bool> GetPagesAsync()

{

  try

  {

    HttpClient client = new HttpClient();

 

    //Create two asynchronous operations

    Task<string> getDotNetHintsStringTask = client.GetStringAsync("http://dotnethints.com");

    Task<string> getWikipediaStringTask = client.GetStringAsync("http://www.wikipedia.org");

 

    //The method will still run at the same time as the asynchronous operations do

    ComputeOtherStuff();

 

    //This is the place where the method must wait for the operations to complete

    await Task.WhenAll(getDotNetHintsStringTask, getWikipediaStringTask);

    return true;

  }

  catch

  {

    return false;

  }

}

 

 

void ComputeOtherStuff()

{

  //Just wait for two seconds

  System.Threading.Thread.Sleep(2000);

}

 

Hmmm, these methods do a lot of new stuff. If you got confused let's take a good look together, all the way from the beginning. First thing you may have noticed is that GetPagesAsync returns Task<bool>, while we might have been expecting to see a simple bool value. And what is this Task thing anyway?

 

If you haven't heard of tasks before, you may want to read this paragraph. The Task class (System.Threading.Tasks) is a part of the Task Parallel Library. Not going any further, consider a Task object as the representation of an asynchronous operation. A Task object has many methods reffering to that operation such as Start, Wait and Cancel.

 

So, when we write

 

Task<string> getDotNetHintsStringTask = client.GetStringAsync("http://dotnethints.com");

 

we are creating a new Task object (asynchronous operation) that is expected to carry a string value. .NET 4.5 has introduced many new asynchronous methods in order to use with its new asynchronous features like HttpClient.GetStringAsync, StreamReader.ReadAsync, BitmapEncoder.CreateAsync and many more. Asynchronous method names tend to end with the "Async" characters so they are easy to spot.

 

GetStringAsync method will return a Task containing a string value that carries the html of a web page. That happens asynchronously.

 

It may be easier now to understand why a method returning a Task<bool> value can be set to a bool value. Because it is the task's value that is set to the bool variable.

 

Great, so we have now created two asynchronous operations that download two web files. Dotnethints and Wikipedia. Being asynchronous they allow our code to go on. So we call the simple ComputeOtherStuff function that could actually do many things, but instead it will just wait for two seconds as we actually have nothing important to do in mind at the moment.

 

Then comes the await keyword, and what does it do? It says, "All right method, that's as far as you can go, now you will wait for our tasks." What tasks? The ones we tell him. Task.WhenAll(Task1, Task2, ...) will wait for all Tasks stated to complete. That would be getDotNetHintsStringTask and getWikipediaStringTask in our example. If we needed only one Task to complete, then we could simply use

 

await getDotNetHintsStringTask;

 

This is what we did in Call_Async. Remember that?

 

bool isOK = await GetPagesAsync();

 

Now you may be wondering. Is there any point for us to create two async methods, where the first calls the second one? Why not creating only one? You may be right as, the way we mentioned earlier this command is not much different than default synchronous programming. We could instead use this method.

 

protected  void Synchronous_Call()

{

  //Get the Task instead of the value

  Task<bool> boolTask =  GetPagesAsync();

 

  bool isOK = boolTask.Result;

 

  //Inform the user

  if (isOK)

    AsyncLabelID.Text = "Asynchronous methods completed successfully";

  else

  AsyncLabelID.Text = "Asynchronous methods failed to complete successfully";

}

 

The result would be the same in that case. Remember, we are now talking ONLY about the time when you do not want to do asynchronous programming in the first method. That is when you use await in a single command.

 

bool isOK = await GetPagesAsync();

 

In that case only, we could use synchronous programming. However, most developers tend to use async and await even for that single command. That is so we can separate the asynchronous functionality from the caller method. That is the way the examples in this article will be written as well, with the exception of the last example.

 

Ok, you may still have questions but let's see what our full ASP.NET example looks like before we go on.

 

    protected void Page_Load(object sender, EventArgs e)

    {

        // RegisterAsyncTask is used instead of simply calling async void Call_Async method

        RegisterAsyncTask(new PageAsyncTask(Call_Async);

 

        //You may use ExecuteRegisteredAsyncTasks to run asynchronous tasks yourself

        //ExecuteRegisteredAsyncTasks

    }

 

    // State the method as async, so you can use the await keyword

    protected async Task Call_Async()

    {

        //isOK will be set to false if GetPagesAsync fails

        bool isOK = await GetPagesAsync();

 

        //Inform the user

        if (isOK)

            AsyncLabelID.Text = "Asynchronous methods completed successfully";

        else

            AsyncLabelID.Text = "Asynchronous methods failed to complete successfully";

    }

 

    async Task<bool> GetPagesAsync()

        {

            try

            {

                HttpClient client = new HttpClient();

 

                //Create two asynchronous operations

                //These methods will asynchronously get the content of the specifies web pages

                Task<string> getDotNetHintsStringTask = client.GetStringAsync("http://dotnethints.com");

                Task<string> getWikipediaStringTask = client.GetStringAsync("http://www.wikipedia.org");

 

                //The method will still run at the same time as the asynchronous operations do

                ComputeOtherStuff();

 

                //This is the place where the method must wait for the operations to complete

                await Task.WhenAll(getDotNetHintsStringTask, getWikipediaStringTask);

                return true;

            }

            catch

            {

                return false;

            }

        }

 

 

    void ComputeOtherStuff()

        {

            //Just wait for two seconds

            System.Threading.Thread.Sleep(2000);

        }

 

 

 

Result:

Asynchronous methods completed successfully

When in an ASP.NET application, we can use the RegisterAsyncTask(new PageAsyncTask(method_name)) method to avoid straight calling of async void methods.

 

I think we have covered how this code works. All we need now is the AsyncLabelID Label control where we will state if the operations were successful. And one more thing. When creating ASP. NET asynchronous functionality you will need to set Async="true" in your page parameters and use asynchronous operations only within events that fire before the PreRenderComplete does.

 

Now, let's move on to a WPF application that does about the same thing as the previous example did.

 

 

WPF Example

 

 

The following example will get the same web pages as we did earlier. The story will begin when we press a button and call AsyncButton_Click.

However this time, while the pages are fetched, we will show a waiting message in the AsyncLabel Label. Since this is a WPF application we can change the label's content any time we want.

 

// State the method as async, so you can use the await keyword

private void AsyncButton_Click(object sender, RoutedEventArgs e)

{

  //Use CallAsyncMethods to avoid use of void async in the AsyncButton_Click method

   CallAsyncMethods();

}

 

async Task CallAsyncMethods()

{

  //isOK will be set to false if GetPagesAsync fails

  bool isOK = await GetPagesAsync();

 

  //Inform the user

  if (isOK)

    AsyncLabel.Content = "Asynchronous methods completed successfully";

else

   AsyncLabel.Content = "Asynchronous methods failed to complete successfully";

 

}

 

async Task<bool> GetPagesAsync()

{

  try

  {

    HttpClient client = new HttpClient();

 

    //Create two asynchronous operations

    //These methods will asynchronously get the content of the specifies web pages

    Task<string> getDotNetHintsStringTask = client.GetStringAsync("http://dotnethints.com");

    Task<string> getWikipediaStringTask = client.GetStringAsync("http://www.wikipedia.org");

 

   //The method will still run at the same time as the asynchronous operations do

   ComputeOtherStuff();

 

   //This is the place where the method must wait for the operations to complete

    await Task.WhenAll(getDotNetHintsStringTask, getWikipediaStringTask);

   return true;

  }

  catch

  {

  return false;

  }

}

 

 

void ComputeOtherStuff()

{

  AsyncLabel.Content = "Waiting . . . .";

}

 

async await wpf

 

WPF Second Example

 

This is our last example which will be a bit more complicated than the previous one. We will also use arguments to show that everything works just like typical methods. Take a look at the code first.

 

protected void AsyncButton_Click(object sender, EventArgs e)

{

  CallAsyncMethod();

  //The next command will be executed even before the asynchronous method is completed

  AsyncLabel.Content = "Waiting . . . .";

}

 

 

private async Task CallAsyncMethod()

{

  string result = await GoToSlowMethod("Job Done");

  //To get past this point GoToSlowMethod should be completed

  AsyncLabel.Content = result;

}

 

private Task<string> GoToSlowMethod(string message)

{

//Create a Task that calls the SlowMethod method

return Task.Run<string>(() => SlowMethod(message));

}

 

private string SlowMethod(string message)

{

  //Wait for three seconds

  System.Threading.Thread.Sleep(3000);

  return message;

}

 

Let's go through the action sequence one by one.

  1. We press the button. AsyncButton_Click is called.
  2. CallAsyncMethod is called
  3. GoToSlowMethod is called
  4. A Task containing the SlowMethod method is run.
  5. SlowMethod is called. We are waiting for 3 seconds.
  6. In the meantime, we go back to CallAsyncMethod. We are still waiting for GoToSlowMethod.
  7. So we go back to AsyncButton_Click. AsyncLabel.Content = "Waiting . . . ."; is executed.
  8. About three seconds later SlowMethod is completed and returns "Job Done"
  9. GoToSlowMethod will return a Task containing the "Job Done" string.
  10. CallAsyncMethod sets the content of AsyncLabel to "Job Done"
  11. AsyncButton_Click completes

 

So, the result will be:

 

wpf async await example 2

 

 

 

Conclusion

 

.NET 4.5 presented a new technique of asynchronous programming using the async and await keywords. A method marked as async is expected to contain asynchronous operations and the await keyword. When an asynchronous operation is created the current method's code will keep executing until we reach the point where await is set for that operation. Asynchronous programming can be very helpful when dealing with time consuming independent methods.

 

Reference

DotNetHints

Δημοσιεύτηκε στις Κυριακή, 9 Φεβρουαρίου 2014 1:35 μμ από το μέλος k badas :: 0 σχόλια

Secure your website

When was the last time you heard a website was hacked? Well, probably what you have heard of concerned some major properly secure website and the people who got access to it were no rookies. However this is no excuse for you to stand there waiting for a novice hacker to play around with your website. Let's go through a few of the most common and easy to handle techniques.

web security

Getting Started

 

Web is a complicated thing.  There are a lot of ways a malicious user may attack you. Just because between you and him lies the web. A user can create false responses, create false cookies or try to get access to your database. To begin with let's keep in mind that what we will be talking about is not the security of your web server. This is a whole new topic responsible of which is your host and not you. However you are responsible for what you have created. No host will be sorry you for your deleted database tables if you were not careful enough with your code.

 

What's the whole idea of the attack? A nice way to attack a web application is to create unpredictable conditions. That is, to cause your server to throw an exception and send the attacker the exception details. You may think that this is no big deal and that even when you, who have written the code, take a look at an exception, there may be times you won't get what the problem is at once. So how could a stranger do so? That is absolutely not true. An attacker at first has no idea what your site code looks like. By getting exception messages he can slowly create an image of that.

exception message

 

So, a simple, yet great, step towards securing your website is to stop these messages. To do so, you should create an error page.

 

Creating an error page is a quite simple thing to do. It requires two things.

  1. Create a simple aspx page. It is a good thing to keep the same design as the rest of the site in case a user happens to find himself there, he will not feel alienated. Our simple error page will contain nothing more but the message              <b>This is the error page!</b>
  2. Set <customErrors mode="On" defaultRedirect="ErrorPageName.aspx"/> on your web.config file

 

 

That's all. Now even though your attacker will know he did something bad, he will have no means to tell what effect this had.

 

 

Setting the scenery for our attacks

 

We will use a simple aspx page

 

Enter your username to log into our insecure website:

<asp:TextBox runat="server" ID="EvilTextBox" />

<asp:Button runat="server" ID="LogInButtonID" Text="Log In" OnClick ="LogInButtonClicked" />

<br />

<asp:Label runat="server" ID="ResultLabelID" />

 

Let's call it security.aspx

 

This is the code behind

 

protected void LogInButtonClicked(object sender, EventArgs e)

{

  //Get the text to enter in our sql query

  string evilTextBoxMessage = EvilTextBox.Text;

 

  string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

  SqlConnection con = new SqlConnection(connectionString);

  string sql = " SELECT * FROM TestMembers WHERE Username = '" + evilTextBoxMessage +"'";

 

  SqlCommand cmd = new SqlCommand(sql, con);

 

  con.Open();

  SqlDataReader reader = cmd.ExecuteReader();

  if (reader.HasRows)

    //Log the user

    ResultLabelID.Text = "Logged In. Welcome " + EvilTextBox.Text;

  else

    //Show failure message

    ResultLabelID.Text = "Could not log In. Username " + EvilTextBox.Text + "does not exist in the database.";

    reader.Close();

    con.Close();

 

}

 

I guess what it does is quite plain. We create an SqlCommand using the connection string we got from the web.config file. We open our connection, hit the database and then show the message. This would do perfect for a first database connection example but nothing more.

 

Let's see what may happen depending on the input.

 

1) A good user enters "Tom"

The SQL query is SELECT * FROM TestMembers WHERE Username = 'Tom'

and since Tom happens to be a member of our website we get a success message.

 

 

2) An evil user familiar to SQL enters x'; DROP TABLE TestTable;--

The SQL query is  SELECT * FROM TestMembers WHERE Username = 'x'; DROP TABLE TestTable;--'

 

 

 

Wow. A total table is deleted. The malicious user somehow found out that we have a table called TestTable and took great advantage of it. Instead of deleting the table he could as well have created new rows or updated existing rows ( passwords etc) and do many nasty things before we get a clue that something bad has happened.

 

This kind of attack is called SQL Injection.

 

3) Another evil user, this time familiar with JavaScript, enters "<script>alert("Gotcha!");</script>"

What does our label show?

Could not log In. Username <script>alert(\"Gotcha!\");</script>does not exist in the database.

 

However the actual result is

 

cross-site scripting attack

 

Boom. A total stranger inserted a script in the page he received. Well ok, that's no big deal since in our case he's the only person who can see this alert. However, what would have happened if the person had signed in using that script as a username? Supposing our website has an administration site, when the administrator visits the member's page the script will be executed as well. Then the administrator will get this alert as well. And if you think that a simple alert message is no big deal, keep in mind that using JavaScript the user can get much more valuable information and we may never get a clue of that.

 

This kind of attack is called Cross-Site Scripting Attack.

 

Keep in mind that by default, asp.net will throw an exception if you try to post a script message. This is a useful precaution set by the framework so that inexperienced developers will be protected by cross-site scripting attacks. And that's quite useful. For example it is quite uncommon that a person might  want to sign up using a script within his user name. However there may be times a user may want to include script in his input. For example forums that have to do with web development are quite common to include scripts in their posts. In that case we do not want the framework to block these messages. To do so, we set

validateRequest="false"

in our page properties. From now on it's up to us to avoid such attacks.

 

 

Watch out for the input.

 

It's not as easy to be protected from all kind of attacks. We will first discuss how to protect your site from attacks that have to do with input, like the examples above.

 

What happened, is that the user took advantage of the fact that there was no validation in the field we asked for data. So he easily filled our textbox with nasty code. And it's not all in what you insert in textboxes. Everything that comes to you from the web must validated. And I mean everything.

  1. Textboxes and all types of form input
  2. Query String
  3. Cookies
  4. Viewstate

 

These can be altered quite easily, so they all have to be validated.

 

A good way to start your validation is to see if the input contains what is supposed to contain. If the input contains money amount, check if you can cast it to double. If you get an exception, the input is no good. It's a good idea to handle such exceptions using try/ catch so you can have total control of the flow. And like we said, use an error page. Look at the following code.

 

//Amount validation part

double amount;

try

{

  amount = Convert.ToDouble(AmountTextBoxID.Text);

}

catch(FormatException ex)

{

  //If the conversion fails then we should show the error page

}

// Do whatever you wish with the amount value, since the input was no good

 

If you want, you can do extra validation using regular expressions, to check, for example, if an email input seems to have email format etc.

 

OK, this will do something, but how can we protect ourselves against input that is supposed to contain a string? A nice way to prevent simple cross side scripting attacks is to use the HtmlEncode method located within the System.Web namespace.

 

HtmlEncode should be used before inserting the input to the response. HtmlEncode will return the input string having replaced all html characters with html-encoded text. For example '<' will be turned to "&lt;" and '>' to "&gt;" This way the browser will treat them as simple text and no scripts will be executed.

 

Look what happens to the previous input when we use HtmlEncode.

Instead of

Could not log In. Username <script>alert(\"Gotcha!\");</script>does not exist in the database.

We get

Could not log In. Username &lt;script&gt;alert(&quot;Gotcha!&quot;);&lt;/script&gt;does not exist in the database.

 

This will work just fine and fill the label with the actual input, protecting us from possible problems.

 

 

Preventing SQL Injections

 

Now, what to do with the SQL Injections? The solution to this problem is quite simple. We will use parameters in the SqlCommand object instead of creating a simple query string. For example

 

//Use SqlParameters in our command instead of creating a plain sql query

string sql = " SELECT * FROM TestMembers WHERE Username = @Username";

 

SqlCommand cmd = new SqlCommand(sql, con);

//Add parameters to the SqlCommand object

cmd.Parameters.Add(new SqlParameter("@Username", evilTextBoxMessage));

 

When a value is set to an SqlParameter then it is attached to the parameter. In other words, no matter what we write in the textbox, its content will always be used in order to filter the results based on the Username column.

 

Another way to cancel SQL Injection attacks would be to use stored procedures in about the same way. You can also use LINQ instead. No matter what we choose to do, what we need is to bind the value with the parameter so it will execute nothing more than it is supposed to.

 

This is the first method using the new, more secure methods we talked about.

 

 

 

protected void LogInButtonClicked(object sender, EventArgs e)

{

  //Get the text to enter in our sql query

  string evilTextBoxMessage = EvilTextBox.Text;

 

  string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

  SqlConnection con = new SqlConnection(connectionString);

  //Use SqlParameters in ouir command instead of creating a plain sql query

  string sql = " SELECT * FROM TestMembers WHERE Username = @Username";

 

  SqlCommand cmd = new SqlCommand(sql, con);

  //Add parameters to the SqlCommand object

  cmd.Parameters.Add(new SqlParameter("@Username", evilTextBoxMessage));

  try

  {

  con.Open();

  SqlDataReader reader = cmd.ExecuteReader();

  if (reader.HasRows)

    //Log the user

    ResultLabelID.Text = "Logged In. Welcome " + EvilTextBox.Text;

  else

    //Show failure message

    ResultLabelID.Text = "Could not log In. Username " + Server.HtmlEncode(EvilTextBox.Text) + "does not exist in the database.";

    reader.Close();

  }

  catch (Exception ex)

  {

  //Try/catch can be used both to check for connection problems and sql injection attacks

  }

finally

  {

  con.Close();

  }

 

 

  //Amount validation part

  double amount;

  try

  {

    amount = Convert.ToDouble(AmountTextBoxID.Text);

  }

  catch(FormatException ex)

  {

    //If the conversion fails then we should show the error page

  }

  // Do whatever you wish with the amount value, since the input was no good

 

}

 

 

 

 

Identity Spoofing Attacks

 

We are doing well, but still our website isn't secure even against simple attacks. Identity Spoofing is the next thing we should take into account. A logged user usually has some kind of cookie that contains data for the server. This way he is logged automatically next time he visits - he doesn't have to log in using his credentials. Supposing the data stored in the cookie is the user ID, then the user can easily change it and log himself as another user.

 

This is very very bad. That's why it is much better to create a hash of the data that is to be stored in a cookie.

 

Actually sensitive data, such as passwords is best to be stored as a one-way hash. When a user tries to log he is not authenticated based on his username and password but on his username and hash of password. Anyway, back to the cookies.

 

If you have a cookie with your user ID set to 26 in your browser, you can simply change it to 27 and it's highly possible you will be logged as another user. However if you have a hash, it's highly improbable that spoofing another user will be a piece of cake.

 

It's also a good idea to encrypt your viewstate using the ViewStateEncryptionMode parameter if you store sensitive data within it.

 

identiy spoofing

 

Eavesdropping attacks.

 

A serious attacker can use certain tools to monitor the communication between your server and the clients. This is not good for you (or your clients). This way the attacker can get hold of everything, cookies, session ID (contained within the ASP.NET_SessionId cookie), and the viewstate. Let alone the get and post values. This way he can easily imitate the user he got all the info from. There's no easy trick to prevent this. You will have to use secure connections.

 

Web is a bad thing considering that everything is sent within it. As a result everything is exposed to attacks. Using secure connection, will minimize the ways an attacker can use against you, but still it won't be easy to close all doors.

 

 

 

Conclusion

 

We have made a trip through the methods an attacker can use against us and how to defend against them. SQL Injections can be blocked by using SqlParameters. Cross-site scripting attacks can be matched by checking the input's type and expected value. We have also seen how someone can imitate an existing user and how a secure connection can help us.

 

Reference

DotNetHints

Δημοσιεύτηκε στις Δευτέρα, 3 Φεβρουαρίου 2014 7:40 μμ από το μέλος k badas :: 1 σχόλια

Abstract classes and interfaces

In this article we are going to talk about abstract classes and interfaces. Both abstract classes and interfaces are a part of .Net's architecture and are not explicit of its web equivalent. They are a way of describing some characteristics a class may have in a way resembling the inheritance model. Yet, though these two may look similar there are a few significant differences and these will consist of the second part of the article.

 

First there was inheritance

 

I guess most developers know what inheritance is. Since a base class and an interface have much in common we'll go through the inheritance to reach the interface. In a few words inheritance is the connection between two classes when one of them gets the other one's characteristics. For example we can use the classes Parent and child.

 

public class Parent

{

    public string Name { get; set; }

 

    public void SetName()

    {

        Name = "Anakin";

    }

}

 

public class Child : Parent

{

}

 

Child inherits the class Parent. That means that a Child object has all the characteristics a Parent object has.

 

For example

 

Parent par = new Parent();

par.SetName();

ResponseLitID.Text = "Parent's name is " + par.Name;

 

Parent's name is Anakin

 

A child object has both a Name attribute and a SetName class

Child ch = new Child ();

ch.SetName();

ResponseLitID.Text = "Child's name is " + ch.Name;

 

Child's name is Anakin

 

 

Inheritance also allows us to hide or override the parent class characteristics. This class has its own SetName class

 

public class HiddenChild : Parent

{

    new public void SetName()

    {

        Name = "Luke";

    }

}

 

HiddenChild hidCh = new HiddenChild ();

hidCh.SetName();

ResponseLitID.Text = "Child's name is " + hidCh.Name;

 

Child's name is Luke

 

 

Abstract classes

 

So far, we have seen examples of basic inheritance applications. However there may be times you do not want to implement the whole of these characteristics at once. That's when we should mark a class as abstract.

 

Here's our new abstract class. There's not much difference between that and the previous Parent method. Actually the only difference is the keyword "abstract".

 

abstract public class AbstractParent

{

    public string Name { get; set; }

 

    public void SetName()

    {

        Name = "Anakin";

    }

}

 

However if we tried to create an AbstractParent object we would get an error stating we can cannot create an instance of the abstract class. That is the way of the compiler to tell us that an abstract class can only be used to create derived classes, not the one itself. So, we should always keep that in mind. An abstract class cannot be used by itself.

 

Now, what if we tried to create a derived class? That would work great and we would get our method.

 

public class AbstractChild : AbstractParent

{

}

 

AbstractChild abCh = new AbstractChild ();

abCh.SetName();

ResponseLitID.Text = "Child's name is " + abCh.Name;

 

Child's name is Anakin

 

In addition to creating an abstract class we can also create abstract methods or properties.  To mark a method as abstract it must be placed within an abstract class and be declared (marked as override) only inside the derived class. If not, we will get a compile time error.

 

So, if we added an abstract method to the AbstractParent class, our example would look like:

 

abstract public class AbstractParent

{

    public string Name { get; set; }

 

   public void SetName()

    {

        Name = "Anakin";

    }

 

    //We may not create body for an abstract class in the base class

    abstract public void SetNewName();

}

 

public class AbstractChild : AbstractParent

{

    //An abstract method must be declared in the derived class

    override public void SetNewName()

    {

        Name = "Leia";

    }

}

 

Child's name is Leia

 

 

Here's what we have here.

First, there is an AbstractParent class marked as abstract. This means that we cannot create an object of that class the way it is, and we have to create a new class (AbstractChild) in order to use it.

Then we created the SetNewName which is an abstract method which we must implement in the AbstractChild class using the override keyword. The SetNewName method is marked as abstract because we want it to exist, yet we do not want to create an implementation in the base class.

 

So, now we know what an abstract class is. However, if you are not familiar with such concepts, you may still be wondering why we may want to turn a simple class into abstract since we can simply override every method we like.

 

The answer is, we do not have to create an abstract class, but we may choose to do so. Suppose you got some derived classes and all of them need to save some values to the session. Instead of creating a new method in each one of them, we can create a method SaveToSession in the base class. However, due to our specifications, each class must store different values in the session. For example class A must store type AA values, while class B must store type BB values and so on. So, the question is: What should the method's body in the base class look like? Should it look like class A, B or any other class? Since we find it difficult to answer we'd better mark the base class and its method as abstract. In that way we ensure that all derived class MUST contain this method.

 

 

Interfaces

 

Now, we know what an abstract class is. An interface is quite a similar term. Consider an interface as an abstract class that contains only abstract elements. As a result an interface can't be instantiated and the derived class (we need to create) must contain source code for all elements implementation.

 

This is an example of an interface

interface IRunner

{

    int speed { get; set; }

 

    string GetName();

}

 

Usually, interfaces are named using the 'I' letter in the beginning, for example IRunner, IDeveloper, IHelper.

 

The interface IRunner contains the int speed property and the GetName method, and based on its name it is created so it contains characteristics that runners have. Since it is an interface we may not create an IRunner object or put the GetName's body inside the IRunner declaration.

 

To use it we have to create a derived class, for example:

public class OlympicRunner : IRunner

{

    public int speed { get; set; }

 

    public string GetName()

    {

        return "I'm an olympic runner.";

    }

}

 

Now we can create an object and use it.

 

OlympicRunner Bolt = new OlympicRunner();

ResponseLitID.Text = Bolt.GetName();

 

The result will be

I'm an olympic runner.

 

 

Keep in mind that all elements within an interface must be declared private. On the contrary, they must be declared public in the derived classes.

 

That's about all you need to know concerning interfaces. Interfaces seem to be quite similar to abstract classes.

If so, why do we need interfaces or, similarly thinking, why do we need abstract classes?

 

The major difference is that a class can inherit only one base class but may inherit as many interfaces as it wants. So, if you had two classes, Bipedal and Mammal, and wanted to inherit both of them on the Human class, I'm sorry to tell you but you can't do that. .Net does not allow that.

 

This brings us to another crucial difference between abstract classes and interfaces. Think of the previous example. Based on basic biology knowledge we have, should the Human class inherit both Bipedal and Mammal class? Actually, no. The correct architecture should be that Human's base class should be Bipedal and Bipedal's base class should be Mammal, as Human contains Bipedal elements and Bipedals contain Mammal elements. However a Bipedal object could also contain elements from the Bird class. Hmmm, that makes it more complicated. Which class should the Bipedal class derive?

 

The answer is simple. Bipedal should not be a class, but an interface instead. Actually Bipedal describes something that uses two legs to walk, so we could as well use the interface IBipedal. Keep that simple rule in mind.

 

A base class represents what a derived class is. An interface represents what abilities it has.

 

In the previous example, Human is a Mammal, so this is the base class. On the contrary, even though Human is a Bipedal, it would have been more accurate to say that Human has the ability of bipedalism, thus showing us that we should create the interface IBipedal.

 

Let's see how interfaces work in .Net. A well known .Net interface is IEnumerable. Practically, a class that implements the IEnumerable is granted the ability to loop over its elements, in other words, it can use the foreach keyword. IEnumerable, located in the System.Collections library, contains the GetEnumerator method which returns an IEnumerator interface object. IEnumerator contains the MoveNext method which is used to move to the next element.

 

Since IEnumerable is an interface, the following statement

IEnumerable intCollection = new IEnumerable ();

would return a compiler error, as expected. However, according to what we said, the List class (which implements the IEnumerable interface) can create objects that can use the GetEnumerator method.

 

        List<int> intList = new List List<int>();

        foreach (int i in intList)

            //do sth

            ;

 

Reaching the end of this article, consider this as one more difference between an abstract class and an article, which may help you decide which one you want to use. An abstract class may contain attributes that are not abstract, while this is not an option to an interface. Remember that an interface can contain nothing more but the declaration of its attributes. So if you want to create some default behavior, then you may choose an abstract class.

 

 

Summary

 

Abstract classes are a special kind of class which cannot be used on their own but rather tell their derived classes what attributes they should contain. Abstract classes may contain more than just a declaration of their attributes. In contrast, interfaces, though they look much like abstract methods, may contain nothing more than declarations. Furthermore a class may implement more than one interface but may use only one base class.

 

 

Reference

dotnethints.com

 

Περισσότερες Δημοσιεύσεις « Προηγούμενη