Translate

Saturday 28 June 2014

Differences between Hashtable and Dictionary

Dictionary:

·         It returns error if we try to find a key which does not exist.
·         It is faster than a Hashtable because there is no boxing and unboxing.
·         Only public static members are thread safe.
·         Dictionary is a generic type which means we can use it with any data type.
·         static typing (and compile-time verification)

Hashtable:

·         It returns null if we try to find a key which does not exist.
·         It is slower than dictionary because it requires boxing and unboxing.
·         All the members in a Hashtable are thread safe,

·         Hashtable is not a generic type,

        DICTIONARY VS HASHTABLE in C# REAL TIME EXAMPLES

        Differences Between Hashtable and Dictionary

        1. Hashtable is threadsafe and while Dictionary is not.
        // Creates a synchronized wrapper around the Hashtable.
          Ex:Hashtable myhashtable = Hashtable.Synchronized(hash);
        The Synchronized method is thread safe for multiple readers and writers. Furthermore, the synchronized wrapper ensures that there is only one writer writing at a time.

        2. Dictionary is types means that the values need not to boxing while Hashtable 
            values  need to be boxed or unboxed because it stored the  values and keys as 
            objects.         
        3. When you try to get the value of key which does not exists in the collection, the 
            dictionary throws an exception of 'KeyNotFoundException' while hashtable returns 
            null value.
        4. When using large collection of key value pairs hashtable would be considered more 
            efficient than dictionary.

        5. When we retrieve the record in collection the hashtable does not maintain the order 
            of entries while dictionary maintains the order of entries by which entries were added.

        6. Dictionary relies on chaining whereas Hashtable relies on rehashing.

        7.Dictionary is a strongly typed generic collection while hashtable collection takes a object datatype

     Example

        public void MethodHashTable()
        {
            Hashtable objHashTable = new Hashtable();
            objHashTable.Add(1, 100);    // int
            objHashTable.Add(2.99, 200); // float
            objHashTable.Add('A', 300);  // char
            objHashTable.Add("4", 400);  // string

            lblDisplay1.Text = objHashTable[1].ToString();
            lblDisplay2.Text = objHashTable[2.99].ToString();
            lblDisplay3.Text = objHashTable['A'].ToString();
            lblDisplay4.Text = objHashTable["4"].ToString();

            // ----------- Not Possible for HashTable ----------
            //foreach (KeyValuePair<string, int> pair in objHashTable)
            //{
            //    lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
            //}
        }


        Dictionary Example 

        public void MethodDictionary()
          {
            Dictionary<string, int> dictionary = new Dictionary<string, int>();
            dictionary.Add("cat", 2);
            dictionary.Add("dog", 1);
            dictionary.Add("llama", 0);
            dictionary.Add("iguana", -1);

            //dictionary.Add(1, -2); // Compilation Error

            foreach (KeyValuePair<string, int> pair in dictionary)
            {
                lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
            }

          }






What is the difference between ArrayList and Generic List in C#?

Arraylist:
  1. It is like Array of objects.
  2. "System.Collections" is the Namespace for Arraylist. It automatically added to namespace section in aspx.cs page.
  3. We need not to specify object type arraylist going to contain.
  4. In arraylist each item is stored as object. And return value as object.
  5. It needs to box and unbox the elements.
  6. No type safety (Compile time)
List<T>:



  1. "System.Collections.Generic" is the Namespace for List. We need to add this.
  2. We need to specify object type which type of elements it contain. 
  3. Ex: List<string> StrObj=new List<string>();
  4. From the above example StrObj will only store string objects.
  5. It doesn't need.
  6. Type safety (compile time)
Example: 

namespace Example
{
   class Program

    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add("hello");
            list.Add(new Program()); // Oops! That's not meant to be there...
            list.Add(4);
            foreach (object o in list)
            {
                Console.WriteLine(o.ToString());
            }
            List<string > lstString = new List<string>();
            lstString.Add("ABCD");
            lstString.Add(new Program());   //Compiler error
            lstString.Add(4);   // Compiler Error
            foreach (object o in lstString)
            {
                Console.WriteLine(o.ToString());
            }  }

}


WIPO Patent Translation (language)

https://www3.wipo.int/patentscope/translate/translate.jsf?interfaceLanguage=en

Thursday 26 June 2014

Why we can't create object to ABSTRACT & INTERFACE classes?

             We cannot create object for interface and abstract class. Because, it is possible that some methods are not implemented within interface or abstract class. In the case of an interface, non of the methods are implemented and an abstract class, abstract method cannot implemented.

Without a full implementation, how could we instantiate the class.

Runtime Polymorphism and Method hiding

Runtime polymorphism:

By runtime polymorphism we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding.



namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class shape
        {
            public int _radius = 5;
            public virtual double getArea()
            {
                return 0;
            }
        }
        public class circle : shape
        {
            public override double getArea()
            {
                return 3.14 * _radius * _radius;
            }
        }
        public class sphere : shape
        {
            public override double getArea()
            {
                return 4 * 3.14 * _radius * _radius;
            }
        }
        static void Main(string[] args)
        {
            shape objBaseRefToDerived = new circle();  // run time polymorphism
            objBaseRefToDerived.getArea();

            shape objBaseRefToDerived1 = new sphere();  // run time polymorphism
            objBaseRefToDerived1.getArea();

            Console.ReadLine();
        }
    }
}

we want calculate area of circle, at the time we have to create object like

BaseclassName obj=derivedclassName()  

--------------------------------------------------------------------------------------------------
Method Hiding:

namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {

            public new void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output--> Show From Base Class.

            Console.ReadLine();
        }
    }
}

Output is:? Show From Base Class.

Tuesday 24 June 2014

create Directory and copy file from location and put into created Directory

  public void Test1()
    {

        string fileLocation = WebConfigurationManager.AppSettings["FileCreationLoc"].ToString();
        string SourceLocation = WebConfigurationManager.AppSettings["FileSource"].ToString();

        SourceLocation = SourceLocation + "Upload";
        string FileName = string.Empty;
        List<string> list = new List<string>();
        list.Add("Gksamy");
        list.Add("Alex");
        list.Add("lenin");

        for (int i = 0; i < list.Count; i++)
        {
            string path = fileLocation + list[i];
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);

                string[] Source_path = Directory.GetFiles(SourceLocation);
                for (int j = 0; j <= Source_path.Length - 1; j++)
                {
                    FileInfo file = new FileInfo(Source_path[j]);
                    string F_Name = file.Name.ToLower();
                    if (F_Name.Contains(list[i].ToLower()))
                    {
                        FileName = file.Name;
                        var source = Path.Combine(SourceLocation, FileName);
                        var destination = Path.Combine(fileLocation + list[i], FileName);

                        File.Copy(source, destination);
                    }
                }
            }
            else
            {
                Directory.CreateDirectory(path);

                string[] Source_path = Directory.GetFiles(SourceLocation);
                for (int j = 0; j <= Source_path.Length - 1; j++)
                {
                    FileInfo file = new FileInfo(Source_path[j]);
                    string F_Name = file.Name.ToLower();
                    if (F_Name.Contains(list[i].ToLower()))
                    {
                        FileName = file.Name;
                        var source = Path.Combine(SourceLocation, FileName);
                        var destination = Path.Combine(fileLocation + list[i], FileName);

                        File.Copy(source, destination);
                    }
                }
            }
        }
    }


Web.config
<appSettings>
<add key="FileCreationLoc" value="C:\College\Student\"/>

<add key="FileSource" value="C:\colleges\"/>
</appSettings>

Monday 23 June 2014

Run multiply instances of the same method simultaneously in c# without data loss?

 namespace ConsoleApplication9
{
    using System.Collections.Generic;
    using System.Threading.Tasks;

    class Program
    {
        static void Main()
        {
            var numbers = new List<int>();

            for (int a = 0; a <= 70; a++)
            {
                for (int b = 0; b <= 6; b++)
                {
                    for (int c = 0; c <= 10; c++)
                    {
                        var unmodifiedA = a;
                        var unmodifiedB = b;
                        var unmodifiedC = c;

                        Task.Factory.StartNew(() => MyMethod(numbers, unmodifiedA, unmodifiedB, unmodifiedC));
                    }
                }
            }
        }

        private static void MyMethod(List<int> nums, int a, int b, int c)
        {
            //Really a lot of stuffs here
        }
    }
}

Model View Controller in Asp.Net MVC

Model 

The Model represents a set of classes that describes the business logic and data. It also defines business rules for how the data can be changed and manipulated.
Moreover, models in Asp.Net MVC, handles the Data Access Layer by using ORM tools like Entity Framework or NHibernate etc. By default, models are stored in the Models folder of the project.

The Model can be broken down into several different layers as given below:

  1. Objects or ViewModel Layer

    This layer contains simple objects or complex objects which are used to specify strongly-typed view. These objects are used to pass data from controller to strongly-typed view and vice versa. The classes for these objects can have specific validation rules which are defined by using data annotations. Typically, these classes have those properties which you want to display on corresponding view/page.
  2. Data Access Layer

    This layer provides objects to access and manipulate the database of your application. Typically, this layer is made by using ORM tools like Entity Framework or NHibernate etc.
  3. Business Layer

    This layer helps you to implement your business logic and validations for your application. This layer make use of Data Access Layer for persisting data into database. Also, this layer is directly invoked by the Controller to do processing on input data and sent back to view.

