Oct 28

Scientists build world’s smallest storage device

General 50 Comments »

Currently rated 3.7 by 3 people

  • Currently 3.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Binary
Scientists used a phosphorous atom embedded in a silicon crystal for the experiment

Major breakthrough in quantum computing

Written by Iain Thomson in San Francisco

Scientists are claiming to have made a major breakthrough in quantum computing after managing to store information inside the nucleus of an atom.

The team from Princeton University, Oxford University and the US Department of Energy used both the electron and nucleus of a phosphorous atom embedded in a silicon crystal. Both the electron and nucleus behaved as tiny quantum magnets capable of storing quantum information.

"The electron acts as a middle-man between the nucleus and the outside world, " said John Morton, a research fellow at Oxford's St. John's College.

"It gives us a way to have our cake and eat it – fast processing speeds from the electron, and long memory times from the nucleus."

While memory has been stored in a nucleus for just one tenth of a second, the team managed to keep the information accessible for nearly two seconds. Researchers studying quantum computing recently calculated that if a quantum system could store information for at least one second, error correction techniques could then protect that data for an indefinite period of time.

"Nobody really knew how long a nucleus might hold quantum information in this system," said Steve Lyon, leader of the Princeton team.

"With crystals painstakingly grown by the Berkeley team and very careful measurements, we were delighted to see memory times exceeding the threshold."



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

Oct 22

Singleton design pattern

C# | Design Patterns 76 Comments »

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
IMPORTANT:  The example code which i discussed is attached at the end of this post. You can download it to compile.
 
 
  Singleton assures that there is one and only one instance of a class and provides a global point of access to it.
Why Singleton:
There are number of cases in programming when we want a class to have only one instance. e.g.
  •  Sometimes we want just a single instance of a class to exist in the system.
  • We need to have that one instance easily accessible
  • And we want to ensure that additional instances of the class can not be
    created
How to Implement Singleton pattern in C Sharp:
Ok, now we have understand that why we need the singleton, now the question is that how to implement this?
We will do two things to implement the singleton pattern which are given below:
  1. Declare a static Boolean variable to keep track that instance of the class is created or not.
  2. The constructor of the class should be private.
Now lets dig into the above two points that how these two points will be used to implement the singleton:

First we stated that we will declare a static boolean variable to keep track that the instance of the class is created or not. Secondly we stated that we will make that constructor of that class private.

This was all theory, now lets try to make our hands dirty with the code.

First of all I need to declare my class which should have the one and only one instance. Lets say I gave it the name "MySingleton". Now I will write code to accommodate my two points which I mentioned previously.
///
/// The following class will behave as singleton
///
class MySingleton
{
// The following is a static variable which
// will be used to keep the track that instance
// of this class is created or not.
private static bool IsAlreadyCreated = false;
///
/// Constructor of the class. It is declared private
/// so no one would be able to create the instance of
/// this class.
///
private MySingleton()
{
// I declared it private so now no one
// would be able to create the instance
// this class

}
///
/// It is static method. I declared it static, because
/// I have designed the class in such a way that the
/// instance of this class can not be created. And We know
/// that static method can be accessed without declaring
/// the instance of the class.
/// This method will check the static boolean variable which
/// we declared in the class. If the boolean variable is false
/// then It will return the instance of the MySingleton class.
/// Else if will return null
///
///
public static MySingleton GetSingletonHandle()
{
if (!IsAlreadyCreated)
{
IsAlreadyCreated = true;
return new MySingleton();
}
else
{
throw new MyException("Get last, I can not give you more than one handle");
}
}
}

The above code is commented and self explanatory. Now lets start write code to check our class.

In the Main program write the following line:
MySingleton _MySingleton = MySingleton.GetSingletonHandle();
if (_MySingleton != null)
{
Console.WriteLine("Instance is created");
}
else
{
Console.WriteLine("I cant not give more than one handle");
}

In the above code I am trying to get the "GetSingletonHandle()" from the MySingleton class. Here this point must be noted that the following line
MySingleton _MySingleton is just the object of the MySingleton class. It is not instantiating the instance of the class. The instance is created by using the new keyword, like this:
MySingleton _MySingleton = new MySingleton();

Ok, after getting the "GetSingletonHandle()" from the MySingleton class, I am checking that what I got (i.e. Is it null or not).
What is the meaning if I am getting null??
It means that the instance of this class was already created, and if its not null then it means that we have got the GetSingletonHandle.

Out put:
If you run program you will get the out put some thing like this:

You got the Handle

Upto this point we are almost finished with the Singleton design pattern. But I am not satisfied with the Main program which is trying to get the GetSingletonHandle(), Why?
  • Do you think that it is a good approach to always check that GetLogErrorhandle() is null or not?
