Δημοσιεύτηκε στις Τετάρτη, 19 Ιουλίου 2017 9:51 πμ από το μέλος k badas :: 0 σχόλια

Enumerations, bitwise operators and flags

Enumerations are a simple and efficient way to deal with a set of values. The most common way to use an enumeration is to use its values separately. There are however times when we want to use a combination of the enumeration's values. In that case we can use bitwise operators. To make things easier, we can also use flags.

 

 

Enumeration

Let's start using a simple enumeration example. Enumerations are structs consisting of a set of values the type can be assigned. So let's use an enumeration of payment methods. Here's the enumeration.

 

public enum PaymentMethods

{

    None = 0,

    Cash = 1,

    Cheque = 2,

    CreditCard = 3

}

 

We can now use this enumeration to connect PaymentMethod values with their integer representation. For example

 

int creditCard = 3;

PaymentMethods creditCardMethod = ( PaymentMethods)creditCard;

or

int creditCard = (int) PaymentMethods.CreditCard;

 

It is quite easy to switch between the enumeration and its numeric equivalent and use it anyway we want. Either in order to set the value to a select item or to store it in a database table. This method seems to be ok for let's say an e-shop where the customer chooses a product and selects a method to pay. However, that wouldn't work in case of a crm system where the customers wished to have more than one way of payment. For example, some client might wish to choose as payment method Cheque or CreditCard.

 

Bitwise Operators

In order to choose multiple values rather than a single one, we can use bitwise operators. In other words we can use an enumeration's binary value instead of the integer representation. This is called Flag Enumeration, even though using the Flag keyword is not mandatory.

 

For example, in the PaymentMethods enumeration each value's binary representation would be

Name        Integer       Binary

None             0             000

Cash             1             001

Cheque         2             010

CreditCard    3             011

 

Now, we could change the enumeration's values so they were all represented by powers of 2.

 

 

public enum PaymentMethodsAdvanced

{

    None = 0,

    Cash = 1,

    Cheque  = 2,

    CreditCard = 4

}

 

 

In that case the previous table would look like

Name         Integer     Binary

None              0           000

Cash             1           001

Cheque          2           010

CreditCard     4          100

 

 

It's pretty clear that all we have said so far concerning PaymentMethods applies to PaymentMethodsAdvanced as well. Now let's see what choosing a combination of these values would look like.

 

var cashOrCheque =  PaymentMethodsAdvanced.Cash |  PaymentMethodsAdvanced.Cheque;

var cashOrCreditCard =  PaymentMethodsAdvanced.Cash |  PaymentMethodsAdvanced.CreditCard;

 

Name                        Integer     Binary

None                             0           000

Cash                             1           001

Cheque                         2           010

CreditCard                    4           100

cashOrCheque              3           011

cashOrCreditCard         5         101

 

 

This way we can represent multiple options by using an option that is created on the fly.

 

In order to check if a variable contains an option we can use the & operator.

 

int paymentMethodAdvancedIntValue = 3;

var paymentMethodAdvancedValue = ( PaymentMethodsAdvanced)paymentMethodAdvancedIntValue;

bool isCash = (paymentMethodAdvancedValue &  PaymentMethodsAdvanced.Cash) ==  PaymentMethodsAdvanced.Cash; //true

var cashOrCheque =  PaymentMethodsAdvanced.Cash |  PaymentMethodsAdvanced.Cheque;

bool isCashOrCheque = (paymentMethodAdvancedValue & cashOrCheque) == cashOrCheque; //true

 

 

Instead of using logical operators we can use the HasFlag method. HasFlag works in a similar way but it makes things easier to read and use.

 

int paymentMethodAdvancedIntValue = 3;

var paymentMethodAdvancedValue = ( PaymentMethodsAdvanced)paymentMethodAdvancedIntValue;

bool isCash = paymentMethodAdvancedValue.HasFlag( PaymentMethodsAdvanced.Cash); //true

var cashOrCheque = PaymentMethodsAdvanced.Cash |  PaymentMethodsAdvanced.Cheque;

bool isCashOrCheque = paymentMethodAdvancedValue.HasFlag(cashOrCheque); //true

var cashOrCreditCard =  PaymentMethodsAdvanced.Cash |  PaymentMethodsAdvanced.CreditCard;

bool isCashOrCreditCard = paymentMethodAdvancedValue.HasFlag(cashOrCreditCard); //false

 

 

One thing to keep in mind is how the 0 value works; the one called None in our example. Suppose we use HasFlag or the & operator (which actually end up in the same thing). Here's how things might get tricky.

 

var cashOrCheque =  PaymentMethodsAdvanced.Cash |  PaymentMethodsAdvanced.Cheque;

bool isNone = cashOrCheque.HasFlag( PaymentMethodsAdvanced.None);

 

isNone is true. Actually everything you compare to None returns true. Why would you say this is? It all ends up to this.

bool isNone = (cashOrCheque &  PaymentMethodsAdvanced.None) ==  PaymentMethodsAdvanced.None;

3 & 0 == 0

This expression is always true regardless of the first value. So this is not the right way to tell if the value is None. To do so, we should do a direct comparison.

bool isNone = cashOrCheque ==  PaymentMethodsAdvanced.None;

 

 

One last thing: remember how we created our enumeration?

public enum PaymentMethodsAdvanced

{

    None = 0,

    Cash = 1,

    Cheque= 2,

    CreditCard = 4

}

 

The exact same thing can be done using bit shifting which can make things less complicated in case of long enumerations.

public enum PaymentMethodsAdvanced

{

    None = 0,

    Cash = 1 << 0,

    Cheque= 1 << 1,

    CreditCard = 1 << 2

}

 

 

 

Using Flags

It is a strange thing that many people tend to think that you need to use the Flags attribute in order to use bitwise operators. That is not true. We can use Flags however, to make things easier for us developers to debug or to display selected values.

 

To use Flags the only thing we need to do is to place the Flag keyword before the enumeration.

[Flags]

public enum PaymentMethodsFlags

{

    None = 0,

    Cash = 1,

    Cheque = 2,

    CreditCard = 4

}

 

So, if we had an enumeration with Flags as mentioned and another one without Flags, like this

public enum PaymentMethods

{

    None = 0,

    Cash = 1,

    Cheque = 2,

    CreditCard = 4

}

 

using the debugger we would get the following results

var cashOrCheque =  PaymentMethods.Cash |  PaymentMethods.Cheque; //Debugger says 3 

var cashOrChequeFlags =  PaymentMethodsFlags.Cash |  PaymentMethodsFlags.Cheque; //Debugger says Cash | Cheque 

 

Similarly

string cashOrCheque = ( PaymentMethods.Cash |  PaymentMethods.Cheque).ToString(); //Equals to "3" 

string cashOrChequeFlags = ( PaymentMethodsFlags.Cash |  PaymentMethodsFlags.Cheque).ToString(); //Equals to "Cash, Cheque" 

 

 

 

Summary

We can use bitwise operators to combine multiple values from one single enumeration. The enumeration needs to contain powers of two as values. To compare such values we can use logical operators or the HasFlag method. In addition, we can use the Flags attribute to make debugging or parsing enumeration values easier.

Reference – DotNetHints

Δημοσιεύτηκε στις Κυριακή, 25 Ιουνίου 2017 6:34 μμ από το μέλος k badas :: 0 σχόλια

Getting random values

You do not have to be working on some gambling project in order to request for a random number. Things like that happen all the time. Either you may need to pick a random product to show out of a list or you may want to present some results randomly ordered. Anyway, getting a random number is something you will need to do from time to time. To get a random number we may use the Random or the RNGCryptoServiceProvider class. We are going to find out what is the difference between them and talk about what makes a random number.
 
 

Randomness

Let's start with the basics. What makes a random number? A number is considered random when there is no method to predict what that will be before it is presented. You may think of this as something obvious, however it is not.
 
Let's say someone asked you to pick a number between 1 and 10 and you picked 5. Why would that be? Maybe that is because you like number 5, or you like the fact it is located in the middle of the 1 to 10 range, or because of a subconscious thought of the 5 euro note you were holding a while ago, or well, pretty much anything. Not being able to predict the number you are going to pick, makes it quite a random guess.
 
However, no matter why you have chosen number five, there will always be some reason why you picked that number. A person may be able to locate that reason and from that moment on be able to predict what number you are going to pick at given circumstances If the value of the cause and the way it affects the result number is easy to guess, this makes your number pseudo-random.
 
The value of the reason that causes the number to be selected is called seed.
 
So a random number will never be 100% pure random. However, the less easy to compute the seed, the more random it will be. In case you've been wondering what all this fuss is about, that's because Random class is far more pseudo-random than RNGCryptoServiceProvider. And we are now going to see the reason why.
 
random dice

Using the Random class

 
To use the Random we first have to create an object instance like this

Random rnd = new Random();

 
 
After that, there are a few handful methods we can use to get our random values. For example
//Get a random integer greater than or equal to 0
int random = rnd.Next();
//Get a random integer greater than or equal to 0 and less than 100
int random = rnd.Next(100);
//Get a random integer greater than or equal to -10 and less than 100
int random = rnd.Next(-10, 100);
//Get a random floating point number greater than or equal to 0 and less than 1
double random = rnd.NextDouble();
//Get a random 32-bit integer than or equal to 0
double random = rnd.NextDouble() * Int32.MaxValue;
 
By using the Next method (or a similar one) we get a new random value generated by our Random object.
 
Now, there are two ways to instantiate a Random object. One is the default one we used earlier
Random rnd = new Random ();
The other one is using a seed of our own by setting an integer argument to the constructor like that.
Random rnd = new Random(5);
 
What should be taken into account here is that Random objects initialized using the same seed will produce the same results.
Random rnd = new Random(5);
Random rnd2 = new Random(5);
int random11 = rnd.Next();
int random21 = rnd2.Next();
int random12 = rnd.Next();
int random22 = rnd2.Next();
//random1 equals random21 and random12 equals random22
 
So Random will produce no actual random results, rather it is considered a pseudo-random method since its integer seed is responsible for all results.
 
So, how about using the default constructor?
Random rnd = new Random();
In case we feed no seed to Random, it gets its own value from the CPU-clock time value. In that case, things are not as bad as when we use our own seed, since time values can vary. Still it is not considered actual random since, as mentioned, some easy to guess seed determines all results. Actually if you find out a few results created, you can even predict what the next result will be even before it pops up.
 
Also, take a look at the following example.
 
var randoms =new int[5];
for (int i = 0; i < randoms.Length; i++)
{
     Random rnd = new Random();
     randoms[ i ] = rnd.Next();
}
 
Since each of my loops takes a tiny amount of time to complete, all rnd objects we create use the same seed. As a result all values in the randoms array are equal. To avoid this we should have created one Random object and then use Next on the loop like this.
 
var randoms = new int[5];
Random rnd = new Random();
for (int i = 0; i < randoms.Length; i++)
     randoms[ i ] = rnd.Next();
 
You may now be wondering, is there any point in using the constructor that takes a seed, if it makes things far less random than the default constructor does? Well, not much, but you can use it, if you want to test your random methods more than once so they will return the same values every time.
 
 
So, using Random is ok when we need a few random values that we do not mind if they are not actually random. And this applies perfectly most of the times. Actually, I've never found myself in need of more than that. However there are times we do need something more. This is where RNGCryptoServiceProvider comes into play.
 
random casino
 

Using the RNGCryptoServiceProvider class

RNGCryptoServiceProvider located in the System.Security.Cryptography will implement a cryptographic Random Number Generator using the implementation provided by the cryptographic service provider. What is the meaning of all that? Simply put, RNGCryptoServiceProvider uses OS Entropy as a seed. That OS Entropy is a value produced by things like keyboard timings, thermal temp, sound etc so it can be really hard to predict. As a result this makes it quite a random value generator.
 
We can use RNGCryptoServiceProvider like this.
 
using (var rng = new RNGCryptoServiceProvider())
{
     byte[] bytesArray =new byte[5];
     rng.GetBytes(bytesArray);
     int randomvalue = BitConverter.ToInt32(bytesArray, 0);
}
 
Even though RNGCryptoServiceProvider generates random results, using it instead of Random all the time is not a good idea since it is slower. If you do not wish to go for totally random values, stick to the simpler Random class.
 
 
It is also worth mentioning that the random number generators we described provide random (or pseudo-random numbers). However, randomness should not be mistaken with uniqueness. That means that a random generator does not necessarily produce unique numbers, even though it may be quite unusual to get two equal numbers one after the other in a sequence. To face the uniqueness problem we can use GUIDs which on the contrary are meant to be unique but not random. You can read this article of mine concerning GUIDs if you wish to learn more.
 

Summary

To generate random values we can use either the Random or the RNGCryptoServiceProvider class. Random is actually a pseudo-random generator based on its initialization seed. On the other hand RNGCryptoServiceProvider creates actual random values.
Reference – DotNetHints
Δημοσιεύτηκε στις Κυριακή, 11 Ιουνίου 2017 7:32 μμ από το μέλος k badas :: 0 σχόλια

Yield and iterator methods

All around C#, there are over a few dozen keywords. One of them, which is rarely used and is sometimes misunderstood, is yield. However, if used properly, yield can help in optimizing your code. Let's take a look at how it works.
 

What does yield do?

 
Let's get to what yield does using an example. We are going to create a method that returns a Fibonacci sequence. You have probably heard what Fibonacci numbers are, from your first for loop classes. So, a Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers. Well, this may not be the exciting way you would expect to implement yield, but I guess this will make things easier to grasp. So let's write the following code.
 
 
string fibonacciSequence = "";
foreach (int f in FibonacciEnum(10))
     fibonacciSequence += f + " ";
 
The following method returns a Fibonacci sequence.
 
private IEnumerable<int> FibonacciEnum(int n)
{
     List<int> fibonacciEnum = new List<int>();
 
     int a = 0; int b = 1; int sum = 0;
     for (int i = 0; i < n; i++)
     {
          fibonacciEnum.Add(a);
          sum = a + b;
          a = b;
          b = sum;           
     }
return fibonacciEnum;
}
 
So, we just created a method that returns an IEnumerable of integers by adding every number to a list. We call the method, get that IEnumerable and then loop through it and create the following string.
 
0 1 1 2 3 5 8 13 21 34
 
Ok, let's implement the same method using yield and see what it looks like.
 
 
private IEnumerable<int> Fibonacci(int n)
{
     int a = 0; int b = 1; int sum = 0;
     for (int i = 0; i < n; i++)
     {
          yield return a;
          sum = a + b;
          a = b;
          b = sum;
     }
}
 
This is what implementing yield looks like. You can tell both methods look alike. It's like we removed our list object and use yield return to add one integer at a time to our IEnumerable on every iteration. What's even more confusing is that the result string we get is the same.
 
0 1 1 2 3 5 8 13 21 34
 
So, is there any reason to use yield at all?
 
The answer is yes. Actually using yield is totally different that using a typical method. The answer would be easier to show if you could place a breakpoint within the Fibonacci method. Then you would notice that the method is not executed at all when called. On the contrary it will start executing when it is needed, in other words, when the for loop in the caller method begins. At that moment the Fibonacci method starts executing but stops as soon as it reaches yield return. When it does, code returns to the outer for loop and will get back to the method the next time an IEnumerable element is requested. The following picture will make things clearer.
 
 
As you can see, yield allows us to move in and out from our method but the method does not initialize. Its variables store the same values the way they were during last iteration. It's like the execution is paused, saved and then resumed from the save point later on. Repetitions will go on until we stop requesting elements or there are no more elements to return.
 
Yield can be used in combination with return on a method or a get accessor that returns an IEnumerable or IEnumerator. Using yield the method turns into an iterator. In other words the method is turned into a stateful machine which calculates each element of the IEnumerable only when needed. The compiler does all that transformation hard work here. All you have to do is use yield.
 
 
Before moving on, we should mention yield break. This is another way to end the iteration loop on our own. Suppose we do not want to compute Fibonacci numbers forever and ever, we can insert yield break, like this.
 
private IEnumerable<int> Fibonacci(int n)
{
     int a = 0; int b = 1; int sum = 0;
     for (int i = 0; i < n; i++)
     {
          if (i < 9)
          {
               yield return a;
               sum = a + b;
               a = b;
               b = sum;
          }
          else
               yield break;
     }
}
 
 
This will end our method on the 9th iteration.
 
0 1 1 2 3 5 8 13 21
 

Using yield

 
Let's move on to another example. I'm not saying that Fibonacci numbers are boring but, well, I personally never had to use them since first year at school. So let's use sights that people visit on trips instead.
 
 
Here's a Sight class
 
public class Sight
{
     public int Id;
     public int CityId;
     public string Title;
 
     public Sight(int id, int cityId, string title)
     {
          Id = id;
          CityId = cityId;
          Title = title;
     }
}
 
Here's a list so we can have some something to work with
   
public List<Sight> sightsList = new List<Sight>() { new Sight(1, 1, "Eye Of London"), new Sight(2, 1, "Westminster Abbey"), new Sight(3, 2, "Louvre"), new Sight(4, 1, "Tower Bridge"), new Sight(5, 2, "Notre-Dame") };
 
 
And finally, here's the method that returns sights that are located within a city with a given Id, or return all sights in case cityId is 0.
 
private IEnumerable<Sight> GetSightsByCategoryId(List<Sight> sights, int cityId)
    {
        foreach (Sight sight in sights)
        {
            if (sight.CityId == cityId || cityId == 0)
                yield return sight;
        }
    }
 
 
Let's call GetSightsByCategoryId in a similar way we did the Fibonacci numbers.
 
string sightSeeing = "";
foreach (Sight sight in GetSightsByCategoryId(sightsList, 1))
     sightSeeing += sight.Title + " | ";
 
 
 
You can probably guess how things work, but let's give it a try together. At first GetSightsByCategoryId will return Eye Of London, then Westminster Abbey. On next call it will ignore Louvre and move on to Tower Bridge. After that ,it will move on to the final two iterations trying to find more Sights but since there are no more that match, will return nothing more.
 
The result will look like that.
 
Eye Of London | Westminster Abbey | Tower Bridge |
 
 
The same pattern would be followed if instead we had used
 
string sightSeeing = String.Join(" | ", GetSightsByCategoryId(sightsList, 1).Select(x => x.Title));
 
 
Needless to say that yield does not need to show up only in methods that contain iteration loops. For example the following method is totally valid.
 
    private IEnumerable<Sight> GetSights()
    {
        yield return new Sight(1, 1, "Eye Of London");
        yield return new Sight(2, 1, "Westminster Abbey");
    }
 
 
Now let's add some LINQ in our recipe.
 
string sightSeeing = GetSightsByCategoryId(sightsList, 1).First().Title;
 
This will enter GetSightsByCategoryId only once, since there is no need to get more elements. It will return
 
Eye Of London
 
Eye Of London - Yield
 
string sightSeeing = GetSightsByCategoryId(sightsList, 0).Last().Title;
 
This will loop through all elements of sightsList till it gets to the last one. In contrast to the Fibonacci numbers there actually is no point in searching every single element since we know that the last element of the list has nothing to do with the previous ones. So this might not be a perfect case to use yield. Anyway, the result would be
 
Notre-Dame
 
string sightSeeing = GetSightsByCategoryId(sightsList, 1).First().Title + " | " + GetSightsByCategoryId(sightsList, 1).Last().Title;
 
You may have probably guessed that the result is
 
Eye Of London | Notre-Dame
 
notre-dame-yield
 
I know, it's not much different than the previous one and, well, if you understand how yield works it's always the same pattern. What's more interesting is this. How many iterations do you think took place in order for the previous statement to be completed? If you guessed the same as the number of the list elements, you would be wrong. The thing is that a method containing yield is always computed from the beginning whenever it is called.
 
If for example we had
string sightSeeing = GetSightsByCategoryId(sightsList, 1).Last().Title + " | " + GetSightsByCategoryId(sightsList, 1)Last().Title;
this would require iterations twice the size of the list.
 
If you are familiar with Data contexts this is probably not the first time you've heard of such things. Actually LINQ is based on yield. You may have already noticed that GetSightsByCategoryId(sightsList, 1) is no different than sightsList.Where(x => x.CityId == 1). As a result yield carries along all pros and cons of LINQ.
 

Why should I use yield?

 
Keep in mind that yield takes effect only in sequences like enumerators. So we may need to use it only in case we want to return a collection of objects.
 
Imagine you want to do some processing with a lot of elements contained within a sequence (that sequence could be anything, for example a database table or a group of files) but you want to process them one at a time. There is no point in wasting time and memory into loading all elements first and process them later. Instead you can get the first one, do what you want with it and then move to the next one. And so on. You can use yield to obtain lazy loading.
 
Otherwise suppose you have thousands of database records but you only need a few of them. Why would you want to fetch them all at the first place? Use yield instead.
 
Or maybe you want to get a sequence like the Fibonacci we talked about earlier. There surely is no end to that sequence, so you may want to give yield a try and get the sequence little by little.
 
Accessing one item at a time can make things less complicated if something goes wrong. Only the items currently in use need to be examined instead of the whole list.
 
Finally think of a sequence source bound to continuous changes. Creating a list of the objects could contain objects that might have changed from the time the list is loaded till we actually use them.
 
So, yield can be of help in certain situations but offers nothing in other cases. For example if we do want to loop through all elements of a sequence, there is no point in using yield. Or if we want to use the returned elements more than once. In that case data we ask for will be computed from the begining every time we need them. Transforming a method into an iteration and moving through all its objects takes time. Much more time than creating a list would take. So, whenever you think using yield would do good, remember to test your code afterwards so it doesn't backfire. Anyway, keep in mind that if there is no actual reason to use yield, then don't use it.
 

Conclusion

Yield can be used to create an iterator out of a simple method. This can help us access the method's elements one at a time, whenever we need them instead of getting them all at once and then process them. This way, yield can help us when we want to get lazy loading; still it can be helpful in other cases as well. However we should be careful cause using yield is not always as good an idea as it may seem.

 

Reference – DotNetHints

Δημοσιεύτηκε στις Δευτέρα, 21 Νοεμβρίου 2016 9:04 μμ από το μέλος k badas :: 0 σχόλια

Session in ASP.NET MVC applications

Session is a simple and nice way to store info in memory and has been used in ASP.NET for a long time. Since MVC came out, there were many people out there saying that session should be abandoned and replaced by other methods while others said that there is no problem using session the way we used to. As this may confuse developers that are not highly experienced in MVC, let's see what actually happens here.
 

Before MVC

Web Forms have been the basic model for a developer who has been working on ASP.NET, for a long time. Web Forms was the result of Microsoft's efforts to create a web application based on windows standards. By default, web is stateless. If I send a request, this is supposed to be a request of its own, no matter what the history between me and the web server has been. To use a RESTful model, info should be sent using GET, POST requests, cookies etc. However, this model did not resemble windows applications. In order to avoid this, developers started using state management tools, like session for example.
 
If you are not so sure what session is, you can take a look at this older post of mine. Now, the thing is that as applications became more and more complex so did the way we used session. People had to be extra careful that nothing bad happened to their session.
 
session_mvc_aspnet

After MVC

Then MVC was introduced and people who had been watching Web Forms growing all these years along with the troubles they carried, felt like something new, pure and RESTful could happen. These people felt like in order to achieve this, all the bad stuff Web Forms contained should be sent away, session being one of them.
 
So, using Session in MVC projects is no different than using session in Web Forms projects. The same problems that showed up in Web Forms are still right there. Then let's take a look at a few of them and see what all the fuss is about.
 
  • Session by default is stored in the IIS and uses its memory. This means that if IIS needs to recycle the application pool or memory is not enough, the session will be gone. There are other places to store session e.g. the Sql server; however this is not much different than storing the info in database tables in the first place.
  • Session will expire after a while, depending on your timeout value. If you choose to increase timeout carelessly, you may end up consuming much more memory than you thought you would.
  • If you are using load balancers (and most enterprise website do so) you need to make sure that a user will get the same response no matter which server will serve him.
 

Conclusion

Using session on an MVC project is no different than doing so in a Web Forms project. Since choosing between using session or other ways of storing data depends on your case and your specs, there is no reason why you should not do it. If you believe that using session will do no harm to your project you may go for it, no matter what the project type is.
Reference – DotNetHints
Δημοσιεύτηκε στις Κυριακή, 29 Μαΐου 2016 6:28 μμ από το μέλος k badas :: 0 σχόλια