View 

The View is responsible for transforming a model or models into UI. The Model is responsible for providing all the required business logic and validation to the view. The view is only responsible for displaying the data, that is received from the controller as the result.
Moreover, views in Asp.Net MVC, handles the UI presentation of data as the result of a request received by a controller. By default, views are stored in the Views folder of the project.

Controller 

The Controller is responsible for controlling the application logic and acts as the coordinator between the View and the Model. The Controller receive input from users via the View, then process the user's data with the help of Model and passing the results back to the View.
Moreover, controllers in Asp.Net MVC, respond to HTTP requests and determine the action to take based upon the content of the incoming request. By default, controllers are stored in the Controllers folder of the project.

Thursday 19 June 2014

Design Patterns in .Net

Common Design Patterns in C# 4.0
Design Patterns provide standardized and efficient solutions to software design and programming problems that are re-usable in your code. Software Architects and developers use them to build high quality robust applications.

1.    Creational Design Patterns
These patterns deal with the process of objects creation in such a way that they can be decoupled from their implementing system. This provides more flexibility in deciding which objects need to be created for a given use case/ scenario. There are as follows:
  • Factory Method : Create instances of derived classes
  • Abstract Factory : Create instances of several classes belonging to different families
  • Builder : Separates an object construction from its representation
  • Prototype : Create a duplicate object or clone of the object
  • Singleton : Ensures that a class can has only one instance
2.    Structural Design Patterns
These patterns deal with the composition of objects structures. The concept of inheritance is used to compose interfaces and define various ways to compose objects for obtaining new functionalities. There are as follows:
·         Adapter : Match interfaces of different classes
·         Bridge : Separates an object’s abstraction from its implementation
·         Composite : A tree structure of simple and composite objects
·         Decorator : Add responsibilities to objects dynamically
·         Façade : A single class that represents an entire complex system
·         Flyweight : Minimize memory usage by sharing as much data as possible with similar objects
·         Proxy : Provides a surrogate object, which references to other object
3.    Behavioral Design Patterns
These patterns deal with the process of communication, managing relationships, and responsibilities between objects. There are as follows:
·         Chain of Responsibility: Passes a request among a list or chain of objects.
·         Command: Wraps a request under an object as a command and passed to invoker object.
·         Interpreter
·         Iterator
·         Mediator
·         Memento
·         Observer
·         State
·         Strategy
·         Visitor
·         Template Method

Creational Design Patterns

a.

Ref:
http://www.dotnet-tricks.com/Tutorial/designpatternslist

http://www.dotnet-tricks.com/Tutorial/designpatterns/NTEH250513-Gang-of-Four-(GOF)-Design-Patterns-in-.Net-.html

Wednesday 18 June 2014

Bind Gridview from Javascript

 <asp:Button ID="Button2" runat="server" BorderWidth="1px" CssClass="btn" OnClick="test"
        Style="display: none" />

<script language="javascript" type="text/javascript">

        function CallClick() {
           document.getElementById('Button2').click();
        }
    </script>

 protected void test(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("Test");
        cmd.Connection = con;
        cmd.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        GridView1.DataSource = dt;
        GridView1.DataBind();

    }



Ref:  (other way)

http://www.aspsnippets.com/Articles/Populate-ASPNet-GridView-by-binding-DataSet-Client-Side-using-jQuery-AJAX.aspx


http://stackoverflow.com/questions/20465104/populating-gridview-using-ajax

Monday 16 June 2014

Generic Collections in C#

Collections

In this chapter we will deal with C# collections. The .NET framework provides specialized classes for data storage and retrieval. In one of the previous chapters, we have described arrays. Collections are enhancement to the arrays.
There are two distinct collection types in C#. The standard collections, which are found under the System.Collections namespace and the generic collections, under System.Collections.Generic. The generic collections are more flexible and are the preferred way to work with data. The generic collections or generics were introduced in .NET framework 2.0. Generics enhance code reuse, type safety, and performance.

http://people.cs.aau.dk/~normark/oop-csharp/html/notes/collections_themes-list-sect.html

http://www.dotnet-tricks.com/Tutorial/csharp/U08E301212-Difference-between-Generics-and-Collections-with-example.html

http://zetcode.com/lang/csharp/collections/

http://www.onlinebuff.com/article_what-are-generics-in-c-using-an-example_33.html

http://www.c-sharpcorner.com/UploadFile/abhishekbhatore/GenericTypeWithSample07292005092634AM/GenericTypeWithSample.aspx



NULL and Undefined and == and === difference

NULL and Undefined

In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:
var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined
null is an assignment value. It can be assigned to a variable as a representation of no value:
var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object