If yes, then you are wrong and if no then also you are wrong. :)
If your answer is yes, then I must say that bad developers like me forgot to check these kinds of basic thing that the object on which I am going to perform some operation is null or not. So to make the life easy for the developers like me It would be good to design the singleton to throw a custom exception instead of sending null if its object is already created.

If your answer was no, then again you are wrong becasue there is no fault in the singleton class, It was my mistake that I always forgot to check the basic null checks. :)

So why not to write a small class of my own custom exception. And in the singleton class I will make use of that custom exception (i.e. if the instance was already created then throw the exception rather than throwing the null).

Ok, so here is the code of my Custome Exception class:


public class MyException: Exception
{
public SingletonException(string s) : base(s)
{
}
}

Now lets change in the GetSingletonHandle function of our Singleton class to make use of the above exception class.

public static MySingleton GetSingletonHandle()
        {
            if (!IsAlreadyCreated)
            {
                IsAlreadyCreated = true;
                return new MySingleton();
            }
            else
            {
                throw new MyException("Get last, I can not give you more than one handle");
            }
        }

}
}

Now run the program, you will get the same output. To check our complete program which we have written, we need to change our Main program, so that we can check that what happened If I asked my singleton to give me more than one handle.

My Complete program is now given below:

using System;
using System.Collections.Generic;
using System.Text;

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                MySingleton _MySingleton = MySingleton.GetSingletonHandle();
                if (_MySingleton != null)
                {
                    Console.WriteLine("Instance is created");
                }
                MySingleton _MySingleton2 = MySingleton.GetSingletonHandle();
            }
            catch (Exception ex)
            {
                
                Console.WriteLine(ex.ToString());
            }

        }
    }

    /// <summary>
    /// The following class will behave as singleton
    /// </summary>
    class MySingleton
    {
        // The following is a static variable which
        // will be used to keep the track that instance
        // of this class is created or not.
        private static bool IsAlreadyCreated = false;
        /// <summary>
        /// Constructor of the class. It is declared private
        /// so no one would be able to create the instance of
        /// this class.
        /// </summary>
        private MySingleton()
        {
            // I declared it private so now no one
            // would be able to create the instance
            // this class

        }
        /// <summary>
        /// It is static method. I declared it static, because
        /// I have designed the class in such a way that the
        /// instance of this class can not be created. And We know
        /// that static method can be accessed without declaring
        /// the instance of the class.
        /// This method will check the static boolean variable which
        /// we declared in the class. If the boolean variable is false
        /// then It will return the instance of the LogError class.
        /// Else if will return null
        /// </summary>
        /// <returns></returns>
        public static MySingleton GetSingletonHandle()
        {
            if (!IsAlreadyCreated)
            {
                IsAlreadyCreated = true;
                return new MySingleton();
            }
            else
            {
                throw new MyException("Get last, I can not give you more than one handle");
            }
        }
    }

    public class MyException : Exception
    {
        //new exception type for singleton classes
        public MyException(string s)
            : base(s)
        {
        }
    }
}




In the main program I tried to get the GetSingletonHandle() two times. first time it gave me the handle and the second time I got the exception. the screen shot of the out put is given below:




 
 
 If you are giving interview somewhere then the above explanation is good enough to show that you actually know about the singleton, but there are some issue which still needs to be covered. i.e.
 
  • What if two threads called the singleton at the same time? Well, the answer is that the two threads could create more than one instance of the class. How to overcome this issue? There are different ways to handle this issue. The first one is that make the  GetSingletonHandle() synchronized.
If you are discussing singleton with some one then they might ask you that what is Lazy instantiation and what is eager instantiation. 
The approach which we used in our singleton is called the lazy instantiation whic is "create the instance if it does not exists".
 
Eager instantiation is another apprach for implementing the singleton design pattern. In eager instantiation we create the singleton instance in a static initilizer. This is guaranted to be thread safe. So If I want to change my class to implement the eager then I will follow the following steps:
 
  •  Declare the static varible of the type singleton class (In my case it is MySingleton) and initilize it in the class. i.e.
           private static MySingleton mySingleton = new MySingleton ();
  • Now change the  GetSingletonHandle()  like this:
        public static MySingleton GetSingletonHandle()
        {
            return
mySingleton ;
        }

         
That is it. Now we have implemented the Singleton pattern using the eager instantiation.
 
You can change the singleton class according to the requirments but the bottom line is that singleton class is a class which have one and only one instance.Now its upto you that how do u ensure it in your domain and according to your requirments.
 
Regards,
Shahid riaz bhatti
Microsoft certified professional

Program.cs (2.54 kb)



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