Boolean types - To null or not to null?

Boolean types are quite common to be found within a database. Alike many other types there are boolean and nullable boolean types. Simple boolean types consist of two values: True and False. Nullable ones offer null as a third choice. So, do we really need this third option in our database or source code and if so how should we deal with it?
 

Nullable types

Nullable bool is not the only type that accepts null values. For example we got nullable integers and nullable DateTimes. So, what is the meaning of null? To put it simply null means we have no idea what the value is.  So if, you got a nullable int, its values could be 10, 100, 0 or null. Now, 10 and 100 are standard values. So is 0, even if it actually refers to the number of zero objects. However null tells us that we do not know if the value is any one of these. Supposing int refers to the Bahamas' number of citizens. Setting null value to that variable does not imply that the Bahamas do not exist or have no citizens or that there is no record of that number somewhere out there. What it means is that at that given moment we do not know what the number is and this is quite different from using 0 as that would tell that there are no citizens at all.
 
The same thing goes for the DateTime. Using null as a DateTime value is like saying that we do not know when something happened. A person who is not really fond of history classes might respond "I have no idea at all" when asked when the French Revolution took place while another person might answer that it took place at 1789.
 
The same thing goes for boolean types. When asked whether it rained all day yesterday or not you could answer yes or no, but you could also answer "I don't know" (null) if you were all day long inside your no-windows office trying to finish that project that had to be delivered no matter what.
 
bahamas-bool

Nullable boolean types on database

By now you may be wondering why I'm writing this article concerning nullable boolean types and not nullable types in general. The reason is, common types such as integers and DateTimes I mentioned earlier can get a lot of different values. However a boolean type has only two values and by adding an extra one we move on from binary to three-value logic. So even though all nullable types share common concepts, this case makes things a little more different.
 
Imagine you create a table named Orders. This table may contain two columns: DateCreated and DateDelivered. When creating an order row you know what the DateCreated is (the date the Order is created) but you have no knowledge of when the order is going to be be delivered. Keep in mind DateDelivered does not represent the date the order is expected to be delivered, but the date the order was actually delivered. As a result this column should be addressed as nullable.
 
Now, let's see how boolean types fit in. Suppose the table requires one more column called IsPriorityOrder and by default an order is not set as having priority unless assigned to. Should that be a nullable boolean (actually the exact SQL server type name is bit) or just a plain boolean? The question that needs to be answered is "Could there be a case where we will not know if IsPriorityOrder is either true or false?" . If the answer is true, go for the nullable, otherwise go for the boolean.
 
In the case of IsPriorityOrder, if all orders by default get false value, which can then be altered to true if needed, then the answer is boolean. This case does not prove to be much difficult. However, suppose in the same scenario, that there is no way to know what the default value should be (there are as many priority as non-priority orders) and that after a person creates an order, there is some other person who gets all orders that have no IsPriorityOrder value in order to add one to them. How would you get all such orders, if both these and the ones that have verified false value look the same? Of course, using a nullable type is not the only way to move on. I am just trying to point out that in order to choose between nullable and not nullable bools you need to pay extra attention to where you want to get (as goes on with everything concerning database actually).
 
Let's do one more column. We add a column called HasPositiveReview. In this case using a simple bool type would make thinks complicated. Sure you can use it if you want, and say for example that all records get by default HasPositiveReview false value. Now when the order is completed and we get the review we can set the value to true if we want to. However, imagine you are asked for a review mentioning how many orders contain false reviews. Now you have to find all orders having false HasPositiveReview and add some extra check to avoid the ones that have not yet been set (check if DateDelivered is null for example) while in the case of nullable bool all you had to do was check the HasPositiveReview value for false.
 
Personally, I prefer solutions that make things clearer. The ones that wil make things easier for some other person (or yourself after a while) to comprehend how things work. However, since there are people who prefer to try out custom solutions, you can always choose the method you want, just make sure that it won't cause you extra trouble in future.
 
So the thing is, if you do need an extra third case, apart from true or false, use nullable boolean. If not, don't use it just in case there might be a time in future when you will need a nullable boolean, as nullable types are more complex than non-nullable ones and might cause trouble.
 
For example, keep in mind that null is neither false nor true or anything else. Null is nothing. That's the reason when we write a select query the correct syntax is
SELECT * FROM Orders WHERE IsPriorityOrder IS NULL
while the following query
SELECT * FROM Orders WHERE IsPriorityOrder = NULL
will not work properly.
 
bahamas bool

Nullable types and C#

Nullable types are different from their non-nullable equivalent. They are actually instances of the System.Nullable<T> struct. Using the '?' symbol after a type, is nothing more than a shortcut to the nullable type. Using nullable types when not needed, will make you take extra actions.
 
Nullable types, being different, may not directly be used with non-nullable types. So they contain the bool property HasValue. Checking that property, is similar to testing your nullable value for null. After that you can get its non-nullable type value by using the Value property. Here's what it looks like in case of bool types (it really makes no difference any type you choose).
 
bool nonNullableType = false;
bool? nullableType = null;
 
if (nullableType.HasValue)
//Check for if(nullableType != null) if you prefer
     nonNullableType = nullableType.Value;
     //You could also use nonNullableType = (bool)nullableType;
 
In case the bool? contained null value and the HasValue test was omitted, an InvalidOperationException would be thrown.
 
As you can see, using nullable types may cause bugs, which would have been avoided by non-nullable types, to show up. Take the following example. Even though bool types have no such problems, greater than and lower than operators will not work as expected when comparing nullable types. Comparing with null will return false; and that makes perfect sense since we can't tell what a value we don't know has to do with a value we do know. Look at the following example to see how things can get complicated in the third case where lower than returns false while not greater than returns true.
 
int? i = 4;
if(i < 5)
     ; // true
if(i > 5)
     ; // false
if(!(i > 5))
     ; // true
 
int? i = null;
if(i < 5)
     ; // false
if(i > 5)
     ; // false
if(!(i > 5))
     ; // true
 

Summary

Nullable types are used to insert null, as an extra option, when we don't know what the value is. Nullable Boolean types create a three-value logic type. Nullable values are better to be avoided, if not necessary, to avoid possible bugs as well.
Reference – DotNetHints
Δημοσιεύτηκε στις Δευτέρα, 11 Απριλίου 2016 8:42 μμ από το μέλος k badas :: 0 σχόλια

Shorten your URLs using goo.gl

Shortened URLs have slowly turned into one of the latest trends. Even though it's been about 15 years they've been helping people having difficulty with limited character messaging applications and SMS, social networks sharing such limitations have caused some major increment in their use. We are going to see what shortened URLs are, and how we can create our own, using goo.gl API.
 

What is a shortened URL?

 
A shortened URL is a URL that redirects to the same address as the one requested. For example you can use goo.gl (Google's URL shortener service) to create a shortened URL by visiting https://goo.gl/ and placing the URL you want to shorten. If you place http://dotnethints.com/  you get http://goo.gl/5nIcLC.
 
Now, if you hit that new address on your browser you will head to that URL shortener's company site. The original URL will be found and you will be automatically redirected to your destination. Keep in mind that shortened URLs are supposed to last forever.
 
So, we may use shortened URLs when we want to minimize the number of characters contained within our URL. Shortened URLs can also be used if we want to hide the address our original URL is pointing to from the person to click it. This is the reason many spammers choose to use URL shortening.
 
There are many URL shortening services out there, including bitly and tiny URL. goo.gl, the service supported by Google, is the one we will be using in this article.
 

Using goo.gl

goo.gl
 
As mentioned earlier, to use goo.gl a single person can use the service in the https://goo.gl/ page.
 
A developer can also make use of the goo.gl API to create a JSON request containing the original URL and get a JSON response containing the shortened URL.
 
To use the goo.gl API a developer needs to have an API key. You can get a key in this page
 
Now that we have our key, we need to create our request to https://www.googleapis.com/urlshortener/v1/url?key=my_API_key and deal with the results so we get the shortened URL.
 
To accomplish this we can use the following method:
 
 
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=my_API_key");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
 
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
   string json = "{\"longUrl\":\"" + url + "\"}";
   streamWriter.Write(json);
}
 
We create a POST request containing a JSON object with a longUrl element. That is the original URL we want to shorten.
 
Then we will get a JSON response containing a serialized object (in the form of the UrlShortener class we create) containing three elements: kind, id and longUrl.
 
kind  is the kind of response we get eg urlshortener#url
longURL is the original URL we want shorten
id is the shortened URL.
 
    private string GetShortenedURL(string url)
    {
        var shortenedURL = url;
 
        //Create the request
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=my_API_key");
       httpWebRequest.ContentType = "application/json";
       httpWebRequest.Method = "POST";
 
      //Add longURL
      using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
      {
         string json = "{\"longUrl\":\"" + url + "\"}";
         streamWriter.Write(json);
      }
 
 
 
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            //Deserialize response
            var responseText = streamReader.ReadToEnd();
            var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            jsonSerializer.MaxJsonLength = 2147483647;
            UrlShortener shortener = jsonSerializer.Deserialize<UrlShortener>(responseText);
 
            shortenedURL = shortener.id;
        }
 
        return shortenedURL;
    }
 
    private class UrlShortener
        {
            public string kind;
           public string id;
           public string longUrl;
        }
 
 
For example if I used the code above to ask for the http://dotnethints.com/ shorten URL, I would get the following JSON
{
"kind": "urlshortener#url",
"id": "http://goo.gl/RWZBj0",
"longUrl": "http://dotnethints.com/"
}
 
Since a serialized JSON is no more than a string we can also get its id by using string methods, but I personally find this way to be a better one.
 

Summary

Shortened URLs are URLs that can be used in place of the original longer ones to minimize their length. There are many services we can use to create a shortened URL, goo.gl being one of them. We can either visit goo.gl's home page to create shortened URLs on the fly or use the goo.gl API to create JSON requests and get responses containing the info we want.

Reference

DotNetHints

Δημοσιεύτηκε στις Κυριακή, 28 Φεβρουαρίου 2016 11:38 πμ από το μέλος k badas :: 0 σχόλια

Shallow and deep copying objects

 

Working as a developer I have created quite a lot of objects. Most of them were unique. There were some of them, however, that were created by copying already existing objects. C# provides us with a few techniques to accomplish this, keeping in mind whether we want to create a copy that keeps all data the prototype had, or how to deal with the referenced types contained within that object.

Shallow and deep copies

A way to understand things better is to create a class called Book. What we're going to do, is try to copy Book objects. Here's the class.
 
public class Book
{
    public string Name { get; set; }
    public double Price { get; set; }
 
    public Writer Author { get; set; }
 
public Book(string name, double price, Writer author)
    {
        Name = name;
        Price = price;
        Author = author;
    }
}
 
public class Writer
{
    public string Name { get; set; }
}
 
Book class contains three parameters: Name, Price  and Author. Author is a Writer; a class that contains only one parameter; string Name.
 
Book book = new Book("The Gods Themselves", 7.5, new Writer { Name = "Isaac Asimov" });
 
We have just created a Book object.
 
The most straightforward way to create a copy is a new constructor that gets the old object and creates the copy.
 
public Book(Book book)
{
     Name = book.Name;
     Price = book.Price;
     Author = book.Author;
}
 
Book bookCopy = new Book(book);
 
And this is our brand new copy. Let's change something shall we?
 
bookCopy.Name = "Out Of The Silent Planet";
 
After that command, book's name is The Gods Themselves and bookCopy's name is Out Of The Silent Planet. However since Out Of The Silent Planet is written by C.S.Lewis we should also change the author name.
 
bookCopy.Author.Name = "C. S. Lewis";
 
Done. So, right now we got two books. Asimov's The Gods Themselves and Lewis' Out Of The Silent Planet. Actually... no we don't. At the moment both books seem to be written by Lewis. Why is that? That is because when we created our copy, we created a fresh copy of Name, Price and the reference to Asimov. Not the Writer itself. As a result changing the referenced Writer from our copy, we change the value the original object is pointing to as well.
 
A copy that works this way is called a shallow copy. Could we change the constructor somehow so it creates a copy of the author instead of a copy to the reference? Yes, we can. All we need to do is:
 
public Book(Book book)
{
     Name = book.Name;
     Price = book.Price;
     //Deep copy 
     Author = new Writer { Name = book.Name};
}
 
Now, if we run the same code as above, Asimov will stand right where we put him and both books will have their respective authors. A copy where all values are copied from the scratch is called a deep copy.
 
 
Asimov - copying objects
 
Now that we have come in terms with what a shallow and a deep copy is, let's focus on methods we can use to create them.
 

Using MemberwiseClone

Using a constructor we can create a copy of an object whether this is a shallow or a deep one or something in between. We can also add extra features to it the way we like. Of course changing the values compared to the ones the original object had will not create an exact copy but, anyway, the point is that using a constructor you are free to do whatever you want.
 
MemberwiseClone is .NET's way of creating a shallow copy. It will copy all non reference values and copy the reference of the reference types. Let's create the Copy method for our Book class.
 
public Book Copy()
{
    //Shallow copy
    return (Book)this.MemberwiseClone();
}
 
MemberwiseClone will create a shallow copy. We can add extra code to create a deep copy.
 
public Book DeepCopy()
{
     //Deep copy
     Book copy =  (Book)this.MemberwiseClone();
     copy.Author = new Writer { Name = this.Author.Name };
     return copy;
}
 

The IClonable interface

IClonable is an interface created in order to be implemented on classes that are expected to copy themselves. It requires the Clone method. Here's how the Book class would look like using the IClonable interface.
 
public class BookClone : ICloneable
{
    public string Name { get; set; }
    public double Price { get; set; }
    public Writer Author { get; set; }
 
   public BookClone(string name, double price, Writer author)
    {
        Name = name;
        Price = price;
        Author = author;
    }
 
    public object Clone()
    {
        return this.MemberwiseClone();
    }
}
 
This is an example of how we can use the IClonable interface
 
BookClone book = new BookClone("The Gods Themselves", 7.5, new Writer { Name = "Isaac Asimov" });
BookClone bookCopy = (BookClone)book.Clone();
 
So, if a class implements the IClonable interface then we may presume that it supports objects copying.
 
Since ICloneable is nothing but an interface, all that it says is that you have to implement the Clone method. However it does not tell you what the Clone method does. Clone could be implemented to create a shallow copy or a deep copy for example. People argue that the IClonable and the Clone method are more of a trouble than help as a developer will have to check what the Clone implementation actually does before using it.
 
In other words a person might prefer creating his own e.g. ICopyable interface which contains the CopyShallow and CopyDeep methods and make things clearer for everyone using that code.
 
simpsong icloneable
 

Serialization

Searialization is the process of converting an object into a stream of bytes. You may want to do that in order to store that info in memory or in a file or for any other reason you like. Deserialization is the reverse procedure; getting a stream of bytes and turning it back into an object.
 
By serializing and deserializing an object we can easily create a deep copy. Check out the following method.
 
public Book DeepCopyUsingSerialization()
{
     using (MemoryStream memoryStream = new MemoryStream())
     {
           IFormatter formatter = new BinaryFormatter();
           formatter.Serialize(memoryStream, this);
           memoryStream.Seek(0, SeekOrigin.Begin);
           return formatter.Deserialize(memoryStream) as Book;
     }
}
 
To make that code build, you may want to use the following libraries.
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
Oh, and don't forget to declare your classes as [Serializable].
 
All we are doing is what we described earlier. We serialize the object and then create a new object by deserializing the stream created. There are many ways to accomplish object serialization in .NET. The example I've written is just one of them.
 
Keep in mind that using serialization might be a slower method to choose than the ones mentioned before.
 
Apart from the methods described, you may also use reflection to copy objects. I am planning on writing an article concerning reflection later on, so apart from mentioning it, I am not going to write more about it.
 
There is no perfect way to copy an object. The ones we talked about are the most commonly used. You may choose the best one, depending on your case or create your own custom method.
 
c s lewis - copying objects
 

Summary

When it comes to copying objects, there are two categories; shallow and deep copies. Shallow copies will hold the same references to referenced individual objects and copy all other values, while deep copies will create new instances for these objects as well. There are many ways to copy an object either shallow, or deep. Using constructors, the MemberwiseClone method, serialization and reflection being among them.
Reference
DotNetHints
Δημοσιεύτηκε στις Δευτέρα, 8 Φεβρουαρίου 2016 8:06 μμ από το μέλος k badas :: 0 σχόλια

Choosing between fields, properties and methods

I once told a friend of mine that programming is much like chess. In some cases it is; for example when you know where you want to get but there are so many paths to follow. Choosing between fields, properties and methods when you want to store a value temporarily or retrieve it, can be described as some of these scenarios. There was a time I created a class and wanted to store some data, but I was not sure which was the best way to do it. Should I create a simple private variable where I would store the value, use a property and some extra auxiliary variable, or instead avoid getters and setters and use nothing more than a method? Since there may be some developers out there sometimes confused with such questions, I thought of writing an article about it.
 

Is there a problem at all?

 
To get started, let's create a class called MartialArtist which holds a single important piece of information: the martial artist's name. Here's the code.
 
public class MartialArtist
{
    //This is a field
    public string Name;
 
    //This is an automatic property
    public string NameProp { get; set; }
 
    //This is a simple method
    public string GetName()
    {
        string name;
 
        //Compute name
 
        return name;
    }
}
 
Ok, that's what we've been talking about. However things still don't seem to be complicated. There's a field, a property and a method and they all seem to work in their own way. So, let's make things a bit more complicated.
 
public class MartialArtist
{
    //This is a field
    public string Name;
 
    public string _nameProp;
    //This is a property
    public string NameProp
    {
        get
        {
            return _nameProp;
        }
        set
        {
            _nameProp = value;
        }
    }
 
    //This is a simple method
    public string GetName()
    {
        return _nameProp;
    }
}
 
Now, differences between them seem to get unclear. Why is a public field different from a public property using a private field? And what is the difference between a public property using a private field and a public method using a private field? Let's try to clear things out.
 
martial artist property

Fields vs Properties

 
Here's how we use the field.
MartialArtist BruceLee = new MartialArtist();
BruceLee.Name = "Bruce Lee";
string martialArtistName = BruceLee.Name;
 
And how about the property?
BruceLee.NameProp = "Bruce Lee";
string martialArtistName = BruceLee.NameProp;
 
There seems to be no difference between how we use a field or a property. So let's focus on what is a field and what makes a property.
 
A field is nothing more than a part of the class info. A position in the memory for a string variable to be placed. If we wish to store some value on Name, that's exactly where it will be stored. And if later on we wish to get it back that's where we'll get it from. That's as simple as it can get.
 
Properties are a bit more complicated. An automatic Name property looks like this
public string NameProp { get; set; }
This looks simple as well, however it is not. When we write this line, unaware to us, two methods and a field will automatically be created. These methods consist of the getter and the setter, and the variable represents the place where the data will be stored. In a few words, creating an automatic property will look like creating a non automatic property
   
private string _name;
public string Name
{
    get
     {
           return _name;
     }
     set
    {
           _name = value;
     }
}
 
True, an automatic property is nothing more than an actual property and the ability to create one was granted to us developers in order to save us the trouble of writing extra code than necessary. So, now that a few things concerning fields and properties are clearer, let's try and answer the base question. Should we prefer fields over properties?
 
Fields are, well, fields. Properties are methods that use fields. So properties are expected to be far slower in accessing stored values. However this is not what happens. You see, when creating properties with methods that keep it simple, these properties will be inlined by JIT compiler, so that they will be optimized and become faster; much faster. Even faster than a single field. So even if you guessed that you should choose a field over an automatic property, just because the field will execute faster, you should think about it twice.
 
Apart from being faster, using properties has more advantages. Properties may include extra code within their getter and setter methods and they may even include exception handling. They may also have no getter or setter method, this way averting the user from setting or getting the property's value directly.
 
Furthermore, you may not use a field as datasource for controls. You can instead use a property. Properties support encapsulation. Accessor methods can be overridden by classes inheriting this one. Also keep in mind that you may use properties on interfaces but you may not use fields.
 
One last thing to mention is you may think that you can create a field and, when needed, turn it into a property. Keep in mind in that case you will have to recompile all code that uses this field since a field is much different than a property, even though they use the same syntax when called. This may cause trouble to large projects.
 
True; there are not many good reasons to use a field over a parameter. There are some things, for example you may not use a parameter as a ref or out property when you call a method (but you may use a field for that reason) and you may not have a readonly parameter. However there are workarounds. You will not be forced to use fields, because of these things. Microsoft is little by little moving on to parameters and the basic reason fields are still being useful is because there are tons of code using them, as well as a lot of developers who are used to handling them.
 
Still, if you enjoy it, you are free to go on using fields the way like, as long as you keep in mind the things said.
 
Bruce lee property
 

Properties vs Methods

 
Let's move on to the methods. Again, what was that trouble we had?
 
public class MartialArtist
{
    public string Name {get; set;}
 
private string _name;
    public string GetName()
    {
        return _name;
    }
}
 
Well, we were not sure when to use a property or a method. So far, we mentioned that some properties can get inlined, making them faster than using a method. However, this not the main difference.
 
Properties represent some info or attribute, while methods represent some action. For example Name is well suited to be a property since it represents a MartialArtist's value.
 
Since a property represents some object value, it is fairly expected that this value is easy to compute. It is a part of the object info after all. So a property is supposed to be fast. A method on the other hand could be expected to take a lot of time to complete.
 
int counterProperty = MartialArtists.Where(ma => ma.Origin == "Hong Kong").Count();
int counterMethod = MartialArtists.Where(ma => ma.GetOrigin() == "Hong Kong").Count();
 
Look at these expressions. Which one seems to be faster to you? The first one I guess. That's because you are expecting a property to work faster than a method. Actually, if you are not the person who has written the class code (most likely) you may not even realize if Origin is a property or a field. Anyway, in case a property takes a lot of time to compute every time it is called, you'd better go for the method.
 
 
Property values are expected to remain intact no matter how many times they are used. That's unless of course you change its value on purpose.
 
MartialArtist BruceLee = new MartialArtist();
string name1 = BruceLee.Name;
string name2 = BruceLee.Name;
 
name1 and name2 are expected to hold the same value. It's nothing more than a property of the object after all.
 
MartialArtist BruceLee = new MartialArtist();
string name1 = BruceLee.GetName();
string name2 = BruceLee.GetName();
 
In that case however name1 and name2 are far less obvious to hold the same value. Calling GetName once may have changed a lot of things, which will change what GetName will return the next time it is called.
 
Furthermore, properties should not have significant side effects. If for example, getting Name, will cause the NamePerSessionCounter to increase (which is a "significant" value supposed to increase only once per session), we might consider using a method instead to avoid confusion.
 
So, choosing between a property and a method depends on how you are planning to use it. Keep it simple so everyone is happy.
 
 
Getting close to the end of this article, let's talk about some well known property, DateTime.Now. This property behaves in the following way
public static DateTime Now { get; }
It does represent some info and no action, it is fast to get results and affects nothing more. So it's fair to be a property. What's strange about it, though, is that DateTime may not return the same value if called more than once (if it takes some time between the first and the second time for example), violating one of the things we told. So, if DateTime.Now returns different DateTime values each time it's called, should it be a property? This is the reason many people argue that DateTime.Now should have been turned into a static method instead.
 
ying yang methods properties

Summary

 
You may use fields, properties and methods to get and set values within your code. Fields are not much better than properties. When comparing properties to methods, however, you should pay attention to what they are made for doing and how they affect the rest of your source code.
Reference
DotNetHints
Δημοσιεύτηκε στις Σάββατο, 7 Νοεμβρίου 2015 6:28 μμ από το μέλος k badas :: 0 σχόλια

Deferred execution on LINQ to Entities

Many people use entity framework but are not aware of what deferred execution is and how it may affect their projects. In this article, we are going to have a little talk about it and see how things work.
 

LINQ to entities and deferred execution

 
We take into account that we all have some understanding of entity and LINQ or lambda expressions.
 
To go through this post we created a table called Videogames containing four columns (ID, Name, MainCharacterName and Publisher) and filled it with some popular vintage videogames. Let's start with the following piece of code.
 
 
string videogameNames = "";
var MarioVideogames = db.Videogames.Where(v => v.MainCharacterName == "Mario");
 
foreach (var videogame in MarioVideogames)
  videogameNames += videogame.Name + "<br/>";
 
 
Let's say our table contained only two Videogames having Mario MainCharacterName:  Super Mario Bros and Super Mario Bros 2. The resulting string would be
 
Super Mario Bros<br/>Super Mario Bros 2<br/>
 
(There's nothing wrong in using lambda expressions when talking about LINQ to entities. It's all the same in the end and I personally think that it is much easier to read. If you preferred LINQ queries you could have written
var MarioVideogames = from videogame in db.Videogames where videogame.MainCharacterName == "Mario" select videogame 
instead )
 
Nothing strange so far. What is interesting about it is the deferred execution we talked about. In other words, the MarioVideogames variable will not be filled with data the moment it is declared but rather the moment it is used. To be exact, the moment it is iterated.
 
The IEnumerable interface requires the implementation of the GetEnumerator() method, which returns an enumerator to iterate through a collection, regardless of whether that collection is an IEnumerable, an IQuerable, or even a List.
 
So whenever we have a variable based on IEnumerable and we want to do something with that (that could be using foreach, First, Average etc) we need to iterate through that variable and as a result ask the query to be executed.
 
Linq to enitites Mario
 

Why do we need deferred execution?

 
All right, since we know the query is not executed instantly, what would happen in the following case?
 
 
var MarioVideogames = db.Videogames.Where(v => v.MainCharacterName == "Mario");
string firstVideogameName = MarioVideogames.First().Name;
string lastVideogameName = MarioVideogames.Reverse().First().Name;
 
Sure, firstVideogameName would be "Super Mario Bros" and lastVideogameName would be "Super Mario Bros 2". Yet, what's interesting is that we requested the database twice. First, is when we executed MarioVideogames' query to get firstVideogameName value, second in the case of lastVideogameName.
 
Was that a good thing? Typically, yes it is. There's no reason in requesting data before we need it. Take a look at this.
 
 
var MarioVideogames = db.Videogames.Where(v => v.Name.Contains("Mario"));
if(type == 1)
     MarioVideogames = MarioVideogames.Where(v => v.MainCharacterName == "Mario");
else if(type == 2)
     MarioVideogames = MarioVideogames.Where(v => v.MainCharacterName == "Wario");
 
In this case, MarioVideogames contains different data, depending on the type. Let's say, by default MarioVideogames would return 50 rows of videogames, where in case of type == 1 or type == 2, would return way less videogames. If things did not work that way, we would ask the database for these 50 rows, and after we got all of them, then we would filter out the ones who got the MainCharacterName we want. On the contrary, what happens now is we ask the database for videogames containing Mario in their Name and having specific MainCharacterName at the same time. The records we get will be the ones we actually want.
 
If for any reason we did want to execute the query at a given moment and get the data into memory we may use something like ToList or ToArray method. This way, instead of a simple IEnumerable, we can create a list that is stored in memory and has no longer anything to do with the database.
 
 
var MarioVideogames = db.Videogames.Where(v => v.Name.Contains("Mario")).ToList();
if(type == 1)
     MarioVideogames = MarioVideogames.Where(v => v.MainCharacterName == "Mario").ToList();
else if(type == 2)
     MarioVideogames = MarioVideogames.Where(v => v.MainCharacterName == "Wario").ToList();
 
This time MarioVideogames will return the 50 videogames at once, and then filter out the ones we don't need.
 
Linq to entities Wario

 

Does it always work?

 
Now, you may wonder, why would we want to "deactivate" deferred execution? It seems to work just fine even in the following case.
 
 
var videogames = db.Videogames.Where(v => v.MainCharacterName == "Mario");
 
//Someone changes Super Mario Bros into Super Mario Bros 3 at this point
 
string firstVideogameName = videogames.First().Name;
string lastVideogameName = videogames.Reverse().First().Name;
 
If the query had already been executed before we needed it to, then firstVideogameName would be "Super Mario Bros", which would by now be outdated. So, as you can see deferred execution works and by default we get no such problems. Unless of course you do not wish to have updated data from the moment your program starts executing.
 
Anyway, now here's something interesting.
 
 
 
Videogame firstMarioVideoGame = null;
var MarioVideogames = db.Videogames.Where(v => v.MainCharacterName == "Mario");
if(MarioVideogames.Any())
{
     //Someone removed all Mario games from the database at this point
     firstMarioVideoGame = MarioVideogames.First();
}
 
This one would end up in a NullReferenceException and what's really bad about it, is there is no easy way of having both deferred execution and ensure that such a case will not occur at the same time.
 
Sure, you can handle such exceptions if you like, but the thing is you can’t always avoid inconsistency issues. For example
 
 
var MarioVideogames = db.Videogames.Where(v => v.MainCharacterName == "Mario");
int MarioVideogamesCounter = MarioVideogames.Count();
 
//Someone removes Super Mario Bros from the database at this point
 
foreach (var videogame in MarioVideogames)
  videogameNames += videogame.Name + "<br/>";
 
Now, the counter says we have two videogames but we see only one videogame name.
 
Here's another example where deferred execution is no good.
deferred execution nintendo
List<string> videogameNamesList = GetVideogameNamesList();
 
//videogameNamesList is a list containing videogame names
 
var NintendoVideogames = db.Videogames.Where(v => v.Publisher == "Nintendo");
 
foreach(string name in videogameNamesList)
{
    var selectedNintendoVideogames = NintendoVideogames.Where(nv => nv.Name == name);
 
    //.........
}
 
This time we request data as many times as videogameNamesList's contents are. If it consisted of one thousand strings, we would request data one thousand times.
 
Enumerating the query using ToList would do some good in such cases. Still, handling 50 Nintendo videogames is fine. What would you do if your database had tens of thousands of Nintendo videogames? Things would go really slow if you had to fetch fifty thousand records in order to get no more than five of them in the end.
 
Caching could be used to get us out of such trouble, even though there is no easy way out of this. It all depends on what you want to do, what problems may arise and how you expect your project to work.
 
 

Summary

 
Creating a LINQ query on entity framework does not instantly get us data from the database. Instead, that will happen the moment we need them. This is called deferred execution and it helps us avoid unnecessary database requests. However this may also turn out to be more of a trouble than help so we should always keep an eye on how our queries are executed.
Reference DotNetHints
Δημοσιεύτηκε στις Κυριακή, 27 Σεπτεμβρίου 2015 12:26 μμ από το μέλος k badas :: 0 σχόλια

Create a secure socket layer WCF service

We have already seen how to create a WCF service. This time we are going to see how to combine a WCF service with SSL security, which will be a trickier thing to do.
 
To reach our goal, we need to take three steps. Step one is to create a WCF Service. Step two is to install a certificate for authentication. Step three is to bring the two first steps together. Since creating a secure socket layer for a website takes more than just a few words. I am planning on writing some future article about that. In order to apply the following methods, a reader should either already have a secure website or, if unable to wait, find a proper article since there are quite a lot out there.
 
Concerning WCF services
 
 
This is the article where we created a WCF service. However since this task is more complex, we will start by repeating a few things.
 
To create a WCF service, we create a service (svc) file. This is where we place the code to execute when the service is requested.
 
The svc file may look like that
<%@ ServiceHost Language="C#" Factory="System.Data.Services.DataServiceHostFactory, Microsoft.Data.Services, Culture=neutral, PublicKeyToken=31bf3856ad364e31" Service="IceCream" %>
 
 
while the code behind file contains the following source code
 
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class IceCream
{
 
    [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    public string GetIceCreamFlavours()
    {
       return "This service is actually working!";
     }
}
 
If the service works fine, you will get the success message when requesting MyPath/IceCream.svc/GetIceCreamFlavours. If not, you will get 404 or 500 errors trying to tell you what you should fix.
 
Now, we need to set up our project so that the code reaches the service when it is requested. Let's edit our web.config file properly. The following code is the minimum code required for a service to work.
 
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
 
    <behaviors>
      <endpointBehaviors>
        <behavior name="DotNetHints.IceCream">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
 
    <services>
      <service name="IceCream">
        <endpoint address="" behaviorConfiguration="DotNetHints.IceCream" binding="webHttpBinding" contract="IceCream" />
      </service>
    </services>
</system.serviceModel>
 
OK, here's what we have here.
 
We created the system.serviceModel node and placed three extra nodes inside: serviceHostingEnvironment, behaviors and services. Let's take a look at them.
 
serviceHostingEnvironment does not have much to do with where we want to get. It contains elements like aspNetCompatibilityEnabled, which control whether ASP.NET HTTP pipeline is used and non-HTTP protocols are prohibited, and multipleSiteBindingsEnabled which allows multiple IIS bindings per site.
 
Our key part, is the services tag. You can see in the following image how service connects all parts. However since sevices require a behavior, let's take a break and build one first. So, we create a behavior named DotNetHints.IceCream which we declare as an EndpointBehavior and place it inside the proper tag.
 
HTTP service diagram
 
 
Then we create our service named IceCream. Services require endpoints. Consider an endpoint as the access point for that service.
 
The address attribure points to the URL the service will use. Since the endpoint we created contains an empty address, requesting MyPath/IceCream.svc/GetIceCreamFlavours will cause the service to show up. Binding contains "webHttpBinding" value. This is the standard WCF method to handle HTTP requests.
 
The contract attribute stands for our service name on the WCF file. We can easily guess that more than one endpoint may use the same sevice.
 
To connect the behavior we created with the service endpoint we use the behaviorConfiguration attribute.
 
That's all we need to implement a simple WCF service. Now let's go for the secure part.
 
 
Creating a secure socket WCF service
 
https security
 
We are now moving forward to step 3, which requires a secure website in order to work. To use https settings, in addition to the parts we placed on our web.config file, we have to create a custom binding. Let's create one and call it HttpsBinding
 
<bindings>
   <webHttpBinding>
     <binding name="HttpsBinding">
        <security mode="Transport">
           <transport clientCredentialType="None"/>
         </security>
      </binding>
   </webHttpBinding>
</bindings>
 
 
By setting security mode to Transport we enable transport security. clientCredentialType determines the messages authentication type. "None" is the simplest type and uses no authentication at all.
 
A few minutes ago we created an endpoint behavior. Behaviors can be classified as endpoint or service behaviours depending on where we call them. This one being set as an endpoint attribute was classified as an endpoint behavior.
<endpoint address="" behaviorConfiguration="DotNetHints.IceCream" binding="webHttpBinding" contract="IceCream" />
 
The behavior we are creating now is a service behavior.
 
<behaviors>
   <serviceBehaviors>
      <behavior name="DotNetHints.IceCream">
      </behavior>
   </serviceBehaviors>
</behaviors>
 
It’s quite similar to the one we already created. All there is left is to create the service and bring everything together. We will create the IceCream service the way we did earlier and add an extra endpoint. This endpoint's bindingConfiguration will be set to our new binding.
 
<services>
   <service name="IceCream" behaviorConfiguration="DotNetHints.IceCream">
      <endpoint address=""
                         binding="webHttpBinding"
                         bindingConfiguration="HttpsBinding"
                         contract="IceCream" />
     <endpoint address=""
                         binding="webHttpBinding"
                         contract="IceCream" />
    </service>
</services>
 
 
We are ready to go. Our service supports both secure and non-secure requests. We can request MyPath/IceCream.svc/GetIceCreamFlavours using http and https supposing that our service is set correctly (and https protocol is enabled for our website). Enjoy!
 
Summary
 
We followed the implementation of a WCF service all the way from the beginning to the end. First we created an svc file which consists of the actual service. Then we started editing the web.config file in order to create a behavior, a binding and finally the service that will put them all together. We managed to create a service that supports both http and https requests.
Reference DotNetHints
Δημοσιεύτηκε στις Παρασκευή, 17 Ιουλίου 2015 11:43 μμ από το μέλος k badas :: 0 σχόλια

Let's talk about GUIDs

I've been using GUIDs for a long time, even though I had no actual clue of what they were. Well, I did know what they were; they looked like 32 hex digit strings separated by hyphens that looked like that A1F5B524-B197-4787-A6FF-38BC0C8D2B01. And they were unique, so I knew that if I had lots of them within my database tables and inserted yet another one, that would be different from all the rest. Then, one day it came to me that it might be interesting to find out what GUIDs actually are, so I did some search.
 
 
What is a GUID?
 
GUIDs are stored as 128-bit values but are usually displayed as 32 hexadecimal digits separated by hyphens, so they can be easier for a human to read, for example A1F5B524-B197-4787-A6FF-38BC0C8D2B01. These groups, containing 8, 4, 4, 4 and 12 hex digits respectively.
 
GUIDs (that stand for Globally Unique Identifiers) are also called UUIDs (Universally Unique Identifiers). Actually UUID was the first term to show up. When Microsoft decided to use UUIDs they preferred to create the name GUID.
 
guids
 
Now, the interesting thing about GUIDs is that the value they represent is quite a large one and can take a lot of different values. Actually it may contain up to 2^128 different values and this is quite a number. It is close to 1.000.000.000... where we get 13 zero triplets. This number, being that large that makes it hard for a person even to conceive, makes it extremely hard for two random numbers to be equal. You may be creating GUIDs all the time and fail to get a single match. Practically the number of possible GUIDs is less than the one described above, since some of the 128 bits are reserved, but we'll get to that later on.
 
In the meanwhile, let's take a look at a few history points.
 
 
GUID versions
 
 
The reason for creating GUIDs is getting an identifier that will be completely different from all the rest. You can easily tell that if I got two database tables using increasing integer numbers as primary keys and wished to concatenate them, I wouldn't be able to retain both tables' IDs. However if I had used GUIDs as primary keys I would have had no trouble at all since GUIDs in both tables are practically different. GUIDs can be found in more places than databases, including COM objects and hard drive partitioning.
 
In a few words GUIDs are used so that distributed systems may possess unique identity information even if no central coordination system is present.
 
GUIDs, as mentioned, stand for unique identifiers. What's bad about that, is that even if it's extremely improbable that two GUIDs are similar, you can never be completely sure about that. To ensure that, version one GUIDs were created based on two different aspects. First is the time the GUID was created, second is the MAC address of the computer that created it.
 
Now, that seems to work fine. You see, different computers cannot produce similar GUIDs and a single computer cannot produce similar GUIDs, so all GUIDs are bound to be different. That system might have worked fine, if it weren't for some problems in both time and space parts.
 
Considering time, suppose I create a GUID and then turn the machine clock back. Or suppose I had a multi-processing computer which could create GUIDs using more than one processor at the same time.
 
MAC address problems also arose, such as what would happen if a person set manually the computer's MAC address or in case of a computer that had no MAC address at all.
 
To avoid such problems. version one GUIDs contain extra bits (apart from the space and time created ones) that try to make things up. Still uniqueness cannot be guaranteed.
 
Furthermore, such GUIDs can be examined so that MAC address and time info can be extracted. And that makes people creating GUIDs no happier.
 
To avoid such problems more GUID versions were created. Microsoft switched to version 4 GUIDs by default on Windows 2000 operating system and has stuck with it since then.
 
Version 4 GUIDs, in contrast to other versions, are created pseudo-randomly. Well, apart from some reserved bits. Let's take a look at the way GUID versions look like. This is the default GUID format:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
 
On version 1 GUIDs the 13th position hex is always 1
xxxxxxxx-xxxx-1xxx-xxxx-xxxxxxxxxxxx
 
Similarly, version 4 GUIDs, contain 4 at the same position
xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
In addition, the 17th hex (represented as y) is allowed to be either 8, 9, A, or B.
 
By the looks of it, the GUID we saw earlier, A1F5B524-B197-4787-A6FF-38BC0C8D2B01, is a version 4 GUID.
 
Earlier we mentioned that version 4 GUIDs are created pseudo-randomly. This method is used to ensure GUID uniqueness. However since the GUID sequence is pseudo-random, a person aware of generator internal state may be able to obtain previous and future GUID values.
 
 
 
GUIDs and .NET
 
To create a new GUID we may use the NewGuid static method.
Guid g = Guid.NewGuid();
 
NewGuid uses the Windows CoCreateGuid function. CoCreateGuid function in return calls the RPC function UuidCreate which returns a UUID (or GUID if you prefer that name). As told earlier this will be a version 4 GUID which is more or less random.
 
In addition to UuidCreate there is an extra function called UuidCreateSequential. This function is used instead of UuidCreate, if you want to make sure that GUIDs created from a single machine are unique. To accomplish this, UuidCreateSequential creates version 1 GUIDs as described earlier. Since version 1 GUIDs contain the computer's MAC address info and a timestamp every GUID created is bound to be unique, compared to all other GUIDs created by that machine. And since the timestamp is set on the GUID and time always marches on every GUID created that way holds a value greater than all previous ones. This is what the term sequential on UuidCreateSequential stands for.
 
By default .NET uses UuidCreate. You can use UuidCreateSequential if you'd like, but it's not as easy as the one line call to UuidCreate.
 
You can also use your SQL Server to create GUIDs. In that case GUIDs are called uniqueidentifiers.
NEWID() creates a version 4 GUID using UuuidCreate.
NEWSEQUENTIALID creates a version 1 GUID using UuidCreateSequential.
 
guid
 
There's one more thing to talk about. Should database tables use GUIDs as primary keys or stick to the traditional integer values? The answer is, it depends. GUIDs require four times the amount of space integers do. Indexing and fragmentation as well as joins and sorting operation are less efficient (using sequential GUIDs will make such things slightly better). They are also far from being user friendly and may make things harder for manual debugging.
 
Still, a person may choose GUIDs since they are overall unique and can make table or database concatenation much easier. They can also be created apart from the database thus separating project parts from each other.
 
People find it hard to agree which method is better. Some say GUIDs are way cool, others think they should never be used as primary keys. Choosing your primary key style depends on what your specs are.
 
Summary
 
GUIDs are 128-bit values which are used to ensure unique values among distributed systems. Since there are far more than a lot possible GUIDs, each newly created GUID may be supposed to be unique. There are two GUID versions currently used by Microsoft, 1 and 4. Version 1 uses the computer MAC address and timestamp to create a GUID while use 4 uses pseudo-random algorithms.
Reference DotNetHints
Δημοσιεύτηκε στις Τετάρτη, 13 Μαΐου 2015 12:18 πμ από το μέλος k badas :: 0 σχόλια

Use your routing system to create a multilingual web forms project

In a previous article we talked about multilingual sites. This time we are going to see how we can place that info in the page URL, using ASP.NET's routing system, and create this way an entirely different version of a website, depending on the language selected.
 
Why, you may ask, would I choose Web Forms to do this instead of using MVC's way better routing system? Well, no matter how deprecated Web Forms may become, websites based on that will still remain out there for a long time, so it may still be useful to some. And, after all, no matter what they look like right now, who doesn't like reading stuff concerning Web Forms?
 

Why messing with the URL?

 
To begin with, what we're talking about is not storing the info in the query string; instead we’ll try out the actual URL body. Actually, language info could as well be stored using cookies or other means. What do we get by using this
MyWebsite/en/contact.aspx
instead of
MyWebsite/contact.aspx?lang=en
or simply store language on some cookie and use
MyWebsite/contact.aspx
 
The main reason for doing so, is SEO. Cookies have nothing to do with SEO, so using them is not a good choice. Storing parameters (language or anything else) in the query string is better than cookies but still not as good as storing info right inside the URL file path.
 
You may of course use different hosts to achieve that (eg MyWebsite.en or en.MyWebsite) which is ok as well. However this is a whole new story which is totally up to you to choose. What we’re talking about here requires nothing more than a single host.
 
You may also read for yourself Google's point of view concerning multilingual sites here.
 
 
multi-language site

Creating routes

 
Before moving on to the main part of the article we are going to take a look at the basics of the web forms routing system.
 
By default, Web Forms use file system request handling. The MyWebsite/contact.aspx request searches for the contact.aspx file located under the root menu. MyWebsite/superheroes/superheroes.aspx should look for the superheroes.aspx file located inside the superheroes file under the root menu.
 
Using the global.asax file we may add our own handling. All we need is to call a method, having a RouteCollection parameter, from within the Application_Start method. So let's create a method called RegisterRoutes and place it within a new file called MyRouteConfig.cs.
 
private void Application_Start(object sender, EventArgs e)
{
    MyRouteConfig.RegisterRoutes(RouteTable.Routes);
}
 
public static class MyRouteConfig
{
   public static void RegisterRoutes(RouteCollection routes)
   {
   }
}
 
Things that change the way routing system works should be placed here. For example, in order to use friendly urls (getting the same result as MyWebsite/contact.aspx when you request MyWebsite/contact) your RegisterRoutes method should look like
 
private void RegisterRoutes(RouteCollection routes)
{
     routes.EnableFriendlyUrls();
}
 
To make it work, add references to Microsoft.AspNet.FriendlyUrls and System.Web.Routing.
 
Now let's check out one more thing. Let's say, you had a page called superheroes.aspx where the superhero id was placed inside the query string superhoeroes.aspx?id=2 and then you got it's value from within your page using Request.QueryString["id"].
 
Instead we could use a friendlier method and replace superhoeroes.aspx?id=2 with superhero/ironman or superhero/hulk.
 
By default this would search for the ironman folder under the superhero folder
 
However we could add the following line in our RegisterRoutes method
 
routes.MapPageRoute("superheroes", "superhero/{SuperheroName}", "~/superheroes.aspx");
 
The simplest instance of MapPageRoute requires three arguments.
1) A string as the route's name.
2) The URL the route will handle.
3) The physical file the route will point to.
 
Using the route we created, if we get a superhero/hulk request, this will redirect to the superheroes.aspx file.
Within the page code we may get the superhero name using Page.RouteData.Values["SuperheroName"]).
 
hulk-homer-avengers
 
In case of superhero/hulk, Page.RouteData.Values["SuperheroName"] would result in "hulk". Always pay attention to null values.
 
Now, let's move on and see how the concept described can be applied to more than one language.
 
 

Adding the language

 
To add a language identifier we need an extra route that will point us to a new handler we will create.
 
routes.Add(new System.Web.Routing.Route("{language}/{*page}", new LanguageRouteHandler()));
 
This is the route we need. Now let's take care of the handler. We are going to create the LanguageRouteHandler class implementing the IRouteHandler interface. This requires creating a GetHttpHandler method that returns an IHttpHandler object. Here's what we have so far.
 
public class LanguageRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        string page = CheckForNullValue(requestContext.RouteData.Values["page"]);
        string virtualPath = "~/" + page;
 
        try
        {
            return BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(Page)) as IHttpHandler;
        }
        catch
        {
            return null;
        }
    }
}
 
Seems nice. So, how does it work?  Let's say we request the contact page. English is our default language. So requesting MyWebsite/contact would request the contact page (based on the previous part routing system) as if we had never created our handler.  That is because our handler searches for {language}/{*page} and  "contact" does not match this. We could have used MyWebsite/en/contact as well, and treat English as any other language; however default language usually needs no language identifier.
 
Don't forget to add references to System.Web, System.Web.UI, and System.Web.Compilation.
 
Now it's time to activate our handler. Request MyWebsite/el/contact.aspx. This request matches the route we created and will use the GetHttpHandler of our new class. Our page variable will be equal to "contact.aspx". However we should add a tilde (~) to it as CreateInstanceFromVirtualPath needs absolute paths to work properly. CreateInstanceFromVirtualPath will return an IHttpHandler object and things will work just fine.
 
CheckForNullValue is a simple custom method that returns a string, taking care of null values instances.
 
Whenever we need to get that language info, we may use Page.RouteData.Values["language"]), the same way we did earlier.
 
"el" refers to the Greek language. As a matter of fact I could have used any possible name eg MyWebsite/DotNetHintsRocks/contact.aspx as long as the "DotNetHintsRocks" string is a reference to a language, according to my personal language dictionary. Search engines however, would prefer spotting "en" or "el" on my URL instead of "DotNetHintsRocks".
 
That's the basic part. We have easily created a multilingual site. However there are still a few more things to do before it is completed.
 
For example MyWebsite/contact will route to MyWebsite/contact.aspx. Still, LanguageRouteHandler will not be able to redirect LanguageRouteHandler MyWebsite/el/contact. It will do its best using CreateInstanceFromVirtualPath but inevitably will get an HttpException stating "The file '/contact' does not exist."
 
To avoid this we could add some extra code to handle such requests, for example
if (!virtualPath.Contains(".aspx"))
      virtualPath += ".aspx";
 
Using that code, virtual path will be turned into "contact.aspx", a file name which does exists. This is a custom solution that may prove nice depending on your case.
 
Let's see a few more custom solutions.  Supposing MyWebsite/ shows home.aspx content. What would MyWebsite/el do? VirtualPath is going to become "~/.aspx" and since there is no such file we will get another exception.
 
There are two ways to avoid this. Either you redirect to your actual page, or you route to that page.
 
if (string.IsNullOrEmpty(page))
        {
            string language= CheckForNullValue(requestContext.RouteData.Values["language"]);
 
            string newPage = "/home";
            if (!string.IsNullOrEmpty(language))
                newPage = "/" + language + newPage;
            HttpContext.Current.Response.Redirect(newPage, false);
            HttpContext.Current.Response.StatusCode = 301;
            HttpContext.Current.Response.End();
 
           //Otherwise, we simply route to home
           //page = "home";
        }
 
Finally, remember that superhero/hulk route we have created? We used
routes.MapPageRoute("superheroes", "superhero/{SuperheroName}", "~/superheroes.aspx");
to make it work. In order to add the language info we should put some extra route underneath. That would be
routes.MapPageRoute("languageSuperheroes", "{language}/superhero/{SuperheroName}", "~/superheroes.aspx");
 
languages-website
 
In case you'd like to see the whole picture, here's what the complete source code would look like. First the global.asax file:
 
<%@ Application Language="C#" %>
 
<script runat="server">
 
   private void Application_Start(object sender, EventArgs e)
   {
       MyRouteConfig.RegisterRoutes(RouteTable.Routes);
   }
 
</script>
 
 
Then the MyRouteConfig.cs file
 
using System;
using Microsoft.AspNet.FriendlyUrls;
using System.Web.Routing;
using System.Web;
using System.Web.UI;
using System.Web.Compilation;
 
 
public static class MyRouteConfig
{
   public static void RegisterRoutes(RouteCollection routes)
   {
        routes.EnableFriendlyUrls();
 
        routes.MapPageRoute("superheroes", "superhero/{SuperheroName}", "~/superheroes.aspx");
        routes.MapPageRoute("languageSuperheroes", "{language}/superhero/{SuperheroName}", "~/superheroes.aspx");
 
        routes.Add(new System.Web.Routing.Route("{language}/{*page}", new LanguageRouteHandler()));
  }
 
 
 
   public class LanguageRouteHandler : IRouteHandler
   {
       public IHttpHandler GetHttpHandler(RequestContext requestContext)
       {
           string page = CheckForNullValue(requestContext.RouteData.Values["page"]);
           string virtualPath = "~/" + page;
 
           if (string.IsNullOrEmpty(page))
           {
               string language= CheckForNullValue(requestContext.RouteData.Values["language"]);
               string newPage = "/home";
 
               if (!string.IsNullOrEmpty(language))
                   newPage = "/" + language + newPage;
               HttpContext.Current.Response.Redirect(newPage, false);
               HttpContext.Current.Response.StatusCode = 301;
               HttpContext.Current.Response.End();
 
              //Otherwise, route to home
              //page = "home";
           }
 
          if (!virtualPath.Contains(".aspx"))
                virtualPath += ".aspx";
 
           try
           {
               return BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(Page)) as IHttpHandler;
           }
           catch
           {
               return null;
           }
       }
   }
}
 

Pay attention

 
Keep in mind that there may be more things that could be irritating in your website's case. For example, our new handler might receive more requests than expected. A request for images/superheroes/hulk.jpg may enter our handler using "images" as our language and "superheroes/hulk.jpg" as page. In fact you should pay extra attention when turning a website from one to many languages support. There may be more routes that need to be specified or source code to be written in order to handle uncommon situations.
 
A few things that you should watch out are the literals or the URLs that will be created. Apart from that, ensure that you get no SEO issues which is quite common to show up.
 
Needless to say, that techniques described above can be applied to situations totally different than the language issue we've been talking about.
 
 

Summary

Placing the website's language info inside your URL is a good thing to do. In order to get to this, we said a few things concerning ASP.NET's routing system and how we can use it to create "better" URLs. Then we described how to create a custom handler that can use the language info and create a multilingual website.
 
Reference DotNetHints
Δημοσιεύτηκε στις Κυριακή, 29 Μαρτίου 2015 11:57 πμ από το μέλος k badas :: 0 σχόλια

5+1 questions concerning strings you never had the time to answer

Many times I've found myself working on a project while questions concerning code efficiency or why some things were made this way, pop up all around. Since project deadlines are usually more important than my questions, I always end up forgetting the questions I had. To end this, I decided to mark them down, so I can check them out later on. As a result I wrote this article about strings concerning six interesting topics which I think many others might find interesting as well.
 
 
 
String.Empty VS empty string
 
This issue is quite common to be found even in code created by the same group. For example, there probably is a place around the source code where str = "" shows up and another one (probably not written by the same person) where str = String.Empty shows up. My remark concerning the person who wrote those lines was meant, as each developer seems to like either the first or the second way best. If so, is there any difference between these two methods? 
 
To begin with String.Empty returns an empty string. You get ""; the same value as that of the empty string. Nothing more, nothing less. String.Empty contains no secrets.
 
Empty is a static field located on the String class. All it does is return a zero-length (empty) string. On the other hand using empty string ("") will create a new string object. So this is pretty much all there is about that. They are both about the same speed; however empty string creates a new object. So, how bad could this be?
 
Actually not that bad at all since .NET supports string interning. In case you haven't heard of string interning before, the CLR creates a table, called the intern pool. Each unique string that is declared or created, places a reference to that table. So, when a new string variable, containing an already created value, is created it gets the reference from the intern pool. And since "" is quite a common string it's really no big deal.
 
So there is no actual resource issue whether you use String.Empty or empty string. It's up to you to pick the one you like. People have claimed that "" can get easily confused with " " or that String.Empty does not look like a string value at first sight, when you are searching all over your source code. Personally I'd choose the empty string, but that's because this is what I am used to and nothing more. So, it's all up to you.
 
 
string questions
 
String.IsNullOrEmpty
 
IsNUllOrEmpty is a widely used static method located in the System.String library. Everyone knows what this method does. It returns true if the given string is null or its value is Empty, otherwise it returns false. String.IsNullOrEmpty is a great choice to let you know if a string contains a value and can be of use to your algorithm. Over the years I've heard of people claiming that String.IsNullOrEmpty is optimized and produces much faster results than custom created code and others claiming that there is no difference between using that or (str == null || str == ""). So, let's see what's really going on.
 
String.IsNullOrEmpty(str) is actually the same as  (str == null || str.Length == 0).
 
First thing to notice is that str.Length == 0 is faster than str == "". That is because Length == 0 simply gets the Length property of the string and compares it to 0, in contrast to == which uses the Equals method and therefore significant more instructions than those (actually more instructions than the whole of String.IsNullOrEmpty method). So String.IsNullOrEmpty(str) is faster than (str == null || str == "").
 
OK, comparison  to empty string is out of the question. Now what about comparing to null or checking only the Length property? As mentioned, String.IsNullOrEmpty performs both null comparison and zero length comparison. As a result null comparison or zero length comparison alone, are indeed faster than String.IsNullOrEmpty.
 
So, what about next time a friend of yours tells you to use str == null for the reason of checking against null only, instead of String.IsNullOrEmpty(str) as this will be faster? Well, he is right. It takes less time. Actually slightly less time. The amount of time it takes for the or operator to take effect. In other words, it's as if comparing  str == null to str == null || str.Length == 0.
 
The same thing applies if you want to test against empty string only. str.Length is faster, but it will be of no help against a string that is null and will throw NullReferenceException.
 
To sum up with, if you want to check for null, or check for empty string alone you may use your own conditions. The same applies if you want to use both for null and empty as the result will be the same, but in that case, why not using the default method? Anyway it is up to you if you want use str == null, str.Length == 0 or String.IsNullOrEmpty(str). There are many people who think it is better to use the same method all around, others who trust String.IsNullOrEmpty is an easier way for a human being to understnd what is going on just a glimpse and others who think  String.IsNullOrEmpty will save you from random exceptions when some unexpected null string will appear. So, it's all up to you to decide.
 
 
 
string VS String
 
In order to create a string we can use string s = "" or String s = "". Even though both will end up in creating the same string, is there some actual reason to pick one of them?
 
String is a class located on the System library. system is an alias for that keyword, meaning that either way you choose to write your code the compiled code will return System.String in the end.
 
So, if string is the same as String, why do both of them exist? Well, except for string, C# includes a few more aliases such as int to Int32 and bool to Boolean. Such aliases have been created in order to give C# its own style but people have argued whether it is good thing. Some said that C# should only allow developers use aliases and not primitive types in order to avoid mixing them up, others that they simply get confused by them eg not sure if int refers to Int32 or Int64 types.
 
Anyway, aliases do exist and the typical way to use them is to use the alias when referring to an object of that type and the actual class when using an attribute of the class. For example we use string s = String.Format("string vs {0}", "String").
 
 
 
Strings are reference types
 
Strings are indeed reference types, yet there's something strange about that as they look alike a value type more than a reference type. (If you would like to know more concerning value and reference types before moving on you may refer to an older article.)
 
For example
bool IntsAreEqual(int a, int b)
{
     if(a == b)
          return true;
     else
          return false;
}
 
This methods returns true if a = 5 and b = 5. However
 
bool ClassesAreEqual(RandomClass a, RandomClass b)
{
     if(a == b)
          return true;
     else
          return false;
}
 
This method returns true if a and b refer to the same place on the heap no matter what the values contained look like.
Since string comparison  str1 == str2 looks like the first method, string seems to look like a value type.
 
Similar, when initializing a new string using an already existing one eg
string str1 = str2;
str1 does not get a reference to the str2 memory space on the heap. On the contrary it creates its own partition on the heap, much like a value type would do.
 
Actually string is a unique type that should have been a value type since we do wish to have value type features. However, on the contrary to other value types, string is not a standard size type. Int32 requires four bytes to be stored. The string "Answer to life the universe and everything" requires far greater memory size than "42" (even though they may refer to the same thing). A string size may be enormous, thus not only causing trouble to the stack proper functioning, it may even not be able to fit in at all.
 
So, strings had to be placed on the stack. However they also had to maintain some of their fellow value types' characteristics. Developers would not be happy if they had to use some value comparing method in order to get simple string comparison. So what .NET architects did was to overload basic operators, for example == and != so that they work alike value types in case of strings.
 
In the same way, special rules apply when a new string, based on a previous one, is created. This will not create a reference to the old string's heap position, but as described earlier create a brand new reference type.
 
At the end of the day, a developer may actually state that strings are reference types having value type features, because that's what they were created for.
 
 
Strings are immutable
 
Well, most people know that. Strings are immutable, meaning that when a string value is created on the heap, this value is never supposed to change.
 
So what actually happens when we write
string str = " valar morghulis -";
str += " All men must die.";
 
Creating the string str, we create the reference on the stack and store the value on the heap. Adding another string to the one we have already created does not change the stored value. Instead, it gets the stored value, adds the new value and stores it on a new block on the heap where the previous stack reference now points. The previous block on the heap remains intact, waiting for the garbage collector to remove it.
 
got
 
So, strings are reference types that are immutable. The question is, why is that? Why is being immutable a good thing, and, if so, why do other reference types are mutable?
 
One part of the answer lies on the essence of string type. Strings on .NET are supposed to hold their values. Developers who wish to have easily mutable strings may use the StringBuilder class instead. As an example, if I create the string
string myName = "Kostas";
then well, that's my name  and there's no point in changing that. Of course you may object saying that you've written thousands of source code lines containing strings that change all the time so that can't be so. And you may be right; I'm not saying that every string created which is bound to value changes should be replaced by StringBuilders. Choosing between string and StringBuilder we will talk about later on. Just keep in mind that if strings were mutable then there would be no need for StringBuilders. Strings are meant to be mostly readable; not editable.
 
Considering that, suppose you have
string myName = MyName;
myName now holds the value of MyName but not it's reference. If strings were not immutable and while using myName an external action changed MyName's value, then that should change myName's value as well. Not a good thing as myName might have already gone half the method's way before changed.
 
A string could also be set as an argument to a method call. If it were a standard reference type, the method could be able to change the argument string's value. We would probably want to keep that string's value as it was before calling the method (since as we mentioned strings are mostly readable) so such an edit would be no good. Of course we could use the ref keyword if we did wish to change the string's value from within the method.
 
We have already mentioned string interning. Using techniques like that helps so string immutability is by far faster, when creating new strings, than expected at first.
 
There is another yet important reason for that. Strings are not standard size variables, When a string is created it reserves memory space on the heap equal to its initial size. Supposing that before modifying the string value, more variables are created and extra heap space has been reserved, what would happen if we wanted to increase the string size? Would we rearrange everything on the heap just to update the string value? Actually no, it would have been easier to create a new value on top.
 
Of course there are ways to change all those immutable strings' values. That would be using reflection or pointers. The thing is not that you cannot change an already created string value, rather than since this is not the proper way to deal with strings, this is also not the straight forward way to change one.
 
Since string's immutable aspect is much based on personal opinions, those who are interested in learning more stuff will find a great deal of info online.
 
 
 
String concatenation
 
Since strings are immutable, creating a new string by adding two existing ones would not seem to be the most effective way. Some people use String.Concat instead. Others use the StringBuilder class. Let's take a look at them all and find out which one actually works best.
 
Adding strings will end up, behind the scenes, on using String.Concat.
string str1 = "Never send a human ";
string str2 = " to do a machine's job";
string str = str1 + str2;
 
is the same as
str = String.Concat(str1, str2);
 
So, there is no point on which one you choose. However when you add non-variable strings eg
string str = "Never send a human " + " to do a machine's job";
compiler will automatically replace it with
string str = "Never send a human to do a machine's job";
which is faster than using String.Concat
 
So, using the add operator is faster when adding non variable strings, but it's quite the same in all other cases. As a result using the + operator VS String.Concat can be of your personal choice, as Concat method seems to have no actual good points apart from being supported by a great deal of programming languages.
 
 
Moving on to StringBuilder. StringBuilder is supposed to optimize string modification. However should we always use the StringBuilder instead of concatenating strings? To answer that we should first find out how StringBuilders work.
 
When a string is created, it takes up memory space on the heap equal to its size. On the other hand when a StringBuilder object is created, it reserves extra space so it can support possible string modifications. Now, suppose we add extra characters to the StringBuilder. Should the new StringBuilder not surpass the current memory size, the new value is simply stored where the previous one was. However, if it does, new heap memory is allocated and the StringBuilder's capacity is doubled. Capacity is the property which returns the number of characters current StringBuilder can take. Default value is 16; however if you know the size will get much larger, you can set your own value on initialization or later on.
 
So, StringBuilder is indeed built to avoid creating new strings all the time. In that case should we always use StringBuilder when we know our strings are bound to changes?
 
Well, the answer is no. You see even though StringBuilder seems much more flexible, creating a StringBuilder object takes more time and resources than creating a simple string. So, in order to accomplish a few string concatenations, String.Concat() or the + operator will do much better. As  a result when you know your code contains fixed or small number of string modifications, stick to the string path, otherwise go for StringBuilder.
 
An extra reason to choose string instead of StringBuilder is the fact that String contains a few extra methods (eg IndexOf, StartsWith etc) which are absent from StringBuider. In that case you may chose to drop the performance boost you would otherwise get.
Reference DotNetHints
Δημοσιεύτηκε στις Πέμπτη, 26 Φεβρουαρίου 2015 8:31 μμ από το μέλος k badas :: 0 σχόλια

Stress test your website

Publishing a website is always a pleasant thing to do. However there may be times you guess your website works fine but things will go bad later on. That may be the time the website starts gathering a lot of visitors, much more than the few users that have been testing it before deployment. At that point a few requests on the database or less optimized source code might not look that bad but when a few hundred visitors or more roam around your website at the same time, things may start looking gloomy.
 
That may be either the result of poor server hardware or slow connection between the server and the database or lousy source code or, well, pretty much anything. Things tend to go bad under pressure. To avoid unpleasant surprises a developer may create stress tests using Visual Studio so he can foresee what may happen in future and fortify the website as soon as possible.
 
Getting started
 
So, what is a stress test? A stress test simulates a bunch of users moving around our website, the way average visitors would, and marking down its reaction to them.
 
To begin with, we are taking a walk around the website and record its track. Then we create the test using the options we like, for example how many users will be simulated, how long the test will last, the browser type the visitors are using etc. After we are all set, we run the test and watch the reports created before us describing the website's behaviour.
 
Seems quite simple. Now let's check it out, step by step, and create a stress test of our own. Keep in mind that this article is nothing more than an introduction to stress tests. Readers who wish to become stress test professionals will find much more info around the web.
 
Creating a web test
 
We are going to create a stress test using Visual Studio 2013 Ultimate.
Go to Files -> New Project and choose Web Performance and Load Test Project having selected Visual C# -> Test on the templates column.
 
Right click the project we just created and select Add -> Web Performance Test.
 
This will automatically open our Internet Explorer and the Web Test Recorder on its left column. All you have to do now is go to your website and do what you think the average visitor would do. If, for example, you think that creating an account is quite a common thing to happen by lots of people simultaneously, go for it. If not, you'd better avoid it. You can see the path you have created on the Web Test Recorder.
 
load test duration                                       
 
When you feel like it, push the stop button to terminate the recording process. This will create a WebTest file on your project.
 
Creating a load test
 
So far we have created a web test, where we have recorded what we want to test. To test it we will have to create a load test.
 
Right click the project and select Add -> Load Test. A wizard will appear which will guide you through the process. You may select the preferences you wish.
load test wizard
 
For example, you can set the load pattern, how many users will visit your website, if they will take step load actions and what options these steps will have.
load test pattern
 
You may also add more than one web test to the load test.
load test more
 
There are a lot of options including warm up and actual test duration.
load test duration
 
 
Running the test
 
You can run the load test using your own machines but using cloud-based load testing would be easier. You will however need to have a Visual Studio online account which is really no big deal. All you have to do is visit this location
and create your account for free. Then use your account info on the visual studio and you are ready to go.
 
load test duration
 
To run the test, select the load test you like and press the test icon on the top left side of the screen. It will take a few moments for visual studio to set up its resources and the test to begin. Once it starts, you can see the way your website responds right on your screen.
 
load test duration                                        load test duration
 
load test duration                                        load test duration
 
When it's all over you can get some nice reports and graphs.
 
load test duration
 
 
Summary
 
To test a website under pressure, we create stress tests. That way we can simulate how the website will respond when a lot of users come around at the same time. First we mark down the typical user behaviour and then we set the test parameters. When we are ready, we run the test and watch the results created on run time. We can avoid unnecessary trouble by using cloud-based testing through visual studio account. 
Reference DotNetHints
Δημοσιεύτηκε στις Δευτέρα, 22 Δεκεμβρίου 2014 8:33 μμ από το μέλος k badas :: 0 σχόλια

Creating an asynchronous select control

Everyone knows the basic select element that is the HTML equivalent to .NET's DropDownList control. Imagine an HTML select containing one hundred or more elements. This would take much time to send and much HTML text to keep your data. Let alone SEO issues that might occur. Instead, data could be filled asynchronously when user activated the control or asked for it using a WCF service leading to far better results. To accomplish that we are going to use JQuery's autocomplete widget.
 
 
Getting started
 
This is a sketch of what we are going to do.
 
Looks better, doesn't it?
 
The select element looks like this
 
    <select>
        <option value="1">Chocolate chip cookie</option>
        <option value="2">Chocolate ice cream</option>
        <option value="3">Cookies and Cream</option>
        <option value="4">Strawberry ice cream</option>
        <option value="5">Vanilla ice cream</option>
    </select>
 
In case you haven't noticed our data consists of ice cream flavours!
 
Creating the WCF service
 
Before writing the HTML and JavaScript code we are going to create the WCF service that will send the results. I am taking into account that you know the basics of WCF services. In case you don't, you could use an old fashioned web service or anything else that will return some JSON data instead.
 
In order to set up our service we will need some info attached to the web.config file. This will do.
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="DotNetHints.IceCream">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="IceCream">
        <endpoint address="" behaviorConfiguration="DotNetHints.IceCream" binding="webHttpBinding" contract="IceCream" />
      </service>
    </services>
  </system.serviceModel>
 
Now we can create WCF services based on the IceCream class. So we create a file called Icecream.svc and place the following code inside
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class IceCream
{
 
    [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    public string GetIceCreamFlavours()
    {
       return "";
     }
}
 
If everything works fine, then by requesting MyPath/IceCream.svc/GetIceCreamFlavours on my web browser I get
{"d":""}
 
This is a web service that returns nothing. Now, let's create a service that will actually do something useful.
 
We are going to use a helper class called IceCreamFlavour that contains two string values, ID and Name.
 
public class IceCreamFlavour
{
    public string ID { get; set; }
    public string Name { get; set;}
}
 
Then we are creating the FillIceCreamFlavors that will get a list of IceCreamFlavour objects and insert the select elements we have created in the beginning.
 
public void FillIceCreamFlavors(List<IceCreamFlavour> searchResults)
{
searchResults.Add(new IceCreamFlavour() { ID = "1", Name = "Chocolate chip cookie" });
searchResults.Add(new IceCreamFlavour() { ID = "2", Name = "Chocolate ice cream" });
searchResults.Add(new IceCreamFlavour() { ID = "3", Name = "Cookies and Cream" });
searchResults.Add(new IceCreamFlavour() { ID = "4", Name = "Strawberry ice cream" });
searchResults.Add(new IceCreamFlavour() { ID = "5", Name = "Vanilla ice cream" });
}
 
Finally let's do our GetIceCreamFlavours service
public string GetIceCreamFlavours()
    {
        List<IceCreamFlavour> searchResults = new List<IceCreamFlavour>();
        FillIceCreamFlavours(searchResults);
 
        //Create a jsonSerializer object
        var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        jsonSerializer.MaxJsonLength = 2147483647;
        //Return serialized json data
        return jsonSerializer.Serialize(searchResults);
    }
 
Now if I request the same URL as I did earlier I get
{"d":"[{\"ID\":\"1\",\"Name\":\"Chocolate chip cookie\"},{\"ID\":\"2\",\"Name\":\"Chocolate ice cream\"},{\"ID\":\"3\",\"Name\":\"Cookies and Cream\"},{\"ID\":\"4\",\"Name\":\"Strawberry ice cream\"},{\"ID\":\"5\",\"Name\":\"Vanilla ice cream\"}]"}
 
This is our data in JSON form. Now we can take one more step and create a method that will filter out all IceCreamFlavours that do not contain the search keyword within their text.
 
public string GetIceCreamFlavours(string searchKeyword)
    {
        List<IceCreamFlavour> searchResults = new List<IceCreamFlavour>();
        FillIceCreamFlavours(searchResults);
 
        if (!string.IsNullOrEmpty(searchKeyword))
        {
            //Use ToLower so letter case will make no difference
            searchKeyword = searchKeyword.ToLower();
            //Use lambda expression to filter out data
            searchResults = searchResults.Where(sr => sr.Name.ToLower().Contains(searchKeyword)).ToList();
 
            //Return no results message
            if (!searchResults.Any())
                searchResults.Add(new IceCreamFlavour() { ID = "-1", Name = "No results :(" });
        }
 
        //Create a jsonSerializer object
        var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        jsonSerializer.MaxJsonLength = 2147483647;
        //Return serialized json data
        return jsonSerializer.Serialize(searchResults);
    } 
 
Now let's try out this URL MyPath/IceCream.svc/GetIceCreamFlavours?searchKeyword=ice
The resulting data is
{"d":"[{\"ID\":\"2\",\"Name\":\"Chocolate ice cream\"},{\"ID\":\"4\",\"Name\":\"Strawberry ice cream\"},{\"ID\":\"5\",\"Name\":\"Vanilla ice cream\"}]"}
 
So far we have successfully created a WCF service that will return IceCreamFlavour data depending on the requested input. Let's move on to the HTML and JavaScript part.
 
 
Using autocomplete
 
To use that JQuery autocomplete widget we need a simple input element like that
<input id="AsyncSearch" type="text" placeholder="Ice Cream Flavour" autocomplete="off" />
 
We also have to use two JQuery library files   
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
 
and optionally a css file so that the results will look nice.
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
 
In addition to the default css I 'd like to add a line of my own to make results look smoother
<style> b, a { font-size:12px;}</style>
 
We are now ready to use the autocomplete function like that
$(function () {
            $("#AsyncSearch").autocomplete({
                source: function (request, response) {
                    $(this.element).data("jqAjax", $.ajax({
                        url: "MyPath/IceCream.svc/GetIceCreamFlavours?searchKeyword=" + encodeURI(request.term),
                        dataType: "json",
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
 
                            if (data.hasOwnProperty("d"))
                                data = eval(data.d);
 
                            response($.map(data, function (item) {
                                return {
                                    label: item.Name,
                                    value: item.ID,
                                };
                            }));
                        }
                    }));
                },
                minLength: 3,
                select: function (event, ui) {
                    window.location.replace('AsyncSelect.html?id=' + ui.item.value)
                }
            });
        });
 
Even though it looks complicated, it is not hard to handle once you get to know it. Event hough autocomplete has many attributes, we'll use only the basic ones.
 
Source describes the data source. Its attributes describe themselves properly: url, dataType, type and contentType. We can easily tell that our service MyPath/IceCream.svc/GetIceCreamFlavours will be the target of the request and it will contain the searchKeyword parameter having value of  encodeURI(request.term).
Let's take a look at success attribute. This is the code that will run when data is retrieved. The following code is important to be included when using WCF services
if (data.hasOwnProperty("d"))
data = eval(data.d);
 
You may remember that a previous call to our service returned
{"d":"[{\"ID\":\"2\",\"Name\":\"Chocolate ice cream\"},{\"ID\":\"4\",\"Name\":\"Strawberry ice cream\"},{\"ID\":\"5\",\"Name\":\"Vanilla ice cream\"}]"}
This is a fine created JSON object, however this "d" property that is by default placed in the beginning when using WCF services will make things hard for autocomplete to handle. This is the reason we need to have it removed.
 
Moving on, minLength is a useful attribute specifying how many characters need to be filled in order for the AJAX call to be created.
 
The select attribute describes what will happen when an item is selected. In our case, we are going to be redirected to a new page (actually it's the same page) containing the item's ID as an id parameter.
 
Everything is ready. Let's take a look at what happens now.
 
 
Using the catcomplete function.
 
We have created our asynchronous select control. Before completing this article there's one more thing to do. That will be, using the catcomplete function, in order to group our results into categories.
 
First thing to do is edit the services we have created so that they can support a categories element. We will create the public class
IceCreamFlavourCategory which is similar to the IceCreamFlavour class, however it includes an extra string Category attribute.
 
public class IceCreamFlavourCategory
{
     public string ID { get; set; }
     public stringName { get; set; }
     public string Category { get; set; }
}
 
We will create a new service called GetIceCreamCategoryFlavours which is about the same as the one we had already created.
   
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    public string GetIceCreamCategoryFlavours(string searchKeyword)
    {
        List<IceCreamFlavourCategory> searchResults = new List<IceCreamFlavourCategory>();
        FillIceCreamCategoryFlavours(searchResults);
 
       //Use ToLower so letter case will make no difference
        searchKeyword = searchKeyword.ToLower();
       //Use lambda expression to filter out data
        searchResults = searchResults.Where(sr => sr.Name.ToLower().Contains(searchKeyword)).ToList();
 
        //Return no results message
        if (!searchResults.Any())
            searchResults.Add(new IceCreamFlavourCategory() { ID = "-1", Name = "No results :(", Category = "", });
 
        var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        jsonSerializer.MaxJsonLength = 2147483647;
        //Return serialized json data
        return jsonSerializer.Serialize(searchResults);
    }
 
We will also use an extra initialization method we are going to name FillIceCreamFlavours, similar to the FillIceCreamFlavours we created earlier.
 
    public void FillIceCreamCategoryFlavours(List<IceCreamFlavourCategory> searchResults)
    {
        searchResults.Add(new IceCreamFlavourCategory() { ID = "1", Name = "Chocolate chip cookie", Category = "Chocolate" });
        searchResults.Add(new IceCreamFlavourCategory() { ID = "2", Name = "Chocolate ice cream", Category = "Chocolate" });
        searchResults.Add(new  IceCreamFlavourCategory() { ID = "3", Name = "Cookies and Cream", Category = "Cream" });
        searchResults.Add(new IceCreamFlavourCategory() { ID = "4", Name = "Strawberry ice cream", Category = "Strawberry" });
        searchResults.Add(new IceCreamFlavourCategory() { ID = "5", Name = "Vanilla ice cream", Category = "Vanilla" });
 
    }
 
Now, the tuime has come to test our new service. When requesting the MyPath/IceCream.svc/GetIceCreamCategoryFlavours?searchKeyword=ice URl we get
 
{"d":"[{\"ID\":\"2\",\"Name\":\"Chocolate ice cream\",\"Category\":\"Chocolate\"},{\"ID\":\"4\",\"Name\":\"Strawberry ice cream\",\"Category\":\"Strawberry\"},{\"ID\":\"5\",\"Name\":\"Vanilla ice cream\",\"Category\":\"Vanilla\"}]"}
 
Notice the results are the same as the ones we got earlier, however now we have the Category info as well.
 
Finally here's the new script we need to use the code we just created.
 
$(function () {
            $("#AsyncSearch").catcomplete({
                source: function (request, response) {
                    $(this.element).data("jqAjax", $.ajax({
                        url: "/MyPath/IceCream.svc/GetIceCreamCategoryFlavours?searchKeyword=" + encodeURI(request.term),
                        dataType: "json",
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
 
                            if (data.hasOwnProperty("d"))
                                data = eval(data.d);
 
                            response($.map(data, function (item) {
                                return {
                                    label: item.Name,
                                    value: item.ID,
                                    category: item.Category
                                };
                            }));
                        }
                    }));
                },
                minLength: 3,
                select: function (event, ui) {
                    window.location.replace('AsyncSelect.html?id=' + ui.item.value)
                }
            });
        });
 
This piece of code is similar to the previous one as well. You may notice the category attribute that is inserted in the response part.
 
We will also need the following piece of code to handle the grouping
 
        $.widget("custom.catcomplete", $.ui.autocomplete, {
            _renderMenu: function (ul, items) {
                var that = this,
                 currentCategory = "";
                $.each(items, function (index, item) {
                    if (item.category != currentCategory) {
                        ul.append("<li ><b>" + item.category + "</b></li>");
                        currentCategory = item.category;
                    }
                    that._renderItemData(ul, item);
                });
            }
        });
 
Every time an item containing a new category shows up we place the items category info before presenting the actual info.
 
The result should look like
 
 
JQuery functions can get many attributes that have not been used on this example. If you want to know more on how to master them, you can visit theofficial page.
 
 
Summary
 
Using a WCF service that returns JSON results based on input in combination with the JQuery autocomplete and catcomplete functions we have created an asynchronous select element. Autocomplete (or catcomplete if we wish to use grouping) calls the service automatically and then handles the results as soon as it gets them.
Reference DotNetHints
Δημοσιεύτηκε στις Πέμπτη, 27 Νοεμβρίου 2014 3:04 μμ από το μέλος k badas :: 0 σχόλια

Attacking a website

People will sometimes attack random websites for their own reason. DotNetHints, being a random website, was bound to become a target of attacks as well. As far as I can tell there has been no damage on either the website or the database. Since all the things I've learned proved quite useful as well as interesting, I decided to write an article containing a list of interesting attack tools, using the attacks made on DotNetHints as a guideline, mentioning what was the purpose of each and every one of them.
 
SQL Injection attacks
 
If you would like to read a few basic things concerning attack patterns, you can read this previous article. Now, let's talk about SQL Injection attacks. An SQL Injection is an attack where text inserted as input can be translated as malicious SQL statements.
 
For example, DotNetHints gets the value of the blog article to show using the query string, let's say http://dotnethints.com/blog?id=53. We could assume that number 53 is passed through the database into a command that looks like
SELECT * FROM Blogs WHERE ID = 53
If a malicious user replaced "53" with "53; DROP TABLE Blogs;" then the SQL statement created would look like
SELECT * FROM Blogs WHERE ID = 53; DROP TABLE Blogs;
and that would easily delete our table (supposing we had a table called Blogs).
 
 
Deleting SQL table
 
However though it may seem easy for us to create malicious SQL statements, the attacker has no clue what his commands are supposed to look like. So he starts off by guessing. He usually creates SQL statements that will cause the server code to fail and using the exception messages or any random piece of info he can get, he forms an image of our database little by little.
 
Keep in mind that SQL Injections have a hard time getting through parameterized SQL queries. That is because in case a BlogID parameter is expected to be an integer, inserting string value will cause an exception to be thrown instead of messing up your database. However even if the variable is expected to be of string type, an SQL parameter will isolate that variable from the rest of the statement, so everything will still be OK. Yet, keep in mind that if you use stored procedures you may not be protected, depending on the stored procedure's syntax. Apart from SQL protection, using an error page is a good idea as well, since the attacker will have nothing straight in his hands.
 
So, if a website contains flaws concerning all that is said, it is vulnerable. Now let's move on and see how an attacker may actually create an attack.
 
Attack tools
 
To make things simple all SQL Injection attacks will be aimed to the current page's ID ( http://dotnethints.com/blog?id=53; that makes it 53 ). The attacker may presume the SQL statement I'm using looks like this
SELECT * FROM Blogs WHERE ID = '53'
since that is a common way to get data from a table. Yet, the attacker cannot be sure what kind of statement is actually used, so he tries to get as much info as possible. In this section, the attacker is trying to find out if the website is vulnerable. In fact all the attacks mentioned below are up against the same thing.
 
53' / '53
Adding an apostrophe inside the statement will cause no harm to the database. The resulting statement looks like
SELECT * FROM Blogs WHERE ID = '53'' / SELECT * FROM Blogs WHERE ID = ''53'
 
Supposing the website had security issues the exception returned would mention something like
Unclosed quotation mark after the character string '53''.
Now the attacker knows that the website is vulnerable and is ready to move on.
 
53' and 'x'='x
The resulting statement looks like
SELECT * FROM Blogs WHERE ID = '53' and 'x'='x'
This time, using the apostrophe, that attacker tries to end the opened string and then add code of his own. 'x'='x' will always result true. So adding this value the result should be the same as if the inserted value were 53. If the attacker gets the same result when adding his code then he knows the website is vulnerable.
 
Any true expression would do.
53 and 1=1
If the attacker gets the same result as using 53 then he knows that both our site is vulnerable and our statement looks like SELECT * FROM Blogs WHERE ID = 53 (in contrast to the previous assumption, this query does not use apostrophes).
 
Instead of using an expression that is always true he could use one that is always false.
53' and 'x'='y
The resulting statement looks like
SELECT * FROM Blogs WHERE ID = '53' and 'x'='y'
 
This time the expression will never return results. Likewise, if the attacker notices system failure, then the site is vulnerable.
Any false expression would do, for example.
53 and 1>1
 
One more point of interest is the following input
999999.9
that creates the seemingly harmless SELECT * FROM Blogs WHERE ID = 999999.9. This will most probably return no rows and is probably used to see if the website is vulnerable. If you see that, you are about to encounter an evil foe. Havij.
 
 
Havij
 
"Havij is an automated SQL Injection tool that helps penetration testers" according to its production company. Well, none could prove them wrong. Yet a hacker is nothing more than a penetration tester who has no permission granted from a website's owner. In other words Havij (and other similar products) is like a knife - you can use it inside your kitchen or you can you use it to attack people. Havij consists of an easy to use Windows environment. This makes it a very popular choice as even people who have no idea what SQL stands for can use it. And in case the website is vulnerable they can get anything out of it.
 
Havij is no magic tool. It uses standard SQL injection attacks. However since it is a software program it can make things work much faster than a single person can. You can find a very interesting description of Havij's basic application on this video entitled Hacking is child's play - SQL injection with Havij by 3 year old.
 
So what Havij is trying to do in a few words is, create exception throwing statements that hold important database info such as tables and columns names on the resulting messages. If the website does not give away exception messages, still Havij can create blind SQL injection attacks and things will end up the same way.
 
Even though I can't be sure, since the attacks I have described so far could have been created by a single person as well, it is probable that I have been the target of a Havij user all the time. Anyway let's see how Havij tried to mess up with the database.
 
999999.9 union all select 0x31303235343830303536,0x31303235343830303536,0x31303235343830303536--
 
OK, so there are three parts in the following SQL statement.
SELECT * FROM Blogs WHERE ID = 999999.9 union all select 0x31303235343830303536,0x31303235343830303536,0x31303235343830303536--
 
1) 999999.9 will return no rows but still carries the table schema
2) union all select 0x31303235343830303536,0x31303235343830303536,0x31303235343830303536 will try to create a union with a three column rows
3) will comment out possible remaining code
 
So, in case our table had four columns the previous statement would throw the following exception.
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
 
OK, so the table does not have three rows. Let's try out four of them.
999999.9 union all select 0x31303235343830303536,0x31303235343830303536,0x31303235343830303536,0x31303235343830303536--
 
This time the result could be the union created row.
Now, if the table consisted of more than four columns Havij would not mind, as it likes creating requests one after the other adding one more row to the previous one's union each time, till it gets to the bottom of it. In my case it tried out to test if the returning data contained up to 23 columns.
 
I have no idea why but Havij is really fond of numbers 999999.9 and 0x31303235343830303536 as I have found many people who have been attacked by exactly the same numbers.
 
Apart from the standard values already mentioned, Havij may also use actual id values instead of 999999.9 and null values instead of hexadecimal numbers.
53 union all select null--
This method is similar to the previous one and will return two rows in case it spots the exact number of columns.
 
 
Time based attacks
 
Time based attacks are SQL Injections as well, however they consist of requests whose response time depends on the SQL statement execution. They are composed of time delaying statements that will usually work if a condition is true. In a few words, if the response takes longer than usual, the attacker knows that his attempt was successful. Look at the following example
 
53; if (1=1) waitfor delay '00:00:01'--
This generates the following SQL statement
SELECT * FROM Blogs WHERE ID =53; if (1=1) waitfor delay '00:00:01'--
 
WAITFOR DELAY is an SQL Server delay function that is created to test if time based attacks can be used against a website. Since 1=1 is always true, if the site is vulnerable, the client should wait a second more than usual to get his response. Time based attacks can be used to bypass the error page defense, in case a site is actually vulnerable.
 
Since an attacker is not sure what database management system the website uses, it makes sense that he should try out some MySQL statements as well.
 
53 and if(1=1,BENCHMARK(208000,MD5(A)),0)
SELECT * FROM Blogs WHERE ID =53 and if(1=1,BENCHMARK(208000,MD5(A)),0)
BENCHMARK is a MySQL statement that repeats an expression a number of times. In the previous example MD5(A) will be executed 208000 times. MD5 is a MySQL function that creates a hash value, in our case the hash value of 'A', and will need some time do so.
 
Using BENCHMARK on MySQL is similar to using WAITFOR DELAY on SQL Server. Both statements will always create time delays so the attacker will know if such an attack can be used.
 
Time based attacks show up in similar forms such as
53' and if(1=1,BENCHMARK(208000,MD5(A)),0) and 'x'='x or
53' AnD BeNChMaRK%(2999999%,MD5(NOW()))
that generate
SELECT * FROM Blogs WHERE ID =53' and if(1=1,BENCHMARK(208000,MD5(A)),0) and 'x'='x' and
SELECT * FROM Blogs WHERE ID =53' AnD BeNChMaRK%(2999999%,MD5(NOW())) respectively.
 
The time based attacks I've described have no actual effect on the database. They are nothing more than simple tests. Yet things could have been different if the website had turned out to be vulnerable.
 
Time based attack
 
 
Padding Oracle attack
 
/WebResource.axd?d=9_aSpQG4otBYJW7wtbgWFn2DTTp5tmDDQLn8KCN2pl3HSkkYcOL6Y5XdP692KHs5mtz1ed72yS
_Ulz7TstrWAxxxcmXpmHVo_-1svjD1wJ01&t=635195661120000000
 
Padding oracle is an attacking tool discovered a while ago where the attacker takes advantage of web resource files in order to get hold of your website encryption method. This vulnerability has been removed through a security update released soon after but as there could be servers that have not yet applied it, it sounds fair enough that attackers would give it a try. Still there are counter measures you can take yourself to make your application safe. Since padding oracle attack would require a lot of pages to be thoroughly described, the following part will be nothing more than a summary of this method. If you would like to know more concerning this you can look it up on the internet.
 
A Web Resource file is a file containing reference to embedded resources within your application. For example if you use ASP.NET's validation controls then the web resource is used to retrieve proper JavaScript files.
 
A web resource's URL looks like that
WebResource.axd?d=SbXSD3uTnhYsK4gMD8fL84_mHPC5jJ7lfdnr1_WtsftZiUOZ6IXYG8QCXW86UizF0&t=632768953157700078
The t parameter refers to time stamp value. What we are interested in is the d parameter which consists of the encrypted identifier. The padding oracle attack is using this identifier to get a hold of your encryption mechanism. Here's how this is done.
 
When a string is encrypted, it has to fit in into eight byte sized blocks. The empty bytes left on these blocks are called padding. Padding has to be filled with something and this something will be the hexadecimal number of the remaining bytes.
 
So supposing there are three bytes left on the block, each one of these will contain data 0x03. When we are trying to decrypt the message, in case one of these blocks contained 0x02, that would cause an error thrown. Padding oracle is the method described. It is the mechanism we can use to check if an encrypted message is correctly encrypted.
 
OK, so far we know what padding oracle is and that a web resource file contains encrypted data. Now what?
 
An attacker can create multiple requests, using a different encrypted identifier each time. If the result is acceptable he gets an OK response, if not he gets an error. After a lot of requests the attacker can get hold of the initialization vector and, from that moment on, create his own encrypted messages or decrypt already encrypted text. Even worse the attacker can even download the application's web.config file.
 
OK, so far I have probably convinced you that padding oracle is some evil thing to deal with. The first question to answer is if a website is vulnerable to padding oracle. To answer that, you must imitate the padding oracle attack.
 
Get your web resource file URL e.g. http://mywebsite.com/WebResource.axd?d=jzjghMVYzFihd9Uhe_arpA2
If you request that, you should get an OK response containing your resource info.
 
Now the attacker would use another identifier  http://mywebsite.com/WebResource.axd?d=acun
If you get anything but an OK response, then the attacker can tell this identifier was not suitable and use another one. So the response should in that case be OK as well.
 
The same applies in case of missing identifier http://mywebsite.com/WebResource.axd?d= where the response would normally be Not Found.
 
So how do we deal with it in case in case something wrong showed up on the previous test? Let's follow these simple steps.
 
1) Use a custom error in your web.config file.
2) Set redirectMode to ResponseRewrite in your web.config file.
3) Add some random sleep delay to your error response.
 
The first step will return an OK page instead of an Error page.
Second step will return an OK instead of a Redirect page.
Even if you always get an OK page someone may guess if an error has occurred based on the time it takes for the response to get. Adding random sleep delay eliminates this issue as well.
 
Keep in mind that getting requests concerning resource files is not always a sign of padding oracle attack. Pods crawling over your website may also cause a "This is an invalid webresource request." exception to be thrown which is no reason to worry about.
 
Padding oracle attack
 
Other types of attacks
 
There are tons of tools a malicious person can use against your website. Whenever something odd comes up administrators should be on the lookout for what it may cause. This is one strange kind of attack that I would like to mention.
 
7 [PLM=0][N ] GET http://dotnethints.com/forum_post?id=7 [0,14770,13801] -> [N ] POST http://dotnethints.com/forum_post?id=7 [R=302][8880,0,522]
 
Even though I have made quite a search concerning the previous attack, it got me nowhere. This type of attack does exist, as many people have been wondering, but none of them has a straight idea what it is for. I am really not sure myself yet I might guess that the attacker is trying to post something to the page as this page contains a form to insert input.
 
Anyway if there is anybody out there who knows what this whole thing is about, I would be really happy to know about it.
 
One last thing to point is the following alarming request I would get
 
/blog?id=41&sa=U&ei=kL7iVOelC43VPIuegOgF&ved=0CBYQFjAA&usg=AFQjCNED6y6PaalihyN0XUzcfDo4KvXuEA
 
Fortunately this one is no attack. It is actually caused by some browser add-on called Google Enhancer when using search engine. So, that drops the threats couter by one.
 
 
Summary
 
SQL Injections are attack tools that have to do with creating malicious SQL statements through input and can be neutralized using parameterized SQL commands. An attacker will usually test to find out if a website is vulnerable before moving on to actual attacks. Using Havij, simple computer users can create effective SQL Injection attacks. Time base attacks are SQL Injection attacks base on the response time. Padding Oracle attack takes advantage of resource files to get access to our encryption methods.
Reference DotNetHints
Δημοσιεύτηκε στις Πέμπτη, 9 Οκτωβρίου 2014 7:59 μμ από το μέλος k badas :: 0 σχόλια

Handling unhandled exceptions

We have already talked about exception handling and creating error pages on a previous article. In this article we will see how we can use the Global.asax Application_Error method to handle every possible exception in our website.
 
Introduction
 
Typical exception handling can use try catch blocks in pieces of code where an exception is likely to happen. On the other hand an error page works for all possible exceptions on our website but will do nothing more than display an error page. However it would be nice if we could be informed when an unhandled exception is thrown. Since our code is supposed to work, an unhandled exception would state that either there is something wrong with it, or someone is trying to throw exceptions on purpose, by messing up with the URL for example.
 
Either way, we can use the Application_Error method to do things like log error info or send an email to the administrator. Application_Error will be called when an unhandled exception is thrown.
 
exception handling
 
Using the Application_Error method
 
Getting the exception info is quite easy. All we have to do is use
Exception ex = Server.GetLastError();
and here's our exception waiting for us to fetch the info we want.
 
Most important things to get are the Message, InnerException.Message and StackTrace. Using these you can get the idea of what exception has been thrown and why. For example
Message :                          Exception of type 'System.Web.HttpUnhandledException' was thrown.
InnerException.Message :   Input string was not in a correct format.
StackTrace :                        at System.Web.UI.Page.HandleError(Exception e)
                                          at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)...
 
 
You can of course get all the info you like an Exception object can offer besides the ones already mentioned.
 
You may also like to write down the time the exception was thrown. This can be easily found using DateTime.Now.
 
On a web application you may probably want to get info located in the Request object. Request contains helpful attributes such as the URL that caused the exception. You may also be interested in the client's IP address.
string url = Request.RawUrl;
string IPAddress = GetIPAddress(Request);
 
 
Application_Error in action
 
The example following shows how we can use the Application_Error method to create an UnhandledException object and then store it in database.
 
First we create the UnhandledException class
public class UnhandledException
    {
        public string URL { get; set; }
        public string Message { get; set; }
        public DateTime DateCreated { get; set; }
        public string StackTrace { get; set; }
        public string IPAddress { get; set; }
 
        public UnhandledException(string url, string message, DateTime dateCreated, string stackTrace, string ipaddress)
        {
            URL = url;
            Message = message;
            DateCreated = dateCreated;
            StackTrace = stackTrace;
            IPAddress = ipaddress;
        }
 
        public int StoreUnhandledException()
        {
            //Stores UnhandledException to database.
            return StoreUnhandledException(this);
        }
    }
 
Then we place code inside the Application_Error method
 void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs     
        string url = Request.RawUrl;
        string IPAddress = GetIPAddress(Request);
 
        // Get the exception object.
        Exception ex = Server.GetLastError();
        //Exception info
        string message = ex.Message;
        if (ex.InnerException != null)
            //InnerException.Message is more accurate than message
            message = ex.InnerException.Message;
 
        UnhandledException uex = new UnhandledException(url, message, DateTime.Now, ex.StackTrace, IPAddress);
        uex.StoreUnhandledException();
       
        //Clear exception
        Server.ClearError();
        //Redirect to error page
        Response.Redirect("~/error.aspx");     
    }
 