==  and  ===

=== and !== are strict comparison operators:
JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:
·         Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
·         Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
·         Two Boolean operands are strictly equal if both are true or both are false.
·         Two objects are strictly equal if they refer to the same Object.
·         Null and Undefined types are == (but not ===). [I.e. Null==Undefined (but not Null===Undefined)]


<script type="text/javascript" language="javascript">
        function test() {
            var a;
            alert(a);

            var b = null
            alert(b);

            if (a == b) {
                alert('==');
            }

            if (a === b) {
                alert('===');
            }
        }
   
    </script>

Here are some major differences between HTTP and HTTPS:
HTTP
HTTPS
URL begins with “http://”
URL begins with “https://”
It uses port 80 for communication
It uses port 443 for communication
Unsecured
Secured
Operates at Application Layer
Operates at Transport Layer
No encryption
Encryption is present
No certificates required
Certificates required




HTTP vs HTTPS: Similarities and Differences
What is HTTPS?

HTTPS (Hypertext Transfer Protocol over Secure Socket Layer, or HTTP over SSL) is a web protocol developed by Netscape.

One can say: HTTPS = HTTP + SSL

HTTPS uses Secure Socket Layer (SSL) as a sublayer under its regular HTTP application layering.

Need of HTTPS:

Hypertext Transfer Protocol (HTTP) is a protocol for transmitting and receiving information across the Internet. HTTP serves as a request and response procedure that all agents on the Internet follow so that information can be rapidly, easily, and accurately disseminated between servers, which hold information, and clients, who are trying to access it. You normally use HTTP when you are browsing the web, its not secure, so someone can eavesdrop on the conversation between your computer and the web server. In many cases, clients may be exchanging confidential information with a server, which needs to be secured in order to prevent unauthorized access. For this reason, https, or secure http, was developed by Netscape corporation to allow authorization and secured transactions.

Similarity between HTTP and HTTPS:

In many ways, https is identical to http, because it follows the same basic protocols. The http or https client, such as a Web browser, establishes a connection to a server on a standard port. When a server receives a request, it returns a status and a message, which may contain the requested information or indicate an error if part of the process malfunctioned. Both systems use the same Uniform Resource Identifier (URI) scheme, so that resources can be universally identified. Use of https in a URI scheme rather than http indicates that an encrypted connection is desired.

Difference between HTTP and HTTPS:

1. URL begins with “http://" in case of HTTP while the URL begins with “https://” in case of HTTPS.
2. HTTP is unsecured while HTTPS is secured.
3. HTTP uses port 80 for communication while HTTPS uses port 443 for communication.
4. HTTP operates at Application Layer while HTTPS operates at Transport Layer.
5. No encryption is there in HTTP while HTTPS uses encryption.
6. No certificates required in HTTP while certificates required in HTTPS.

How HTTPS works?

For HTTPS connection, public key and signed certificates are required for the server.
When using an https connection, the server responds to the initial connection by offering a list of encryption methods it supports. In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities. After this is done, both parties exchange the encrypted information after ensuring that both are using the same key, and the connection is closed. In order to host https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity. Most certificates are verified by a third party so that clients are assured that the key is secure.
In other words, we can say, HTTPS works similar to HTTP but SSL adds some spice in it.

HTTP includes the following actions:

1. The browser opens a TCP connection. 
2. The browser sends a HTTP request to the server
 
3. The server sends a HTTP response to the browser.
 4. The TCP connection is closed.

SSL will include the following actions:

1. Authenticate the server to the client. 
2. Allow the client and server to select the cryptographic algorithms, or ciphers, that they both support.
 
3. Optionally authenticate the client to the server.
 
4. Use public-key encryption techniques to generate shared secrets.
 
5. Establish an encrypted SSL connection.
6. Once the SSL connection is established the usual transfer of HTTP requests will continue.

Where should https be used?

HTTPS should be used in Banking Websites, Payment Gateway, Shopping Websites, Login Pages, Emails (Gmail offers HTTPS by default in Chrome browser) and Corporate Sector Websites. For example:


Beware of using Credit Card Numbers on Internet:  If a website ever asks you to enter your credit card information, you should automatically look to see if the web address begins with https://. If it doesn't, there's no way you're going to enter sensitive information like a credit card number!

Browser integration

Most browsers display a warning if they receive an invalid certificate. Older browsers, when connecting to a site with an invalid certificate, would present the user with a dialog box asking if they wanted to continue. Newer browsers display a warning across the entire window. Newer browsers also prominently display the site's security information in the address bar. Extended validation certificates turn the address bar green in newer browsers. Most browsers also display a warning to the user when visiting a site that contains a mixture of encrypted and unencrypted content.