Oct 19

Abstract Factory pattern

C# | Design Patterns 47 Comments »

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Abstract Factory Method:

 

Abstract factory method created the object of related classes or dependent classes without specifying their concrete class. 

 

Gang of four (GoF) defination:

 

According to the Gof the abstract factory pattern provide an interface for creating families of related or dependent objects without specifying their concrete classes. 

 

Where to use it:

Abstract factory method can be used in the following scenarios:

  • When a system should be independent of how its products are created, composed, and represented.
  • A class can not anticipate the class of object it must create
  • A system must use just one of a set of families of product.

Advantage:

One of the main advantages of Abstract Factory Pattern is that it isolates the concrete classes that are generated. The names of actual implementing classes are not needed to be known at the client side. Because of the isolation, you can change the implementation from one factory to another.


Example:

I am giving a very simple example. When I was studying C++ in college then our teacher taught us a concept of polymorphism by giving a very simple example. btw the polymorphism is that " The same function call behaves differently on every call"..I practically implemented polymorphism in C++ by using function overrding and inheritance. The assignment was that We have a living things all around us which includes human being, plant etc. Human beings can walk but the plant can not walk. So to solve this problem I made a c++ example in which I made an abstract class of Living thing and then inherited two class from it (i.e. Plant and Human being). Then I override the CanWalk method of the abstract class in the child classes with their own body.

 

Today I will take the same example for the abstract factory method. My code of the abstract factory method is given below and also the .cs file is attached at the end of this post.

using System;

namespace Shahid
{
    // MainApp test application

    class MainApp
    {
        public static void Main()
        {

            LivingFactory factory = new ConcreteLiving1();
            Client c1 = new Client(factory);
            c1.Run();

            LivingFactory factory2 = new ConcreteLiving2();
            Client c2 = new Client(factory2);
            c2.Run();


        }
    }

    // "AbstractFactory whicg is Living Factory"

    abstract class LivingFactory
    {
        public abstract AbstractLivingAnimal CreateLivingAnimal();
        public abstract AbstractLivingPlant CreateLivingPlant();
    }

    // "ConcreteLiving1"

    class ConcreteLiving1 : LivingFactory
    {
        public override AbstractLivingAnimal CreateLivingAnimal()
        {
            return new LivingAnimal1();
        }
        public override AbstractLivingPlant CreateLivingPlant()
        {
            return new LivingPlant1();
        }
    }

    // "ConcreteLiving2"

    class ConcreteLiving2 : LivingFactory
    {
        public override AbstractLivingAnimal CreateLivingAnimal()
        {
            return new LivingAnimal2();
        }
        public override AbstractLivingPlant CreateLivingPlant()
        {
            return new LivingPlant2();
        }
    }

    // "Abstract Living Animal

    abstract class AbstractLivingAnimal
    {
        public abstract void CanWalk(AbstractLivingPlant plant);
    }

    // "AbstractLiving plant"

    abstract class AbstractLivingPlant
    {
        
    }

    // "Living Animal 1"

    class LivingAnimal1 : AbstractLivingAnimal
    {

        public override void CanWalk(AbstractLivingPlant plant)
        {
            Console.WriteLine(this.GetType().Name + " can walk but " + plant.GetType().Name + " can not");
        }
    }

    // "Living Plant 1"

    class LivingPlant1 : AbstractLivingPlant
    {
      
    }

    class LivingAnimal2 : AbstractLivingAnimal
    {

        public override void CanWalk(AbstractLivingPlant plant)
        {
            Console.WriteLine(this.GetType().Name + " can walk but " + plant.GetType().Name + " can not");
        }
    }

    // "Living plant 2"

    class LivingPlant2 : AbstractLivingPlant
    {
        
    }
    // "Client" - the client code

    class Client
    {
        private AbstractLivingAnimal Animal;
        private AbstractLivingPlant Plant;

        // Constructor
        public Client(LivingFactory livingThing)
        {
            Animal = livingThing.CreateLivingAnimal();
            Plant = livingThing.CreateLivingPlant();
        }

        public void Run()
        {
              Animal.CanWalk(Plant);
        }
    }
}

 
In the above example we can see that in the main program we didn't called the LivingAnimal1,LivingAnimal2,LivingPlant1 and LivingPlant3 class directly. The code is given below:

            LivingFactory factory = new ConcreteLiving1();
            Client c1 = new Client(factory);
            c1.Run();

            LivingFactory factory2 = new ConcreteLiving2();
            Client c2 = new Client(factory2);
            c2.Run();

