Δημοσιεύτηκε στις Τετάρτη, 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