GetIPAddress is a method returning a string that represents the request's IP address. There are a few ways to get the IP address even though none of them is 100% accurate. In this article we may use the following 
 
//Return client's IP address
public static string GetIPAddress(HttpRequest request)
{
   //In case of proxy use etc
   string ipList = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
 
   if (!string.IsNullOrEmpty(ipList))
       //HTTP_X_FORWARDED_FOR may contain multiple addresses.
       //Get the first one.
       return ipList.Split(',')[0];
 
return request.ServerVariables["REMOTE_ADDR"];
}
 
StoreUnhandledException contains code needed to store exception info in database. Additionally you use could some other method to send an email concerning the exception etc
 
Finally, we clear the exception and redirect to an error page.
 
error handling
 
Summary
 
Storing information concerning unhandled exceptions may prove to be useful. We can use the Application_Error method located within the Global.asax file. This method will be called when an unhandled exception occurs. You can get information concerning both the exception and the request that caused it.
Reference DotNetHints
Δημοσιεύτηκε στις Κυριακή, 21 Σεπτεμβρίου 2014 5:54 μμ από το μέλος k badas :: 0 σχόλια

Facebook & .NET

It's been a few years since social networks have become a part of our life. Since people such as celebrity stars and politicians use them, it is no wonder that developers would choose to do so, in their own way. Let's choose Facebook to interact with. We are going to see how we can use .NET to communicate with Facebook API and use it to do things like getting users info or posting on Facebook.
 
 
Introduction
 
To interact with Facebook we need to have a Facebook application of our own. You can create your own application (similar to my DotNetHints application) through the Facebook Developers portal. Creating the basics is not hard but in case you find yourself in trouble, doing some online research will be more than enough to help you.
 
After you have created your application you will notice you are given two IDs. That's the App ID and the App Secret. Note them down as we are going to use them later on in our example. One more interesting thing is the Site URL parameter. You should mark down the URL you are going to use. I have used my local URL since I am going to use my Visual Studio server.
 
Facebook application set up
 
 
That's all we need for now. We have created a functional Facebook application which we will need to communicate with the Facebook API.
 
Using the Facebook API
 
Supposing we want to create an example which displays the user's name. Here's what are we going to do.
 
First thing, we have to redirect to Facebook and ask for the user's permissions. The user will need to log in, in case he is not already (there is no point in getting a person's info if he is not a Facebook member, right?). Then Facebook will ask user if he wants to grant us permission to access his info. The permission message will be different, depending on the info we want to get, and will be asked the first time only. If he accepts, Facebook will response to our website and return a code.
 
We are then going to use this code to create a web request and in response get an access token, which is different depending on the user and the application and will only work for a short period of time. Once we get hold of this access token we can ask for anything we want, depending on the permission we have requested and the authorization we have been given.
 
That's pretty much all there is out there. If this is the first time you are dealing with the Facebook API you may be a bit confused right now, so let's do an example to clear things up.
 
Getting the code
 
We are going to create a simple example using C# which will do nothing more than getting the user's personal info.
 
To do so, we will create a Web Form containing a button which will cause everything to happen when clicked and a literal where we will show our info.
<asp:Button runat="server" ID="btnShowPersonalInfo" Text="Show Personal Info" OnClick="btnShowPersonalInfo_Click" />
<asp:Literal runat="server" ID="PersonalInfo" />
 
 
 
We will check out the Page_Load method later on. Instead we will first see what happens when the button is clicked.
 
    protected void btnShowPersonalInfo_Click(object sender, EventArgs e)
    {
        //Step 1
        //Button is clicked
        //Redirecting to Facebook and ask the user for authorization
 
        //Base url
        string facebookAuthorizationURL = authorizationURL;
        //FacebookApplicationID
        facebookAuthorizationURL += "?client_id=" + facebookAppID;
        //Redirection URL
        facebookAuthorizationURL += "&redirect_uri=" + GetRedirectURL();
        //Permission scope
        facebookAuthorizationURL += "&scope=user_about_me";
 
        Response.Redirect(facebookAuthorizationURL, true);
    }
 
As we said, first thing to do is to get the code from Facebook. In order to get it, we have to redirect to Facebook. The URL's structure looks like this 
authorizationURL?client_id=MyFacebookAppID&redirect_uri=MyRedirectURI&scope=MyScope
 
1) authorizationURL is a standard URL where we ask for Facebook authorization
    const string authorizationURL = "https://graph.facebook.com/oauth/authorize";
2) client_id is our ApplicationID
    const string facebookAppID = "1541805559......";
3)redirect_uri is the URI we want Facebook to return the user. This most probably will be the same page where we are right now. In our case we use a simple GetRedirectURL method to remove possible code appearance, which will happen when we finally get our code.
 
    private string GetRedirectURL()
    {
        //Step 1.5
        //URL handling
        //This code is nothing more than a simplistic example of how to remove appearance of "code" in the query string
        string redirectUri = Request.Url.AbsoluteUri;
        if (redirectUri.Contains("?code="))
            redirectUri = redirectUri.Remove(redirectUri.IndexOf("?code="));
        return redirectUri;
    }
 
4)scope represents what kind of data we ask permission from the user. In our case the scope is "user_about_me". Other scopes include "publish_stream", "share_item" etc. In our case "user_about_me" will give as the personal info we want.
 
So we redirect to Facebook. What goes next? We said that if the user is not logged, he will need to do so.
 
Facebook login
 
After that, he will be asked to give us permission to get his data. At the moment, we are given permissions and Facebook knows about it, so we are not asked a second time. However if next time our application requires different permission scopes the user will need to confirm that permission as well. When permission is given, Facebook will redirect back to our website (redirect_uri) and the query string will contain some extra value, the code.
 
Facebook user grant permission
 
 
We can now get our code using
string code = Request["code"];
 
 
Getting the access token
 
So far we got ourselves a code. Let's see what we can do with it. We are now getting a new request, this time the one Facebook has created for us. Now, it's time to see our Page_Load method.
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Step 2
            //Getting the access token and our info
            if (Request["code"] != null)
            {
                //We enter this part only when we are redirected from Facebook
                //In that case we have the user's code
 
                string code = Request["code"];
 
                //Now we need the access token
                string access_token = GetAccessToken(code);
                if (access_token != "")
                    GetPersonalInfo(access_token);
                else
                    PersonalInfo.Text = "Sorry, no access_token available.";
            }
        }
    }
 
As we see in the Page_Load code, we are going to use a new method called GetAccessToken which does exactly what its name describes. The access token is what we need to access our user's info or post our own info to Facebook. Here's how we get it.
 
 
private string GetAccessToken(string code)
    {
        //Step 3
        //Get the access token
 
        //Base URL
        string urlGetAccessToken = getTokenURL;
        //Facebook Application ID
        urlGetAccessToken += "?client_id=" + facebookAppID;
        //Facebook Application secret ID
        urlGetAccessToken += "&client_secret=" + facebookAppSecret;
        //Redirection URL
        urlGetAccessToken += "&redirect_uri=" + GetRedirectURL();
        //The code we got a moment ago
        urlGetAccessToken += "&code=" + code;
 
        string responseData = GetWebPageString(urlGetAccessToken);
        if (responseData != "")
        {
            //Use System.Collections.Specialized;
            NameValueCollection col = HttpUtility.ParseQueryString(responseData);
            string access_token = col["access_token"] == null ? "" : col["access_token"];
 
            return access_token;
        }
        else
            return "";
    }
 
All we have to do is create a GET request to Facebook. The request's URL should look like
getTokenURL?client_id=MyFacebookAppID&client_secret=MyFacebookAppSecret&redirect_uri=MyRedirectURI&code=UserCode
 
1)getTokenURL is a standard URL where we ask for Facebook tokens
const string getTokenURL = "https://graph.facebook.com/oauth/access_token";
2)client_id is our ApplicationID
    const string facebookAppID = "1541805559......";
3)client_secret is our App Secret
   const string facebookAppSecret = "0ab63a35ffdd220df...............";
4)redirect_uri is the URI we want Facebook to return the user the same way we did previously. We are using the GetRedirectURL method once again.
5)code is the code we got from Facebook in the previous step.
 
To create the request we will use the GetWebPageString method introduced in a previous blog post.
 
private string GetWebPageString(string targetURL)
    {
        //Step 3.5
        //Create a GET request to facebook
 
        //Create a request to the referenced URL
        WebRequest request = WebRequest.Create(targetURL);
        //Get the response
        WebResponse response = request.GetResponse();
        //Create a Stream and StreamReader containing info from the server
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        //Get the info
        string responseFromServer = reader.ReadToEnd();
 
        //Release resources
        reader.Close();
        dataStream.Close();
        response.Close();
 
        return responseFromServer;
    }
 
So we create a GET request to Facebook and we get as a result something like this
access_token=CAAV6Q......&expires=5126953
which we will treat as a query string  to get the access token through a NameValueCollection.
 
Congratulations. You are now in possession of the access token.
 
 
Go for it
 
We finally have the access token. From now on the code may depend on what we want to do. In our case, get the user's personal info. Back to the Page_Load you will notice that after we get the access token, we use the GetPersonalInfo method. Here's the method.
 
    private void GetPersonalInfo(string accessToken)
    {
        //Step 4
        //Create a GET request to Facebook in order to get personal info
        //When data is returned we store it into a PersonalInfo object
 
        string personalInfoURL = "https://graph.facebook.com/me?access_token=" + accessToken;
        string jsonPersonalInfo = GetWebPageString(personalInfoURL);
        if (jsonPersonalInfo == "")
            PersonalInfo.Text = "Problem while requesting personal info.";
        else
        {
            //Use System.Web.Script.Serialization;
            PersonalInfo info = new JavaScriptSerializer().Deserialize<PersonalInfo>(jsonPersonalInfo);
 
            PersonalInfo.Text  = ShowPersonalInfo(info);
        }
    }
 
The personalInfoURL is quite important as it represents the type of data we want to get from Facebook. Actually the part of interest is the "me/". Using "me/friends/" instead, for example, would ask for the user's friends list. In the personalInfoURL we also have to add our access token.
Using it, we create one last GET request and then get JSON data in response.
 
 
The data in the case of personal info can be deserialized in a PersonalInfo class we create.
 
public class PersonalInfo
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string gender { get; set; }
    public string link { get; set; }
    public string locale { get; set; }
    public string name { get; set; }
    public int timezone { get; set; }
    public DateTime updated_time { get; set; }
    public bool verified { get; set; }
}
 
After desrializing, we have a PersonalInfo object. ShowPersonalInfo will handle that object and use reflection and a StringBuilder to create an HTML table showing the info we got.
 
private string ShowPersonalInfo(object info)
    {
        //Step 5
        //Creating an HTML table to show data using reflection
 
        StringBuilder infoText = new StringBuilder("<table>");
 
        //Use System.Reflection;
        Type type = info.GetType();
        PropertyInfo[] properties = type.GetProperties();
 
        foreach (PropertyInfo property in properties)
            infoText.Append("<tr><td>" + property.Name + "</td><td>" + property.GetValue(info, null) + "</td></tr>");
        infoText.Append("</table>");
 
        return infoText.ToString();
    }
 
Finally, back to the GetPersonalInfo we show the return string using our literal.
PersonalInfo.Text  = ShowPersonalInfo(info);
 
That's all. You should now be able to see a picture like the one following.
 
 
Personal Info
 
 
What to do next
 
Facebook API offers much data to get depending on your permission scope and reference URLs.
 
For example, using "email" in your permission scope and https://graph.facebook.com/me/ you can get JSON data similar to the ones we got earlier yet including user's email as well.
In that case if we created a new class PersonalInfoAndEmail that inherits our PersonalInfo class but also contains the email attribute
public class PersonalInfoAndEmail : PersonalInfo
{
    public string email { get; set; }
}
and deserialize to a PersonalInfoAndEmail object, we would get the following results.
 
 
email personal info
 
 
Using "user_friends" in your permission scope and https://graph.facebook.com/me/friends you can get JSON data of the user's friends.
In my case I get
{"data":[],"summary":{"total_count":355}}
 
 
Using "publish_stream" permissions and creating a POST request (instead of the GET we created earlier) to https://graph.facebook.com/me/feed you can post on the user's wall.
 
You may read more concerning permissions here and reference URLs here
 
One last thing of importance has to do with Facebook permission policy. According to Facebook, "Apps requesting more than public_profile, email and the user_friends permission must be reviewed by Facebook before those permissions can be requested from people. Active apps created before April 30th, 2014 have one year before they are required to go through login review, including updates to existing apps. Facebook apps created after April 30th, 2014 must go through review."
 
So if you want to create an application in order to post in your users' walls, you have to get through Facebook control first. To do so you will need to select your type of extra requests and then upload photos and write a few paragraphs so the Facebook team will have clear understanding of how you are going to use the permissions you ask and then decide if you do need them or not.
 
 
Summary
 
Since Facebook is one of the most popular social networks it would be nice if we could use it to enhance our applications. First we need to create a Facebook application. Then we will use this application to get access to the users' info, first by getting a code, then the access token and finally our data. That is, of course, if the user allows us to do so. We can get most of the user's info, depending on the permission level Facebook has granted us.
Reference DotNetHints
Δημοσιεύτηκε στις Σάββατο, 26 Ιουλίου 2014 3:56 μμ από το μέλος k badas :: 0 σχόλια

URIs, URLs, URNs and .NET

URL is a term familiar to a lot of people since the beginning of the internet age. Actually, not every internet user is familiar with that URL thing, but at least there are some knowing that copying some letters from the top of your browser and sending them to a friend might help him in opening the same page in his browser. People who are familiar with the internet may have heard the term URI and know that is something like the URL. Finally there is is another yet term connected with the previous ones; that's the URN. We are going to find what each one of these terms is about, what they are made for and how .NET may help us to handle them.
 
Introduction
 
A nice way to begin, is by saying what these things are. So here's what each term stands for:
URI : Uniform Resource Identifier
URL : Uniform Resource Locator
URN : Uniform Resource Name
 
We can now tell that they are all referring to some uniform resource. Uniform resources can actually be a lot of stuff. An image, as well as a website address can be such a resource.
 
So they all refer to uniform resources. And what do they tell us about such resources? A URI is an identifier, a URL is a locator and a URN is a name. Even though this may not mean much to you to this point, by the time you reach the bottom of the article you will realize that these names are all the fuss is about.
 
URIs
 
As told, the URI is used to identify the resource. What does identify mean? In a few words to say which is the resource we are looking for out of a group of resources.
 
Supposing there is a resource called Sherlock Holmes. Under that name most people may think of the famous detective created by Arthur Conan Doyle. However can we really be sure that by saying Sherlock Holmes we are referring to the famous detective and not to own of its relatives who may bare the same name? This is where the URI comes in play. The URI will indicate the detective and nothing but that.
 
uri sherlock
 
So what is "Sherlock Holmes" to the person we have just described? It is his name. In other words Sherlock Holmes would be that resource's URN.
 
And what would URL (the locator) be? That might be the way a person in need of detective skills might find Sherlock Holmes, in other words his address. URL would this way be 221B, Baker Street, London, supposing that this address is always uniquely connected to our detective.
 
Now, let's take a look at the following diagram.
 
URI diagram
 
A resource can always be identified by a URI. The diagram tells us that a URI may be either a URL or a URN or both. Back to our previous example, this means that the Sherlock Holmes resource can either be identified using its name (URN - Sherlock Holmes) or its location (URL - 221B, Baker Street, London).
 
Moving on to our familiar URL.
 
 
URLs
 
So what is a URL?
This can be a url : http://dotnethints.com/
This can also be a url: http://dotnethints.com/images/uploads/news/new_17.jpg
 
URLs tell us how we can find and obtain the specified resource. Getting the http://dotnethints.com/images/uploads/news/new_17.jpg URL, we know that we may find the picture located within the images/uploads/news path of the root menu.
 
Keep in mind that dotnethints.com is not a unique URL as more than one URLs could be created depending on the application protocol.
For example http://dotnethints.com/ is not the same URL as ftp://dotnethints.com/. Each one represents a different URL, URI and resource.
 
Content negotiation is a case where a URI may end up in different resource versions (different URLs) depending on circumstances. For example an image can be returned as GIF or PNG file in case the client's browser may not support one of them.
 
URNs
 
So, since URLs work just fine the way we described, why do we need that URN thing? Well, imagine we transferred our website from http://dotnethints.com/ to http://dotnethints_newwebsite.com/. A person who would request http://dotnethints.com/ would get a 404 error. However the resource would still be available online.
 
A URL describes the resources based on its location; as a result it creates a connection between them. Now, imagine creating a simple request for our dotnethints.com resource and automatically getting its URL in order to get our resource, no matter where that would be located right now.
 
That is the ultimate target of the URNs. Being able to locate all resources based on their names. Till then however let's take a look at what a URN looks like.
 
urn:NID:NSS
 
Every URN starts with "urn:" followed by NID and NSS (separated by a colon), where NID and NSS stand for the namespace Identifier and the Namespace Specific String respectively.
For example considering that isbn (International Standard Book Number) is the namespace concerning book standards, a travel guide to Rome which happens to be in my bookcase is uniquely identified by ISBN-13 9781409373162. Romeo and Juliet is also identified by ISBN 0-486-27557-4. That way the URN we could use to identify that book would be urn:isbn:0-486-27557-4.
 
urn-shakespeare
 
Keep in mind that a URN may contain extra namespaces eg urn:NID1:NID2:NSS
 
Namespace Identifiers can also be used in XML Schemas to define namespaces eg
<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="urn:some_namespace" ...
 
 
 
And .NET
 
 
Uri is quite a useful class created to describe a uri address. The easiest way to create a Uri object is using the string of the address it represents. For example
 
Uri uri = new Uri("http://dotnethints.com");
Uri uri = new Uri("http://dotnethints.com/blog?id=47");
Uri uri = new Uri("urn:dotnethints.com");
 
However the following line
Uri uri = new Uri("dotnethints.com");
will throw a System.UriFormatException as we cannot turn every possible string into a Uri.
 
There are two ways to avoid this exception. First one is to use Uri's TryCreate method. TryCreate is similar to TryParse method. It will try to create a Uri object using a string. If it fails, the Uri is set to null.
 
For example
Uri uri =  new Uri();
Uri.TryCreate("http://dotnethints.com/blog", UriKind.Absolute, out uri);
 
creates a proper Uri. However using
 
Uri uri = new Uri();
Uri.TryCreate("dotnethints.com/blog", UriKind.Absolute, out uri);
we get a Uri equal to null.
 
The second way, is to use another Uri method, the IsWellFormedUriString. This method returns true if the string is properly formatted. The following lines will show you how it works.
 
string uriString = "http://dotnethints.com";
Uri uri =  new Uri();
 
if (Uri.IsWellFormedUriString(uriString, UriKind.Absolute))
   uri = new Uri(uriString);
 
 
A common way to create the Uri for the current page (in case of ASP.NET applications) is to use Request.Url.
 
url-uri
 
 
 
We can also use the UriBuilder class in order to create a Uri. Think of UriBuilder as a way of creating Uris separated on parts. For example, scheme, host, path and query refer to the Uri parts respectively. When our UriBuilder object is complete we can use its Uri parameter to create the Uri.
The Uri created in the following example is the same as the one created by new Uri("http://dotnethints.com/blog?id=47").
 
UriBuilder builder = new UriBuilder();
builder.Scheme = "http";
builder.Host = "dotnethints.com";
builder.Path = "blog";
builder.Query = "id=47";
Uri uri = builder.Uri;
 
 
 
So far we have found out how to create a Uri object. Let's see how we can use it.
The Uri class carries along some interesting parameters, for example AbsolutePath, Query and Segments which make things easier when dealing with uris. The following example shows how usefull the Uri class can be.
 
Uri uri = new Uri("http://dotnethints.com/blog?id=47");
URIlit.Text = "OriginalString : " + uri.OriginalString;
URIlit.Text += "<br/> AbsolutePath : " + uri.AbsolutePath;
URIlit.Text += "<br/> PathAndQuery : " + uri.PathAndQuery;
URIlit.Text += "<br/> Query : " + uri.Query;
URIlit.Text += "<br/> Scheme : " + uri.Scheme;
URIlit.Text += "<br/> DnsSafeHost : " + uri.DnsSafeHost;
 
URIlit.Text += "<br/> Segments:";
foreach (string segment in uri.Segments)
    URIlit.Text += segment + " - ";
 
 
 
OriginalString : http://dotnethints.com/blog?id=47
AbsolutePath : /blog
PathAndQuery : /blog?id=47
Query : ?id=47
Scheme : http
DnsSafeHost : dotnethints.com
Segments:/ - blog -
 
 
Reaching the end of this article we are going to create a method that can handle a uri's query string. The method returns the given Uri having inserted new query string value or replaced the existing one, if present. This example, apart from helping in Uris and UriBuilders better understanding, may also prove practically useful.
 
 
    // Replace or insert proper value into uri's query string
    private Uri SetValueInQueryString(Uri uri, string strQueryParameter, string strQueryValue)
    {
        //ParseQueryString returns an encoded NameValueCollection
        var queryStringValues = HttpUtility.ParseQueryString(uri.Query);
        //Insert or update selected name
        queryStringValues.Set(strQueryParameter, strQueryValue);
 
        //Create the new uri using a UriBuilder
        UriBuilder builder = new UriBuilder(uri);
        builder.Query = queryStringValues.ToString();
 
        return builder.Uri;
    }
 
 
Summary
 
 
Urls represent a resource’s location while urns represent its unique name. A Uri can be either a url or a urn. So far, urls are mostly used in comparison to urns. .NET contains the Uri and UriBuilder classes that help us to handle and create uris.
Reference DotNetHints
Δημοσιεύτηκε στις Σάββατο, 21 Ιουνίου 2014 8:38 μμ από το μέλος k badas :: 0 σχόλια

Getting content out of web pages - The WebRequest class

A simple project may be able to do just fine using its local resources, database and nothing but that. However an advanced application may be expected to use distributed resources, such as getting data out of web pages. In that case we need to make requests of our own in order to get that info. .Net contains the WebRequest class which can be quite helpful in such cases. We are going to use WebRequest's methods to get distant info, create a few useful examples and finally find out how we can create asynchronous requests using .Net 4.5.
 
 
 
 
Using the WebRequest
 
A request could be regarded as a basic part of the web architecture. A client sends a request to the server in order to get data. In return, the server will send the data back to the client.
 
create web request
 
We can also create requests using a few lines of code using the WebRequest class.  This is what this article is about. To begin with, we are going to create a simple GET requests to see how we can use it.
 
 
First we need to create a WebRequest object
WebRequest request = WebRequest .Create("http://dotnethints.com");
 
A request is by default a GET request. If however we would like to change that we could use the request.Method property.
Now we create the response
WebResponse response = request.GetResponse();
 
So far, so good. Now we are going to get the page response. That's what we wanted in the first place. We will use a Stream and a StreamReader
 
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd();
 
responseFromServer is the data we are looking for. However we need to release the resources as soon as we are done.
 
reader.Close();
dataStream.Close();
response.Close();
 
That's all. Let's put it all together and create some C# source code which gets the response from a page requested.
 
private string GetWebPageString(string targetURL)
    {
        //Create a request to the referenced URL
        WebRequest request = WebRequest .Create(targetURL);
        //Get the response
        WebResponse response = request.GetResponse();
        //Create a Stream and StreamReader containing info from the server
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader (dataStream);
        //Get the info
        string responseFromServer = reader.ReadToEnd();
       
        //Release resources
        reader.Close();
        dataStream.Close();
        response.Close();
 
        return responseFromServer;
    }
 
For example calling GetRequest("http://dotnethints.com"); will return the dotnethints home page HTML.
 
 
This way we got our HTML info. However this is usually not what we want to do. Most likely we would prefer to get the part of the page which is of interest to us.
 
Supposing a web page contains the following div
<div id="testDiv">This is a test div</div>
and what we want is to get the HTML contained within the testDiv div.
 
In that case we could use a method similar to the following,
 
private string HandleResponse(string responseText, string startString, string endString)
    {
 
        string[] responseParts = responseText.Split(new string[] { startString }, StringSplitOptions.None);
        string handledResponse = responseParts[1].Split(new string[] { endString }, StringSplitOptions.None)[0];
 
        //We could use regular expressions instead
        //string partPattern = startString + ".+" + endString;
        //Match partMatch = Regex.Match(responseText, partPattern);
        //string handledResponse = partMatch.Groups[0].Value.Remove(0, startString.Length);
        //handledResponse = handledResponse.Remove(handledResponse.Length - endString.Length);
 
        return handledResponse;
    }
 
We could now get our the desired info using
HandleResponse(GetRequest("http://dotnethints.com","<div id=\"testDiv\">", "</div>"));
and get the result we've been expecting.
This is a test div
 
 
So far we created a GET request. In order to create a POST request we will first have to insert the POST parameters inside our HttpWebRequest object. The following piece of code looks like the one we used in the previous GET request. However we will need to set request's Method, ContentType, ContentLength and use a Stream object in order to send our parameters, which we have enclosed within a byte array, to the server.
 
 
    private string GetWebPageStringPost(string targetURL)
    {
        //Create a request to the referenced URL
        WebRequest request = (WebRequest )WebRequest.Create(targetURL);
        //Set request method
        request.Method = "POST";
        string formContent = "par1=1&par1=2";
        //Set parameters to a byte array
        byte[] byteArray = Encoding.UTF8.GetBytes(formContent);
        //Set content type and length
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = byteArray.Length;
        //Use a Stream to send parameters
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        //Get the response
        WebResponse response = request.GetResponse();
        dataStream = response.GetResponseStream();
        //Create a StreamReader containing info from the server
        StreamReader reader = new StreamReader(dataStream);
        //Get the info
        string responseFromServer = HttpUtility.UrlDecode(reader.ReadToEnd());
 
        //Release resources
        reader.Close();
        dataStream.Close();
        response.Close();
 
        return responseFromServer;
    }
 
 
 
A WebRequest example
 
dictionary web request
 
Before we go on, let's take a look at an interesting example. Supposing you want to create a dictionary and you are familiar enough with the Dictionary.com, so you know it is quite trustworthy a website. Doing some research, we find out that the search keyword is placed within the search url in the form of http://dictionary.reference.com/browse/search_keyword?s=t.
We also know that the primary result is always placed inside the following HTML code
<span class="dnindex">1.</span><div class="dndata">search_results</div>
Using both facts mentioned we can create a simple method that gets a string parameter and returns the primary result.
 
This is our method
private string UseOnlineDictionary(string keyword)
    {
        return HandleResponse(GetWebPageString("http://dictionary.reference.com/browse/" + keyword + "?s=t"), "<span class=\"dnindex\">1.</span><div class=\"dndata\">", "</div>");
    }
 
Using the following code
        Response.Write("dot: " + UseOnlineDictionary("dot"));
        Response.Write("<br/>net: " + UseOnlineDictionary("net"));
        Response.Write("<br/>hint: " + UseOnlineDictionary("hint"));
 
we get
 
dot: a small, roundish mark made with or as if with a pen.
net: a bag or other contrivance of strong thread or cord worked into an open, meshed fabric, for catching fish, birds, or other animals: a butterfly net.
hint: an indirect, covert, or helpful suggestion; clue: Give me a hint as to his identity.
 
We have succeeded in creating a simple dictionary!
 
Well, our dictionary will not be effective all the time as Dictionary.com does not always create the HTML format we presumed it does. For the sake of our example however we do not take all possible results and error handling into account .
 
Keep in mind that web pages are usually followed by privacy issues. You may probably not be allowed to use directly or copy the content of a web page in case the author is not aware of it. Thus, the previous dictionary example, no matter how simple or useful it may seem, is not suggested to be of use none other than development practice.
 
 
Getting web pages info asynchronously
 
We have already covered how to make asynchronous calls in a previous article. If you are not familiar with asynchronous operations I'd suggest you take a look before going any further. Moving on let's do the previous dictionary example in a WPF manner.
 
GetStringAsync is a method contained within the HttpClient class. It will cause an asynchronous request. We are going to use the Result parameter to get the response HTML following our request.
 
 
All we need is a TextBox named KeywordTextBox, a Label named ResultsLabel and a Button that calls the GetResultsButton_Click method. The user may insert his keyword in the KeywordTextBox and when the button is pressed he may get his results in the ResultsLabel. This time however, the request will be executed asynchronously. While we wait for the response to get to us we may use that valuable time to compute other staff.
 
In just a few words, when using asynchronous operations a method marked as async may use the await keyword to stop the code executing till all previous asynchronous methods are completed.
 
Here's the source code.
 
 
        // State the method as async, so you can use the await keyword
        private void GetResultsButton_Click(object sender, RoutedEventArgs e)
        {
            CreateAsyncRequest();
 
        }
 
        private async Task CreateAsyncRequest()
        {
            string keyword = KeywordTextBox.Text;
 
            //pageHTML will contain all page HTML
            string pageHTML = await GetDictionaryAsync(keyword);
 
            //Show results
            if (pageHTML != "")
                ResultsLabel.Content = HandleResponse(pageHTML, "<span class=\"dnindex\">1.</span><div class=\"dndata\">", "</div>");
            else
                //In case sth goes wrong with the GetDictionaryAsync we get an empty string
                ResultsLabel.Content = "Something went wrong. Please try again.";
        }
 
 
        private async Task<string> GetDictionaryAsync(string keyword)
        {
            try
            {
                HttpClient client = new HttpClient();
 
                //Create asynchronous operation
                //We are going to get the content of the dictionary web page asynchronously
                Task<string> getDotNetHintsStringTask = client.GetStringAsync("http://dictionary.reference.com/browse/" + keyword + "?s=t");
 
                //The method will still run at the same time as the asynchronous operation
                ComputeOtherStuff();
 
                //Here the method must wait for the response to complete
                await Task.WhenAll(getDotNetHintsStringTask);
                return getDotNetHintsStringTask.Result;
            }
            catch
            {
                return "";
            }
        }
 
 
        private void ComputeOtherStuff()
        {
            ResultsLabel.Content = "Getting data . . . In the meanwhile several operations are executed.";
        }
       
        //Get the part of the page we are interested in.
        private string HandleResponse(string responseText, string startString, string endString)
        {
 
            string[] responseParts = responseText.Split(new string[] { startString }, StringSplitOptions.None);
            string handledResponse = responseParts[1].Split(new string[] { endString }, StringSplitOptions.None)[0];
 
            return handledResponse;
        }
 
This is the way the example works.
 
get data synchronous
 
Summary
 
 
WebRequest is a useful class that helps us create requests using .Net code. We can create both GET and POST requests and then get the response HTML using a stream object. Using .Net 4.5  we can create asynchronous requests so that we can continue working till the response is complete.
Reference DotNetHints
Δημοσιεύτηκε στις Κυριακή, 1 Ιουνίου 2014 9:38 μμ από το μέλος k badas :: 0 σχόλια

Garbage collection and memory management.

Garbage collection is an essential part of .Net architecture since it saves you from the trouble of managing the memory parts you have already used.  We are going to see what garbage collection actually is and what may cause it. Next we'll check out how we can manage memory parts ourselves and talk about the disposed pattern.
 
 
Introduction
 
Garbage collection was one of the first things I heard of when started learning .Net. Even so, it's been some time since then that I got the first idea of what garbage collection is about, as most developers were not interested in how it works. Since garbage collection and memory allocation is not a part of a typical .Net developer and "it ain't broke" it doesn't sound like it "needs to be fixed". However a developer who likes to know how things work, may find this article quite interesting, as it forms a simple description of what happens under the hood while our programs keep running.
 
 
The stack and the heap
 
This is an older article where I talk about memory allocation in detail. Let's just go through the basics and see how things are stored in memory, so we can see how things are removed from memory later on.
 
A .Net application gets a part of the available memory and uses it as its own. This part is called virtual memory and even though it can be much larger in 64-bit systems than mere 4GB in 32-bit systems, it will always be limited.
 
Information is stored in two parts of the virtual memory, called the stack and the heap. The stack stores value data types. On the contrary, the heap stores reference data types. 
 
Supposing we wanted to create an integer value
int int1 = 0;
that value would be stored to the stack.
 
Now, if we wanted to create a class object
ReferenceTypeClass object1= new ReferenceTypeClass();
we would create a reference to the stack pointing to some certain point of the heap where we would store the actual object info.
 
The stack and the heap
 
Actually the heap consists of two types, the small object heap and the large object heap. Objects are by default stored in the small object heap unless they are larger than 85000 bytes, in which case they are stored in the large object heap. These types of heaps are no different to the garbage collector so we will refer to both in the same way; heap.
 
 
Stack memory allocation
 
So, information is stored both on the stack and the heap. Since the stack seems to be simpler than the stack, let's do this first.
 
Stack values are stored the way a simple stack would. From bottom to top. However the stack can only take up to 1 MB of data. Exceeding this limit will result in StackOverflow and I guess it is quite clear at that point why this exception is called that way.
 
To avoid this endless info flow .Net uses a stack pointer. This is nothing more than a simple pointer to the next available memory place. So, if I create some integer, the stack pointer will rise by 4 bytes etc. However when a variable stored in the stack goes out of scope, the memory where it's value was stored is no longer useful and the stack pointer will fall down to the place where our integer was stored. There, it will wait till a new variable is created and overwrite the old integer's value. That way, the same memory parts will be used again and again thus causing the StackOverflow far less possible to be thrown.
 
A variable goes out of scope when it can no longer be used in our source code. Here's an example.
 
bool getValueFromCookie = GetValueFromCookie();
int unencryptedValue = 0;
if(getValueFromCookie)
{
   HttpCookie cookie = Request.Cookies["EncryptedValue"];
   if(cookie != null)
   {
      int encryptedValue = (int)cookie["EncryptedValue"]
      unencryptedValue = UnencryptInteger(encryptedValue);
   }
}
 
int newInteger = 0;
 
We have stored an encrypted integer within a cookie. To get it back we check if getValueFromCookie is true, and then we use UnencryptInteger to unencrypt the stored value. This example contains three value types. getValueFromCookie, unencryptedValue and encryptedValue. However the encryptedValue's scope extends far less than the other two variables'. This is because encryptedValue exists only within the if(cookie != null) brackets. When the code reaches the closing bracket the stack pointer will move to the point where the encryptedValue is stored in the stack. The next command, (int newInteger = 0;) will cause this new variable to be placed on that position.
 
 
Heap memory allocation - Garbage collection
 
The heap (also known as managed heap) uses its own pointer, the heap pointer. In contrast to the stack, the heap will keep moving the heap pointer to the next free memory part when a new object is created. Using the same way as the stack to move the heap pointer up and down would be no good as, due to the objects' size diversity, it wouldn't be easy for the heap pointer to find the position suitable to all new objects. As a result the heap pointer always points to the next available memory part.
 
Repeating the same procedure for many objects the heap pointer would eventually reach the end of the heap. In order to avoid this, CLR will cause a garbage collection when the heap pointer surpasses an accepting threshold (this threshold can be adjusted while the application runs). Garbage collection will probably clear some part of the heap and allow the application to move on. Here's how it works.
 
When an object gets out of scope its connection between the stack and the heap is lost, much like it would happen if we had set that object to null. When garbage collection is initialized it searches for objects whose connections are dropped. (We could also say that garbage collection searches for objects without roots. Roots represent the location of the objects in the heap.) The memory these objects required is released. When this procedure is completed, the remaining parts are combined so that they form a solid part of the memory. The heap pointer is then placed on top of that part waiting for the next object to be stored.
 
In the following image there are two examples of garbage collection. In the first one object1 is set to null. In the second, it is object11 that is set to null.
 
garbage collection
 
Keep in mind you can initialize the garbage collection yourselves by calling System.GC.Collect. However you are not advised to do so as the garbage collector and your application cannot both run at the same time.  So, unless you are really sure there are many objects that need to be removed right now, (and not when CLR thinks it's time to do so) you may chose to do so.
 
 
Generations
 
Some interesting part concerning garbage collections is the way it separates older from younger objects. The heap is separated into three sections called generations. Generation 0, 1 and 2.
 
When an object is created, it is placed into the generation 0 section. The heap gets filled with objects this way until the generation 0 threshold is reached. This is when garbage collection is initialized. When the garbage collection is over, all survival objects will be compacted and moved to the generation 1 section.
 
At the moment the generation 0 section is empty. When the next garbage collection shows up, the new remaining objects will be transferred to generation 1 section and all remaining objects formerly in generation 1 will be moved to generation 2 section. The story goes on the same way. Objects stored in generation 2 section surviving the garbage collection will simply be compacted in the same section until the time comes when they will be released.
 
 
Destroying objects
 
Most people have heard that every class apart from the very popular constructor may have a destructor, even though most of them haven't had the chance to use it. A destructor is nothing more than a method named after ~Class_Name. This method can only be called automatically when an object is destroyed (removed from the heap) or the program terminates. For example when an object is destroyed, you may want to change some values in your class. Behind the scenes, a destructor will fire the Finalize method, which is mostly used in languages like C++. That's why the destructors are also called finalizers by some developers.
 
Here's an example where we see a simple destructor in action.
 
    protected void Page_Load(object sender, EventArgs e)
    {
        TerminatingClass.status = "";
        UseGarbageCollector();
 
        //Show results
        ProgressLiteral.Text = TerminatingClass.status;
    }
 
   private void UseGarbageCollector()
    {    
        TerminatingClass t = new TerminatingClass();
        //Set t to null so it does not survive garbage collection
        t = null;
        System.GC.Collect();
 
        //Wait for two seconds so the garbage collection is completed
        Thread.Sleep(2000);
    }
 
class TerminatingClass : IDisposable
{
   static public string status;
 
   public TerminatingClass()
   {
      status += "Constructor";
   }
 
   ~TerminatingClass()
   {
   status += " - Destructor";
   }
}
 
We will use a string static variable to keep track of which methods are called.
First we create a TerminatingClass object. Then it is set to null and we cause garbage collection. (If t was not null, it would have survived the garbage collection). Then we wait two seconds for the garbage collection to finish and the destructors to be called.
 
The result in our page is
Constructor - Destructor
as expected.
 
 
Now here's a nice quote I've heard concerning garbage collection: "Garbage collection is simulating a computer with an infinite amount of memory". What this means is that even though your computer may have limited memory resources, the fact that the garbage collection allows you to use the same resources again and again makes it seem like there's no end (unless you get OutOfMemory or StackOverflow exceptions). So, what the garbage collection does is manage the memory when such a thing has to be done. Supposing we had created a destructor expecting to work for some object of ours. In case the amount of memory was large enough the garbage collector might never occur. So, presuming that garbage collection will always occur at least once is not accurate.
 
When an object whose class contains a destructor is created an instance is also created in the Finalize queue pointing that when this object is about to be removed from memory there are some things that need to be done first. When such an object is about to be removed through garbage collection, it is not; instead due to the Finalize queue the destructor code will be executed. Next time the garbage collection occurs, is when that object will be removed. Keeping that in mind we can tell that creating destructors may slow down the garbage collection.
 
Considering that a destructor cannot be called whenever you want among all that we have said, you can see why destructors are not much used any more. Instead most developers have turned to the disposed pattern.
 
 
Disposing of objects
 
A class implementing the IDisposable interface, must contain a Dispose method. This method can either be used directly or by placing the object within a using statement.
 
Dispose is generally used to get rid of resources connected to an objected. For example instead of writing
SqlConnection con = new SqlConnection(connectionString);
con.Close();
 
we could write
SqlConnection con = new SqlConnection(connectionString);
con.Dispose();
as SqlConnection's Dispose method will call the Close method itself.
 
"using" is a keyword which allows a reference variable to be used within (but not outside) the following brackets.
For example
using (SqlConnection con = new SqlConnection())
{
   // do stuff
}
Here's the catch. Dispose will now be called when this object goes out of scope, even if an exception occurs. That way you avoid the try catch you would need before using con.Close() or con.Dispose()
 
An example follows on, similar to the previous, showing how a dispose method works.
 
    protected void Page_Load(object sender, EventArgs e)
    {
        TerminatingClass.status = "";
        DisposeObject();
 
        //Show results
        ProgressLiteral.Text = TerminatingClass.status;
    }
 
   private void DisposeObject()
    {
        using (TerminatingClass t = new TerminatingClass())
        {
            //use t object to do stuff
        }
 
         //some_object.Dispose() works as well
        //TerminatingClass t = new TerminatingClass();
        //t.Dispose();
    }
 
class TerminatingClass : IDisposable
{
   static public string status;
 
   public TerminatingClass()
   {
      status += "Constructor";
   }
 
    public void Dispose()
    {
        status += " - Dispose";
    }
 
}
 
Now the result is
Constructor - Dispose
 
 
Destructors or Dispose?
 
A destructor is not the same as calling Dispose method. A destructor will be called by garbage collector, Dispose will be called either directly or when out of scope. When an object is disposed it is not removed from memory. Calling Dispose will do nothing more than calling dispose.
 
A combination of the previous methods
       
TerminatingClass t = new TerminatingClass();
        t.Dispose();
        t = null;
        System.GC.Collect();
 
        //Wait for two seconds so the garbage collection is completed
        Thread.Sleep(2000);
 
will result in
 
Constructor - Dispose - Destructor
 
As said, a disposed object is not removed from memory. That is what the garbage collection looks after.
Using Dispose seems to be a better way to handle such issues than using destructors, However you may choose to use both methods should you wish to cover all possible cases.
 
 
 
Summary
 
Garbage collection is the way .Net releases no more needed memory resources and is initialized when the CLR thinks it is needed. We can create destructors containing code that will run when the object is about to be removed from memory. Implementing the IDisposable interface, classes may use the Dispose method to release resources much easier.
 
Reference DotNetHints
Δημοσιεύτηκε στις Σάββατο, 10 Μαΐου 2014 12:38 μμ από το μέλος k badas :: 1 σχόλια

Strange little thing called postback.

I guess that most people know what postback is. Well, at least most developers that have been using ASP.NET Web Forms. If so, you know that postback is an essential part of your application. In this article we are going to search in depth what postback actually is, how it is created and how it can be used in combination with other parts of web applications.
 
Brings back memories
 
Probably the first time you heard of postback was when you tried to create a DropDownList the way it is in the following  example.
 
        <asp:DropDownList runat="server" ID="DropDownListID" />
        <asp:Button runat="server" Text="Click" OnClick="ButtonClicked" />
        <asp:Label runat="server" ID="LabelID" />
 
protected void Page_Load(object sender, EventArgs e)
    {
        DropDownListID.Items.Add("Element 1");
        DropDownListID.Items.Add("Element 2");
    }
 
    protected void ButtonClicked(object sender, EventArgs e)
    {
        LabelID.Text = "Selected " + DropDownListID.SelectedValue;
    }
 
Feeling proud at how you managed to capture the DropDownList's value and print it, you might have suddenly realized that your list contained two more elements than before. Troubled, you might have probably asked some senior developer in order to get an answer; you should use the IsPostBack parameter.
 
ispostback
 
        if (!IsPostBack)
        {
            DropDownListID.Items.Add("Element 1");
            DropDownListID.Items.Add("Element 2");
        }
 
And suddenly, it worked. That's some magic here.
 
ispostback2
 
This may have been the first time you heard about postback. You heard that the IsPostBack is a property that is always false the first time you request a page but is true when an event causes postback, for example clicking a button. Later on you found out that there are web controls like the DropDownList you had already seen, which could be set events like OnSelectedIndexChanged so if a postback happened. they would cause certain methods to occur. There was an AutoPostBack parameter as well which could cause a postback of its own. In that way whenever you picked a new element in the list you created a postback.
 
Later on you found out that there exists something called viewstate and that this viewstate carried along with it all the values your server controls contained. This viewstate was sent back to the server when a postback request was created and this way the server could find out that you had either chosen Element 1 or Element 2. Because that value was automatically stored  within the viewstate. That was great.
 
Later on you heard people arguing that this great thing called viewstate was not  so great after all as it could grow that big that could slow down the request and in total the response time. Then people started disabling viewstate whenever they could do so and talking about ASP.NET MVC and using pure JavaScript to create their requests. No matter how this discussion ended, about that time there may be a day when you look at yourself at the mirror and wonder "What the heck is this postback that I've been using for so long?"
 
Even though only a few or none of the above may have occurred to you, we are now ready to see what is actually happening during a postback.
 
 
Postback in action
 
Let's create one more DropDownList control
 
        <asp:DropDownList runat="server" ID="DropDownListID" OnSelectedIndexChanged="IndexChanged">
            <asp:ListItem Text="Item 1" Value="1" />
            <asp:ListItem  Text="Item 2" Value="2" />
        </asp:DropDownList >
 
This server control will be rendered into a simple select HTML code
 
 <select name="DropDownListID" id="DropDownListID">
      <option selected="selected" value="1">Item 1</option>
      <option value="2">Item 2</option>
</select>
 
 
So far so good. What we are actually interested in, is the effect of the AutoPostBack parameter. Let's add AutoPostBack="true" to the control.
 
The new HTML code consists of some interesting staff.
 
 <select name="DropDownListID" onchange="BLOCKED SCRIPTsetTimeout(&#39;__doPostBack(\&#39;DropDownListID\&#39;,\&#39;\&#39;)&#39;, 0)" id="DropDownListID">
      <option selected="selected" value="1">Item 1</option>
      <option value="2">Item 2</option>
</select>
 
First thing to notice is the presence of a JavaScript call
onchange="BLOCKED SCRIPTsetTimeout(&#39;__doPostBack(\&#39;DropDownListID\&#39;,\&#39;\&#39;)&#39;, 0)"
 
This command will call the __doPostBack function. If we perform some HTML decoding in the previous line, we are calling __doPostBack('DropDownListID',''). This __doPostBack function is automatically inserted in the code by the ASP.NET
 
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>
 
 
automatic postback
 
And what it actually does is submitting the form having __EVENTTARGET.value equal to 'DropDownListID' and __EVENTARGUMENT.value equal to '', in our case.
 
That's all concerning the client part. Now the request is sent to the server.
 
To begin with, keep in mind that a postback is always caused by a POST request. However creating your own POST request code will not set IsPostBack to true.
 
Now, let's see what the server will do next. Request.Form, contains info sent to the server in case of a POST request.. It contains a lot of stuff such as viewstate.
Two interesting parts are __EVENTTARGET and __EVENTARGUMENT which we already saw while viewing client side. You may be right to think that this info is transferred all the way to the server.  __EVENTTARGET  contains the ID of the control which caused the postback, while __EVENTARGUMENT contains the info it contains.
 
That's the way server knows which control caused the postback and is able find the proper method to call. A postback will cause the event handlers specified to the control, raised. In the example, the postback will call the IndexChanged method. This method will be set to the page life cycle position saved for controls events. That is after Page_Load and before Page_PreRender.
 
Let's see how we can use  __EVENTTARGET and __EVENTARGUMENT to find out which control caused the postback or what the arguments are using
 
if (IsPostBack)
        {
            if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
            {
                string ControlID = Page.Request.Params["__EVENTTARGET"];
                Control postbackControl = Page.FindControl(ControlID);
            }
            if (Request.Form["__EVENTARGUMENT"] != null)
            {
                string argumentID = Page.Request.Params["__EVENTARGUMENT"];
            }
        }
 
Knowing which control caused the postback may sometimes save time from refreshing data, in case you may not need to. Something like the next piece of code could save a few seconds of your response time.
 
        if (!IsPostBack)
            //Retrieve and compute data
            ;
        else if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
            if (Page.Request.Params["__EVENTTARGET"] != "DropDownListID")
                //Retrieve and compute refreshed data
                ;
            else
                //You do not need to refresh data. Just use viewstate
                ;
 
 
In the example, __EVENTARGUMENT is an empty string. Other types of postback do not end up that way. Intentionally we could call the __doPostBack method ourselves and use the arguments we like.
 
Server controls such as Buttons may cause direct postbacks without JavaScript. For example a button may be rendered as
<input type="submit" value="Click me" name="ctl02">
Such a postback would contain no values in __EVENTTARGET or __EVENTARGUMENT.
 
How do we know which control caused the postback then, if __EVENTTARGET  is empty?
Remember our button?
<asp:Button runat="server" Text="Click" OnClick="ButtonClicked" />
If we clicked that, the Request.Form would contain something like this ,,,&Button1=Click&,,,
 
This is the way to go on.
In the previous method we should add
if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
            {
                string ControlID = Page.Request.Params["__EVENTTARGET"];
                Control postbackControl = Page.FindControl(ControlID);
            }
else
    foreach (string controlID in Request.Form)
                {
                    //Check all possible info within the form
                    Control objControl = Page.FindControl(controlID);
                    if (objControl is Button)
                    //If it is a button, this is what you are looking for
                    {
                        string buttonControlID = objControl.ID;
                        break;
                    }
                }
 
Finally, keep in mind that you can create your own custom controls which can create and handle postbacks the way you want.
 
 
Avoid postback if possible
 
Postback is usually great, but it may sometimes cause trouble. The faster a page responds the better a website feels. Even though there may be hundreds of things you could do to speed up your website you should always keep in mind that excessive use of postbacks may backfire.
 
Postbacks allow you to have server side control over your page but that will cause a new request to be sent and a new response to wait upon. That request will carry all the viewstate info along with it. Let alone the fact that possible client JavaScript calls will be reset.
 
avoid postback
 
A postback is NOT user friendly, therefore it should be used only when necessary. That means, when you need to do something which cannot be done client sided. For example a redirect can be done using a Hyperlink server control or a button. The Hyperlink will be rendered into an HTMLAnchor control and send a brand new request to the server asking for the new page and take it back. On the contrast, the button will cause a postback (carrying the viewstate info along) run through all the handlers till it reaches the button event handler and then redirect. Even better we could straight away use an HTMLAnchor control.
 
In order to make a part of the page disappeardisapear we could use JavaScript or make a postback and set its visible parameter to false. You should always go for the JavaScript whenever you can.
 
To change the data in your page, you need not cause a postback. Use AJAX instead. Keep in mind that AJAX can't be the key to the solution all the time. You should know when it is best to be used.
 
You may also try to reduce the total viewstate size if there are controls which do not need viewstate. You can set their EnableViewState property to false. EnableViewState is by default set to true.
 
 
Summary
 
Postback is an ASP.NET technique which helps us create a request carrying viewstate info back to the server, in order to create a new response. It uses client side JavaScript to submit the HTML form and will set the IsPostBack parameter to true. We can use the submitted form to get info concerning the postback. Even though postback may prove to be useful, it should be avoided when possible as it may decrease our websites speed.

 

 

Reference DotNetHints

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

Delegates

Delegates are a way to handle methods in a different way than we are used to. They comprise a basic part of the .Net architecture and are important in order to use technologies like lambda expressions.
 
What is a delegate?
 
A delegate is a reference type which can be used as a connection between that and the methods it is assigned. Think of it as a reference type for methods. In a few words, we can create the WriteSthDelegate delegate and the WriteSthMethod method. Then we connect the method to the delegate. Now, we can use the delegate the way we would use the method. Consider a delegate something like a pointer to a method.
 
Let's see an example.
 
We will use a simple literal object called DelegateOutputLitID to show the output.
Here's our delegate and the method it will use.
 
delegate void WriteSthDelegate(string outputText);
 
void WriteSthMethod(string outputText)
{
      DelegateOutputLitID.Text += outputText;
}
 
and this is the way to associate them
 
    protected void Page_Load(object sender, EventArgs e)
    {
        DelegateOutputLitID.Text = "";
 
        //Attach WriteSthMethod while creating the writeSthDelegateObject delegate
        WriteSthDelegate writeSthDelegateObject = new WriteSthDelegate(WriteSthMethod);
        writeSthDelegateObject("Hello, I am a delegate");
}
 
What do we have here? We create an instance of the WriteSthDelegate and connect it to the WriteSthMethod. From now on, using the delegate in the way of writeSthDelegateObject("Hello, I am a delegate") will be equal to calling the method WriteSthMethod("Hello, I am a delegate")
 
The output will be
 
 
Hello, I am a delegate
 
Using a diagram, this is the line followed in order to get the result.
delegates diagram
 
Keep in mind that both the delegate and the method must have the same return value and the same arguments. In our case the return value is void and there is one argument of string type.
 
In addition to using the method directly, the connection between the delegate and the method can occur at runtime and we can thus create a much more flexible application.
 
 
Handling delegates
 
We learned how to assign a method to a delegate. Still, a delegate can be assigned more than one method or dismiss some of the ones it is already assigned.
 
The way to do this is quite simple. You associate the method you want to a new delegate object and then you either add the two delegates or subtract them, much like you would do if you wanted to add or subtract two integers.
 
delegateObject += newDelegateObject will assign new methods to a delegate.
delegateObject -= newDelegateObject will remove methods from a delegate's assigned list.
 
In order to combine two (or more) delegates, they must be instances of the same delegate class.
 
You can also manage that by using the methods directly. For example the previous commands will be the same as
delegateObject += newDelegateMethod
delegateObject -= newDelegateMethod
 
 
delegates
 
 
To create a useful example we will use one more method
 
 void WriteSthElseMethod(string outputText)
    {
        DelegateOutputLitID.Text += "<br/>Hello, " + outputText;
    }
 
Now, here's the example
 
 
protected void Page_Load(object sender, EventArgs e)
    {
        DelegateOutputLitID.Text = "";
 
        //Attach WriteSthMethod while creating the writeSthDelegateObject delegate
        WriteSthDelegate writeSthDelegateObject = new WriteSthDelegate(WriteSthMethod);
        writeSthDelegateObject("Hello, I am a delegate");
 
        DelegateOutputLitID.Text += "<hr/>";
 
        //Attach WriteSthElseMethod to the writeSthDelegateObject delegate
        writeSthDelegateObject += WriteSthElseMethod;
        writeSthDelegateObject("I am a delegate");
 
        DelegateOutputLitID.Text += "<hr/>";
 
        //Remove WriteSthMethod from the writeSthDelegateObject delegate
        writeSthDelegateObject -= WriteSthMethod;
        writeSthDelegateObject("I am a delegate");
    }
 
The output will be
 
 
Hello, I am a delegate
I am a delegate
Hello, I am a delegate



Hello, I am a delegate
 
 
 
All we did, is what we talked about earlier. We created a delegate attached to a method. Then we attached another method to it and combined it so that the first delegate now is connected to both methods. After that we remove the method assigned first.
 
Delegates contain a few useful methods, for example GetInvocationList() will return a list of the delegates invoked by the current delegate. If we tried out the following piece of code
 
 
DelegateOutputLitID.Text += "<br/>There are now  " + writeSthDelegateObject.GetInvocationList().Length + " methods attached to the delegate.<br/>";
foreach (Delegate del in writeSthDelegateObject.GetInvocationList())
{
    DelegateOutputLitID.Text += del.Method + "<br/>";
}
 
we would get
 
 
There are now 2 methods attached to the delegate.
Void WriteSthMethod(System.String)
Void WriteSthElseMethod(System.String)
 
 
The previous examples should probably have given you an idea of how delegates work. Moving forward, we are going to see a few more advanced uses.
 
 
Events and delegates
 
Let's start off by creating two buttons, each of them invoking a method printing a message when clicked. Here's the code.
 
<asp:Button runat="server" ID="Button1ID" Text="This is button 1" OnClick="Button1Clicked" />
<asp:Button runat="server" ID="Button2ID" Text="This is button 2" OnClick="Button2Clicked" />
 
protected void Button1Clicked(object sender, EventArgs e)
{
    DelegateOutputLitID.Text += " This is button 1.";      
}
 
protected void Button2Clicked(object sender, EventArgs e)
{
    DelegateOutputLitID.Text += " This is button 2.";
}
 
That's most simple. When I press the first button I get " This is button 1.". When I press the second I get " This is button 2.".
 
What we have here for each button is an event (Click) and a method (Button1Clicked). What we miss is their connection. By writing OnClick="Button1Clicked" we create an event handler, that is the method that will be called by the event. ASP.NET automatically creates the piece of code that says when the Click event of the control with ID Button1ID is raised, the method that will be called will be Button1Clicked.
 
What is most important is that these event handlers (actually all event handlers) are implemented using delegates. If that is so we could treat these methods like any other method.
 
So, the following code
 
    void ButtonHandling()
    {
        DelegateOutputLitID.Text = "";
        Button2ID.Click -= Button2Clicked;
        Button2ID.Click += Button1Clicked;
    }
 
would remove the Button2Clicked method from the event handler and put Button1Clicked in its place. If we then clicked the second button we would get
 
This is button 1.
 
 
 
That is the reason that all event handling methods have the same arguments
protected void EventHandlingMethod(object sender, EventArgs e)
Because they are all invoked by a delegate that also needs these arguments.
 
Why should I use delegates?
 
why should i use delegates
 
We talked about delegates, what they are and what they do. Based on that, you may be able to tell that like most other advanced tools there may not be times where it will be compulsory for you to use delegates, rather than optionally.
 
You can use delegates when you have created your methods but do not wish to handle them plainly within the code. In that case, using a delegate may end up in a better organized source code.
 
Delegates can also be used when you are not completely sure what you want to do in future. You simply create the delegate and later on invoke the methods you feel like.
 
Delegates still, could be the only solution in case you want to use event handlers or other .Net functions that require delegates.
 
LINQ and Lambda expressions for example can use delegates in order to assign expressions created on the fly. For example
  
delegate int linqDelegate(int i);
  
int LinqDelegate(int i)
    {
        linqDelegate increase = x => x + 1;
        //Equal to int increase(int x){return x +1;}
        linqDelegate square = x => x * x;
        //Equal to int square(int x){return x * x;}
        return square(increase(i));
    }
 
If we called this function
LinqDelegate(5);
we would get 36 as a result.
 
However, we are going to talk about lambda expressions in a future article.
 
 
Summary
 
Delegates can be loosely described as reference types for methods. In that way, calling the delegate is like calling the method invoked. You can invoke more than one method to a delegate, add them and remove them any way that you want. Delegates are used to create event handling and are also used in LINQ and lambda expressions.

 

 

Reference DotNetHints

Δημοσιεύτηκε στις Κυριακή, 6 Απριλίου 2014 6:51 μμ από το μέλος k badas :: 0 σχόλια

L stands for lambda

Lambda expressions are anonymous functions that can be really helpful at times. Alike many other .NET methods, lambda expressions are not the only way to create the algorithm you want, however they may help you in writing code that is much easier to read than the old fashioned way. We are going to see what lambda expressions are and go through some basic applications.
 
Lambda calculus
 
Even though the fact that you reading this article shows that you are interested in the .NET's lambda part, we'll first take a little tour over its mathematical background. When Microsoft developers released .Net 3.5 and introduced lambda expressions, that idea had been in store for a long time. The following description is nothing more but a naive description of the mathematical model and will be used as an introduction to the development model.
In 1930s Church, a mathematician, in order to strengthen the foundations of mathematics, created a formal mathematical system based on function abstraction. He called that system lambda calculus and used the Greek letter λ as its symbol.
 
This λ-calculus system was based on anonymous functions. Till then the usual way to create a function was for example f(x) = x * x.
λ-calculus suggests that the function's name (f in the previous example) is unnecessary. Instead we could use λx.x*x. Such an expression is no longer a function but is rather called lambda abstraction.
A lambda abstraction has the form λ<arguments>.<function body>
 
By the way, why did Church name his system after the Greek letter λ? Similar attempts so far used the notation. Church, creating a new system, wished it to be similar, yet different from the existing ones. So he moved the symbol left, like that Λx.x *x. This reminded him of the capital Greek letter lambda (Λ), thus the name was created. Later on the the symbol was turned to λ (λx.x*x), the lowercase Greek letter, as the current typewriters had a hard time printing.
 
A lambda abstraction represents a function. The function λx.x*x represents is x->x*x.
In the same way we have <parameters> -> <function body>.
 
This is the way .NET treats its lambda expressions as we are soon about to see. A lambda expression is the equivalent of a lambda abstraction. So, as we stated in the beginning, we end up that a lambda expression is nothing more but an anonymous function. A function that has no name, does not exist in code and is created on the fly in order for us to use it.
 
lambda-calculus
 
This is a lambda expression
 
We talked about delegates stating that its similar to method pointers in an older article. Using a delegate we can write the following code.
 
delegate int intDelegate(int i);
    //Create anonymous method
    private int DelegateSquare()
    {
        intDelegate d = delegate(int i){return i = i * i;};
        return d(2);
    }
This method will return 4.
 
Since lambda expressions are nothing more but anonymous functions we can write the same code as
    //Create anonymous method using lambda expression
    private int LambdaSquare()
    {
        intDelegate d = i => i * i;
        return d(2);
    }
 
Here's the difference: Instead of delegate(int i){return i = i * i;}; we get i => i * i;
 
We can tell there's no actual difference in what the result will be. The result will still be 4. What we have accomplished is we have turned a simple anonymous method into an even simpler lambda expression.
 
Using λ-calculus we have λx.x*x or x->x*x. Using lambda expressions we have i => i * i. It's all about the same thing, we create an anonymous function that gets the i parameter and returns i * i.
 
If we wanted to create lambda expressions that looked more like anonymous functions we could use brackets. The previous example would then become
 
    //Create anonymous method using lambda expression
    intDelegate LambdaSquare()
    {
        intDelegate d = i => { return i* i; };
        return d(2);
    }
 
Supposing we wanted to create lambda expressions having more than one argument, we would have to present the arguments within parenthesis like this
 
   delegate int twoIntDelegate(int i);
    //Lambda expression accepting more than one argument
    private int LambdaMultiply()
    {
        twoIntDelegated = (i, j) => i * j;
        return d(2,3);
    }
 
Actually all lambda expressions are supposed to contain arguments within parenthesis, however in case of one argument it is not compulsory. So most developers prefer writing i => i * i instead of (i) => i * i, even though it's quite the same thing.
 
Now, here's a bit more complex example that can show us how helpful lambda expressions can be.
 
This method will return the maximum number from a list of integers that is also greater than the minValue specified.
 
//Old fashioned code
    private int GetMaxIntValueGreaterThanLocalInteger()
    {
        List<int> intList = new List<int> { 1, 2, 3, 4, 5 };
        int minValue = 5;
        int maxValue = -1;
         foreach (int i int intList)
           if ((i > minValue) && (i > maxValue))
                maxValue = i;
         return maxValue;
    }
 
This example returns -1 since there is no integer greater than 5 inside the intList.
Here's the equivalent code using a modern approach.
 
    //Modern code
    private int GetMaxIntValueGreaterThanLocalIntegerLambda()
    {
        List<int> intList = new List<int> { 1, 2, 3, 4, 5 };
        intminValue = 3;
 
        //Get the integers greater than minValue
        var minValueLambda = intList.Where(i => i > minValue);
        //Check if at least one integer was greater than minValue
        if (minValueLambda.Any())
            //Return maximum integer
            return minValueLambda.Max();
        else
            return -1;
    }
 
This time the result will be 5.
First we use the lambda expression i => i > minValue to remove the integers that are less than minValue. Then we simply check if there are possible results using Any() and get the maximum result using Max().
 
Here's what Visual Studio's IntelliSense proposes we should use as an argument to the Where method - Func(int, bool) predicate. Predicate stands for anonymous methods that use boolean expressions testing each element of the given sequence. Since we can use anonymous methods we can also use lambda expressions. There are quite a lot of methods that can accept such arguments. The previous example could as well have been written as
 
    private int GetMaxIntValueGreaterThanLocalIntegerLambdaAny()
    {
        List<int> intList = new List<int> { 1, 2, 3, 4, 5 };
        int minValue = 3;
 
        //Get the integers that are greater than minValue
        if (intList.Any(i => i > minValue))
            //Return maximum integer
            return intList.Max();
        else
            return -1;
 
    }
 
Instead of predicates there are also selector expressions which can modify the return value.
Supposing we wanted to get the square of the previous method's return value. Max method can get lambda expression argument. We can write
 
    private int  GetSquareMaxIntValueGreaterThanLocalInteger()
    {
        List<int> intList = new List<int> { 1, 2, 3, 4, 5 };
        int minValue = 3;
 
        //Get the integers that are greater than minValue
        if (intList.Any(i => i > minValue))
            //Return square of maximum integer
            return intList.Max(i => i * i);
        else
            return -1;
 
    }
 
 
Lambda expressions and anonymous methods.
 
So far we have talked about anonymous methods and lambda expressions and it seems that they have many things in common. Actually, we could say that lambda expressions are kind of a special category of anonymous methods. The reason to prefer lambda expressions to anonymous functions is that they are easier to be used by a developer. I have even met novice developers who where familiar with the Where method but knew nothing concerning lambda expressions, delegates or anonymous functions.
 
Keep in mind these simple expressions we created earlier
Anonymous method  delegate(int i){return i = i * i;};
Lambda expression   i => i * i;
 
This lambda expression can also be written this way
(int i) => { return i * i; };
which makes it similar to the method.
 
You can now see all the things we can omit (if possible) when using lambda expressions.
1) parameter type declaration
2) parenthesis between parameter
3) brackets between body declaration
4) the return keyword
 
Ending up in the much simpler expression i => i * i;
 
As we mentioned, when using lambda expressions you do not have to pay attention to parameter types. Even though the anonymous method explicitly states that i is an integer, the lambda expression does not. Lambda expressions use type inference, that is .NET will deduct what type the variable should be and make things easier for you. If however you feel like this will make things worse, stick with the anonymous method.
 
lambda l
 
Conclusion
 
Lambda expressions, similar to anonymous methods allow you to write simple and easy to read code. We have mentioned the basic points of how they work and why we should use them.

 

 

Reference DotNetHints
Δημοσιεύτηκε στις Πέμπτη, 20 Μαρτίου 2014 10:14 μμ από το μέλος k badas :: 0 σχόλια

Sending AJAX requests

In a previous article we had some talk concerning AJAX. We used AJAX to read some simple file. Even though this may have seemed to be quite nice it is but a simple example of what AJAX can do. Things are going to get more interesting in this article where we will be talking about AJAX requests. In other words, how to exchange data between an html page and a server page depending on the requests parameters.

 

GET and POST

 

HTTP Request Methods, describe what the request is about to do. If this isn't the first time you are dealing with the web, you might have probably heard of the two most common methods, GET and POST.

 

Let's try to describe what these terms actually mean. To begin with, both requests contain information. For example whether we ask for the second page inside a forum or fill out and send a form in a contact page, we send information to the server. However you may be able to tell the difference between these requests. In the first example we are asking the server for data. In the second, it is us who send data to the server. If you understand that, you got the main difference between a GET and a POST request.

 

Since a GET request asks for data everyone can see, its variables are put in the url (query string).

http://dotnethints.com/news?id=16. This is a GET request that will return a news page having id 16.

http://dotnethints.com/contact. This is a POST request that will submit the form, but a user will not be able to see its variables since they are not visible.

That way a POST request is more secure than a GET.

 

Based on the url, a GET request, in contrast to POST, can be cached, bookmarked or be used for every reason the url is all we need.

Since a GET request is used for requesting data, we do not expect to send much data, but in case you do find yourself sending more than a few KBs of data (actual limit depends on the browser you use), keep in mind that you have to use POST as GET will not support such an action.

 

So far, we've talked about HTTP Request Methods. Being part of the HTTP, they apply everywhere; ASP. NET, JAVA, PHP, everywhere. We are now going to see how to use what we've covered to create AJAX requests.

 

 

AJAX and GET

 

Here's a brief reminding of what we did last time. We used the following JavaScript function to get and handle an xml file.

 

function loadXML(url) {

            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 () {

                //Check if you are ready

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

                    //Code that handles the response                  

                }

            }

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

            xmlhttp.send();

        }

 

If you need to refresh your memory this is the article concerning AJAX introduction.

 

We are now going to create a simple search form using pure HTML, where the user will insert his search keyword, and a JavaScript function that will send it to the server asynchronous. The server will process the data and response (since we presume that our full-detailed database knows everything) that the search is successful.

 

Since we are using AJAX everything happens asynchronous. The page will not postback, the user will still see the same page and the server will not need to process the whole of the page.

 

So, here's the form

 

    <div>

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

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

        <br />

        <span id="ResponseSpanID" />

    </div>

 

It looks like this.

 

 

ajax Get form

 

 

 

The ResponseSpanID span will be used to show the message in the server response.

 

And here's the function

 

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) {

                    document.getElementById("ResponseSpanID").innerHTML = xmlhttp.responseText;

                }

            }

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

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

            xmlhttp.send();

        }

 

As you can see all we have to do is create the url we need

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

using the value form the input box. Remember, this is a GET request, so we use the url to send our data.

 

Keep in mind that sending data such as a search keyword using a GET request is not a bad good idea considering what we said earlier. We are asking the server for data, so we will use GET.

 

So far we have used HTML and JavaScript. This means we could request every page we wanted no matter what its platform is. However since this is a .Net site we will request the AjaxAdvanced.aspx page.

 

The page could contain much HTML and code processing but all we need for our little example is this.

 

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

 

and the code behind

 

using System;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        //GET uses the query string

        if (Request.QueryString["search"] != null)

        {

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

 

            //Searching...

            //Supposing search had results

 

            Response.Write("Your search for " + search + " had the following results...");

        }

    }

}

 

I guess the code is quite simple. First we check if we actually have the input we've been expecting. Then we set it to a string and process it. Finally we create the response.

 

Then the response  will be handled by JavaScript

document.getElementById("ResponseSpanID").innerHTML = xmlhttp.responseText;

and presented to the user.

 

The following images describe the actions.

 

ajax GET form

 

ajax GET response

 

 

 

We could easily send more than one variable since urls support multiple variables, e.g.  http://dotnethints.com/blog?search=code&page=2

 

 

AJAX and POST

 

This is how we use GET. POST is quite similar. Let's create a form where the user will submit her email and send a question. This would not be a good example of GET request since we are sending data for the server to store.

 

Here's the HTML code

 

<div>

        <table>

            <tr><td colspan="2">Please insert your email so we can answer your question.</td></tr>

            <tr><td> Email: </td><td><input type="text" id="EmailInputID" /></td></tr>

             <tr><td> Question:</td><td> <input type="text" id="QuestionInputID" /></td></tr>

             <tr><td/><td> <button onclick="submitQuestion()">Submit</button></td></tr>

        </table>

        <span id="ConfirmSpanID" />

    </div>

 

ajax POST

 

and the JavaScript code

 

function submitQuestion() {

            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) {

                    document.getElementById("ConfirmSpanID").innerHTML = xmlhttp.responseText;

                }

            }

           xmlhttp.open("POST", "AjaxAdvanced.aspx", true);

           xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

           var email = document.getElementById("EmailInputID").value;

           var question = document.getElementById("QuestionInputID").value;

           var postVariables = "email=" + email + "&question=" + question;

           xmlhttp.send(postVariables);

}

 

The actual difference between GET and POST in the script is right here:

           xmlhttp.open("POST", "AjaxAdvanced.aspx", true);

           xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

           var email = document.getElementById("EmailInputID").value;

           var question = document.getElementById("QuestionInputID").value;

           var postVariables = "email=" + email + "&question=" + question;

           xmlhttp.send(postVariables);

 

First we use the "POST" keyword, then we need to set the RequestHeader and finally insert the variable in the send() method. The rest is quite the same.

 

Similar this is the server page.

 

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

 

 

using System;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        //POST uses Form variables

        if (Request.Form["email"] != null && Request.Form["question"] != null)

        {

            string email = Request.Form["email"].ToString();

            string question = Request.Form["question"].ToString();

 

            //Submit email and question

 

            Response.Write("Form submitted");

        }

    }

}

 

We check for null variables and then get our data from Request.Form. Then (supposing that our cool site never fails) we show a message to the user.

 

Here's the result.

 

ajax POST

 

 

 

ajax POST response

 

 

 

 

 

Summary

 

We had a look at what GET and POST HTTP Request Methods stand for. GET is used when we want to ask for data and POST when we want to send data. We can combine both methods with AJAX and create advanced AJAX stuff by sending input to server pages.

 

Reference DotNetHints
Περισσότερες Δημοσιεύσεις Επόμενη »