In the above code you can see that we have created the instance of an abstract class LivingFactory and instantiated it by the ConcreteLiving1 class. In the code you can see that the ConcreteLiving class is inherited from the abstract class LivingFactory. Then in the next line we created the object of the Client class and then called the Run method of the Client class. The Client's constructor take the parameter of Type LivingFactory and produces the output according to the parameter passed to it. But in the main program we dont know that what will be the out put of Client.Run(). Also if your business logic changes then you can change theimplementation of the Factory classes witout affecting the client side code.

In the example we can see that our main program is independent that how the LivingAnimal1,LivingAnimal2,LivingPlant1 and LivingPlant2 are created and composed.

 


 

Regards,

Shahid Riaz Bhatti

Microsoft certified professional

Program.cs (2.86 kb)



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

Oct 17

Microsoft Sticks to Windows 7 Name for Next OS

General 67 Comments »

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
 
Microsoft Sticks to Windows 7 Name for Next OS

DailyTech

Microsoft Windows Vista is still considered relatively new on the market and some users have not yet upgraded from Windows XP to Vista for a variety of reasons. Microsoft is continuing to allow certain types of computers to run Windows XP thanks to its lower cost and overhead.

Despite being released less than two years ago to the general public, Microsoft is hard at work on the replacement for Vista. DailyTech reported that the next Microsoft PC operating system – codenamed Windows 7 – had its first setback in September. Microsoft had planned to offer the first Windows 7 Beta in October of 2008, that date slipped to December 2008.

Microsoft’s Mike Nash wrote in a blog post that Microsoft would be providing a pre-beta version of Windows 7 exclusively to developers to attendees at the PDC and WinHEC developers conferences.

Nash also wrote in the blog post that Microsoft has decided on the final name for the next Windows operating system, and it’s one we are familiar with. Microsoft has decided to call the operating system Windows 7. This is the first time a Windows operating system has kept its codename as the official name.

Nash wrote, “The decision to use the name Windows 7 is about simplicity. Over the years, we have taken different approaches to naming Windows. We’ve used version numbers like Windows 3.11, or dates like Windows 98, or ‘aspirational’ monikers like Windows XP or Windows Vista. And since we do not ship new versions of Windows every year, using a date did not make sense. Likewise, coming up with an all-new ‘aspirational’ name does not do justice to what we are trying to achieve, which is to stay firmly rooted in our aspirations for Windows Vista, while evolving and refining the substantial investments in platform technology in Windows Vista into the next generation of Windows.”

Details on Windows 7 are still scant, but Nash says that Microsoft will be sharing more in the coming weeks. To this point, feature wise it is known that the OS will support multi-touch and use the same driver system as Windows Vista.



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

Oct 15

HTML Encoding

ASP.Net | C# | General | Random Thoughts | Tips and Tricks | Visual Studio 11 Comments »

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
There are certain characters that have a special meaning in HTML. For example, the angle brackets (< >) are always used to create tags. This can cause problems if you actually want to use these characters as part of the content of your web page. For example, imagine you want to display this text on a web page:
Enter a word <here>
If you try to write this information to a page or place it inside a control, you end up with this instead:
Enter a word
The problem is that the browser has tried to interpret the <here> as an HTML tag. A similar problem occurs if you actually use valid HTML tags. For example, consider this text:
To bold text use the <b> tag.
Not only will the text <b> not appear, but the browser will interpret it as an instruction to make the text that follows bold. To overcome this automatic behavior, you need to convert potential problematic values to their HTML equivalents. For example, < becomes &lt; in your final HTML page, which the browser displays as the < character.
The following table lists some special characters that need to be encoded.
 
Result Description Encoding
  Non breaking space
&nbsp;
<
Less-than symbol
&lt
>
Greate-than symbol &gt
&
Ampersand

&amp

"
Quotation mark
&quote
 
Alternate solution:

  This problem can also be solved in another way i.e. by using the innerText property of the server control. InnerText property automatically converts any illegal characters into their HTML equivalent. However, this won’t help if you want to set a tag that contains a mix of embedded HTML tags and encoded characters. It also won’t be of any use for controls that don’t provide an InnerText property, such as the Label web control . In these cases, we can use the HttpServerUtility.HtmlEncode() method to replace the special characters. (Remember, an HttpServerUtility object is provided through the Page.Server property.)

 
 
Here’s an example:
// Will output as "Enter a word &lt;here&gt;" in the HTML file, but the
// browser will display it as "Enter a word <here>".

ctrl.InnerHtml = Server.HtmlEncode("Enter a word <here>");
// Or consider this example, which mingles real HTML tags with text that needs to be
// encoded:
ctrl.InnerHtml = "To <b>bold</b> text use the ";
ctrl.InnerHtml += Server.HtmlEncode("<b>") + " tag.";

 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , , ,