Buy Electronics

Friday, August 27, 2010

SQL Questions and Answers

Difference between Store Procedure and Trigger?

* we can call stored procedure explicitly.
* but trigger is automatically invoked when the action defined in trigger is done.
ex: create trigger after Insert on
* this trigger invoked after we insert something on that table.
* Stored procedure can't be inactive but trigger can be Inactive.
* Triggers are used to initiate a particular activity after fulfilling certain condition.It need to define and can be enable and disable according to need.

What is the advantage to use trigger in your PL?

Triggers are fired implicitly on the tables/views on which they are created. There are various advantages of using a trigger. Some of them are:

* Suppose we need to validate a DML statement(insert/Update/Delete) that modifies a table then we can write a trigger on the table that gets fired implicitly whenever DML statement is executed on that table.
* Another reason of using triggers can be for automatic updation of one or more tables whenever a DML/DDL statement is executed for the table on which the trigger is created.
* Triggers can be used to enforce constraints. For eg : Any insert/update/ Delete statements should not be allowed on a particular table after office hours. For enforcing this constraint Triggers should be used.
* Triggers can be used to publish information about database events to subscribers. Database event can be a system event like Database startup or shutdown or it can be a user even like User loggin in or user logoff.


What the difference between UNION and UNIONALL?

Union will remove the duplicate rows from the result set while Union all does'nt.

What is the difference between TRUNCATE and DELETE commands?

Both will result in deleting all the rows in the table .TRUNCATE call cannot be rolled back as it is a DDL command and all memory space for that table is released back to the server. TRUNCATE is much faster.Whereas DELETE call is an DML command and can be rolled back.

Explain normalization ?
Normalization means refining the redundancy and maintain stabilization. there are four types of normalization :
first normal forms, second normal forms, third normal forms and fourth Normal forms.

How to find out the database name from SQL*PLUS command prompt?
Select * from global_name;
This will give the database name which u r currently connected to.

What is difference between Co-related sub query and nested sub query?

Correlated subquery are used for row-by-row processing.Each subquery is executed once for every row of the outer query.It is one way of reading every row in a table and
comparing the values in each row against the related data.

Example:
select e1.emp_name, e1.emp_salary, e1.emp_dept from employee e1 where e1.emp_salary
= (select max(emp_salary) from employee e2 where e2.emp_dept = e1.emp_dept)

Nested subquery runs only once for the entire nesting (outer) query. It does not contain any reference to the outer query row.
It is a SELECT query that is nested inside a SELECT, UPDATE, INSERT, or DELETE SQL query
Example:
SELECT Model FROM Product
WHERE ManufacturerID IN (SELECT ManufacturerID FROM Manufacturer
WHERE Manufacturer = 'IBM')

The nested query above will select all models from the Product table manufactured by IBM.

Tuesday, July 13, 2010

Static in C#

C# – Static Members

The main features of a static class are:

* They only contain static members.
* They cannot be instantiated.
* They are sealed.
* They cannot contain Instance Constructors .
* We can hide a base class static method in a derived class by using the keyword "new".

A C# class can contain both static and non-static members.
When we declare a member with the help of the keyword "static", it becomes a static member.A static member belongs to the class rather than to the objects of the class.

Hence static members are also known as class members and non-static members
are known as 'instance members'.


In C#, data fields, member functions, properties and events can be declared
either as static or non-static.
There is no concept of static indexers, even though static properties are there.

a) Static Fields
-------------------
Static fields can be declared by using the keyword " static ".
When we declare a static field inside a class, it can be initialized with a value as shown in the following example.
All un-initialized static fields automatically get initialized to their default values(0) when the class is loaded first time.

Example :

using System;
class MyClass
{
public static int xx= 20;
public static int yy;
public static int zz = 40;

// values first come to constructor
public MyClass(int i)
{
xx = i; // assign xx = 50
}
}

class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.xx,MyClass.yy,MyClass.zz);
MyClass mc = new MyClass(50);
Console.WriteLine("{0},{1},{2}",MyClass.xx,MyClass.yy,MyClass.zz);
}
}

Output :
20,0,40
50,0,40

b) static constructor
--------------------------
The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first.

The name of a static constructor must be the name of the class and even they don't have any return type. The keyword "static" is used with the constructor.
The static constructor can't take any arguments. That means there is only one form of static constructor, without any arguments.
In other way it is not possible to overload a static constructor.

We can't use any access modifiers along with a static constructor.

Example :
// C# static constructor

using System;
class MyClass
{
public static int xx;
public static int yy = 500;

static MyClass ()
{
xx = 100;
yy = 200; // assign yy = 200 not 500
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1}",MyClass.xx,MyClass.yy);
}
}

Output:
100,200

Note that static constructor is called when the class is loaded at the first time. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called.

c) Static Member Functions
-----------------------------------
Inside a C# class, member functions can also be declared as static using "static" keyword.
But a static member function can access only other static members.
They can access non-static members only through an instance of the class.
We can invoke a static member only through the name of the class.
In C#, static members can't invoked through an object of the class as like in C++ or JAVA.

Example :
using System;
class MyClass
{
private static int x = 20;
private static int y = 40;
public static void Method()
{
Console.WriteLine("{0},{1}",x,y);
}
}
class MyClient
{
public static void Main()
{
MyClass.Method();
}
}

d) Static Properties
-------------------------
The properties can be declared as static in C#. The static properties are accessing using the class name.

Example :
using System;
class MyClass
{
public static int X
{
get
{
Console.Write("GET");
return 10;
}
set
{
Console.Write("SET");
}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 20; // calls setter displays SET
int val = MyClass.X;// calls getter displays GET
}
}

Output:
SET
GET

e) Static Members & Inheritance
------------------------------------------
A derived class can inherit a static member.

Example :
using System;
class MyBase
{
public static int x = 25;
public static void Method()
{
Console.WriteLine("My Base static method");
}
}
class MyClass : MyBase
{
}
class MyClient
{
public static void Main()
{
MyClass.Method();
Console.WriteLine(MyClass.x);
}
}

Output :
My Base static method
25

A static member in C# can't be marked as override, virtual or abstract.
It is possible to hide a base class static method in a derived class
by using the keyword "new".

Example :
using System;
class MyBase
{
public static int x = 25;
public static void Method()
{
Console.WriteLine("My Base static method");
}
}
class MyClass : MyBase
{
public new static int x = 50;
public new static void Method()
{
Console.WriteLine(" My Derived static method");
}
}
class MyClient
{
public static void Main()
{
MyClass.Method();
Console.WriteLine(MyClass.x);
}
}

Output :
My Derived static method
50


Wednesday, July 7, 2010

Basics of WCF

Overview of WCF

-> Windows Communication Foundation.
-> It combines functionalities of Asp.Net Web services, remoting, MSMQ and
Enterprise Services.

-> It’s more reliable and secured then Web services.
-> All the major changes can be done in the configuration file instead of code file.

********************************************************
Differences between WCF & Webservices

Hosting
---------
WCF can be hosted on IIS, WAS(Windows Activation Service), self-hosting.
WS can be hosted on IIS.

Attribute
----------
WCF has [ServiceContract] attribute attached with the class.
WS has [WebService] attribute attached with the class.
WCF has [OperationContract] attribute attached with methods.
WS has [WebMethod] attribute attached with methods.

WCF has [DataContract] attribute attached with the class.
WCF has [DataMember] attribute attached for a properties in the class,.

XML
-----
WCF uses System.Runtime.Serialization namespace for serialization.
WS uses System.Xml.Serialization namespace for serialization.


Transports
------------
WCF supports Http, Tcp, Msmq, P2P transport protocols.
Ex: The sample address for above transport schema may look like
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService

WS supports Http protocol.

Security
----------
WCF provides reliable security for messaging and transactions over net.
WS doesn’t provide method level security & message delivery isn’t assured & can be lost without acknowledgment.

There are three major Points in WCF

i)Address
WCF service location that client can use to expose its features

ii)Binding
Configuration for Transport protocol, security and encoding mechanism.

iii)Contract
It defines type of data and type of operations, a client application can use from WCF service.

***********************************************************
WCF configurations in config file :
-------------------------------------------
It declares information about endpoint name, address, binding and contract.

< system.serviceModel >
< client >
< endpoint name = "MyEndpoint"
address = "http://localhost:8000/MyService/"
binding = "wsHttpBinding"
contract = "IMyContract"
/>
</ client >
< / system.serviceModel >


Endpoint :
------------
In WCF the relationship between Address, Contract and Binding is called Endpoint.
The Endpoint is the fusion of Address, Contract and Binding.

Contracts :
-------------
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.
1) Service contracts
Describe which operations the client can perform on the service.
There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.

Ex:
[ServiceContract]
interface IMyContract
{
[OperationContract]
string MyMethod( );
}
class MyService : IMyContract
{
public string MyMethod( )
{
return "Hello World";
}
}

2) Data contracts
Define which data types are passed to and from the service.
WCF defines implicit contracts for built-in types such as int and string,
but we can easily define explicit opt-in data contracts for custom types.

There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties.

[DataContract]
class Contact
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
}
If DataMember attributes are not specified for a properties in the class, that
property can't be passed to-from web service.

3) Fault contracts
Define which errors are raised by the service, and how the service handles and
propagates errors to its clients.


4 )Message contracts
Allow the service to interact directly with messages.
Message contracts can be typed or untyped, and are useful in interoperability cases
and when there is an existing message format we have to comply with.







Saturday, June 26, 2010

Diff getElementById ().value & getElementById ().innerHTML

Example : Updating Text Based on User Input:

Note:
If we want to access the text within a non-input HTML element, then we are going to have to use the innerHTML property instead of value.

<script type="text/javascript">
function changeText()
{
// Get user I/p data
var userInput = document.getElementById (“userInput”).value;

// Get data from non-input element & replace old data
document.getElementById (“boldStuff2”).innerHTML = userInput;
}
</script>

Welcome to the site <b id=“boldStuff2”>dude</b> </p>

<input type=“text” id=“userInput” value=“Enter Text Here” />
<input type=“button” onclick=“changeText ()” value=“Change Text” />

Thursday, May 20, 2010

Design Patterns

What is a Design Pattern?

Design Pattern is a re-usable, high quality solution to a given requirement, task or recurring problem. Further, it does not comprise of a complete solution that may be instantly converted to a code component, rather it provides a framework for how to solve a problem.

Design patterns consist of proven

Reusable architectural concepts,

Reliable and speed up software development process.
Design Patterns are in a continuous phase of evolution, which means that they keep on getting better & better as they are tested against time, reliability and subjected to continuous improvements.

Further, design patterns have evolved towards targeting specific domains.

For example,

> Windows-based banking applications are usually based on singleton patterns,

> E-commerce web applications are based on the MVC (Model-View-Controller) pattern.

Design Patterns are categorized into 3 types:
*
Creational Patterns
* Structural Patterns
*
Behavioral Patterns

Creational Patterns:

What are Creational Design Patterns?

The Creational Design Patterns focus on how objects are created and utilized in an application. They tackle the aspects of when and how objects are created, keeping in mind what’s the best way these objects should be created.

Listed below are some of the commonly known Creational Design Patterns:
>> Singleton Pattern

>> Abstract Factory Pattern
>> Factory Pattern
>> Builder Pattern
>> Lazy Pattern
>> Prototype Pattern

What is the Singleton Design Pattern?

The Singleton design pattern is based on the concept of restricting the instantiation of a class to one object. Say one object needs to perform the role of a coordinator between various instances of the application that depend on a common object; we may design an application using a Singleton. Usage of Singleton patterns is common in Banking, Financial (such as Banking tools or Car Loan tools etc.) and Travel based applications where the singleton object consists of the network related information.

A singleton class may be used to instantiate an object of it, only if that object does not already exist. In case the object exists, a reference to the existing object is given. A singleton object has one global point of access to it.

An
asp.net Web Farm is also based on the Singleton pattern. In a Web Farm, the web application resides on several web servers. The session state is handled by a Singleton object in the form of the aspnet_state.exe, which interacts with the ASP.NET worker process running on each web server. Note that the worker process is the aspnet_wp.exe process. Imagine one of the web servers shutting down; the singleton object aspnet_state.exe still maintains the session state information across all web servers in the web farm.

In .NET, in order to create a singleton, a class is created with a private constructor, and a "static read-only" variable as the member that behaves as the instance.

What’s the difference between Abstract Factory Pattern and Factory Pattern?

In an abstract factory design, a framework is provided for creating sub-components that inherit from a common component. In .NET, this is achieved by creating classes that implement a common interface or a set of interfaces, where the interface comprises of the generic method declarations that are passed on to the sub-components. Note that not just interfaces, but even abstract classes can provide the platform of creating an application based on the abstract factory pattern.
Example, say a class called CentralGovernmentRules is the abstract factory class, comprised of methods like ShouldHavePolice () and ShouldHaveCourts (). There may be several sub-classes like State1Rules, State2Rules etc. created that inheriting the class CentralGovernmentRules, and thus deriving its methods as well.

Note that the term "Factory" refers to the location in the code where the code is created.

A Factory Pattern is again an Object creation pattern. Here objects are created without knowing the class of the object. Sounds strange? Well, actually this means that the object is created by a method of the class, and not by the class's constructor. So basically the Factory Pattern is used wherever sub classes are given the privileged of instantiating a method that can create an object.

Describe the Builder Design Pattern?

In a builder design pattern, an object creation process is separated from the object design construct. This is useful because the same method that deals with construction of the object can be used to construct different design constructs.

What is the Lazy Design Pattern?

The approach of the Lazy Design Pattern is not to create objects until a specific requirement matches, and when it matches, object creation is triggered. A simple example of this pattern is a Job Portal application. Say you register yourself in that site thus filling up the registration table, only when the registration table is filled, the other objects are created and invoked, that prompt you to fill in other details too, which will be saved in other tables.

What is the Prototype Design Pattern?

A prototype design pattern relies on creation of clones rather than objects. Here, we avoid using the keyword 'new' to prevent overheads.

Structural Design Patterns

What are Structural Design Patterns?

A structural design pattern establishes a relationship between entities. Thus making it easier for different components of an application to interact with each other. Following are some of the commonly known structural patterns:

>> Adapter Pattern - Interfaces of classes vary depending on the requirement.
>> Bridge Pattern - Class level abstraction is separated from its implementation.
>> Composite Pattern -
Individual objects & a group of objects are treated similarly in this approach.
>> Decorator Pattern - Functionality is assigned to an object.
>> Facade Pattern - A common interface is created for a group of interfaces sharing a similarity.
>> Flyweight Pattern - The concept of sharing a group of small sized objects.
>> Proxy Pattern - When an object is complex and needs to be shared, its copies are made.

These copies are called the proxy objects.

What are the different types of Proxy Patterns?

1 - Remote Proxy - A reference is given to a different object in a different memory location. This may be on a different or a same machine.
2 - Virtual Proxy - This kind of object is created only & only when really required because of its memory usage.
3 - Cache Proxy - An object that behaves as a temporary storage so that multiple applications may use it. For example, in ASP.NET when a page or a user control contains the OutputCache directive, that page/control is cached for some time on the ASP.NET web server.


Behavioral design pattern

What is a behavioral design pattern?

Behavioral design patterns focus on improving the communication between different objects. Following are different types of behavioral patterns:
>>> Chain Or Responsibilities Pattern - In this pattern, objects communicate with each other depending on logical decisions made by a class.
>>> Command Pattern - In this pattern, objects encapsulate methods and the parameters passed to them.
>>> Observer Pattern - Objects are created depending on an events results, for which there are event handlers created.

What is the MVC Pattern (Model View Controller Pattern)?

The MVC Pattern (Model View Controller Pattern) is based on the concept of designing an application by dividing its functionalities into 3 layers. Its like a triad of components. The Model component contains the business logic, or the other set of re-usable classes like classes pertaining to data access, custom control classes, application configuration classes etc. The Controller component interacts with the Model whenever required. The control contains events and methods inside it, which are raised from the UI which is the View component.

Consider an ASP.NET web application. Here, all aspx, ascx, master pages represent the View.
The code behind files (like aspx.cs, master.cs, ascx.cs) represents the Controller.
The classes contained in the App_Code folder, or rather any other class project being referenced from this application represent the Model component.

Advantages:

· Business logic can be easily modified, without affecting or any need to make changes in the UI.

· Any cosmetic change in the UI does not affect any other component.

When should design patterns be used?

While developing software applications, sound knowledge of industry proven design patterns make the development journey easy and successful. Whenever a requirement is recurring, a suitable design pattern should be identified. Usage of optimal design patterns enhances performance of the application. Though there are some caveats. Make sure that there are no overheads imposed on a simple requirement, which means that design patterns should not be unnecessarily be used.

How many design patterns can be created in .NET?

As many as one can think. Design patterns are not technology specific; rather their foundation relies on the concept of reusability, object creation and communication. Design patterns can be created in any language.

Describe the Ajax Design Pattern?

In an Ajax Design Pattern, partial postbacks are triggered asynchronously to a web server for getting live data. A web application would not flicker here, and the website user would not even come to know that a request is being sent to the web server for live data.

Such a design pattern is used in applications like Stock Market Websites to get live quotes, News Websites for live news, Sports websites for live scores etc.

Tuesday, May 18, 2010

Callback Function in C#

Definition:
-------------
       >> Functions that are triggered when an associated event happens.
 
Example :

------------
 
  > In C, function pointer is used as a callback functions.
 
  > In C++, virtual function is used as a callback function.
 
  > c#, delegate keyword is used to create a call back function.
 
Example in c#:
------------------

 
using System;
using System.Collections.Generic;
using System. Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        public delegate int execute(int a, int b); //declare a delegate method
 
        static void Main(string[] args)
        {
            Program p = new Program();     
                  
            execute ex = new execute(p.add);
            Console.WriteLine(ex(2,3));  //add method is executed
 
            ex = new execute(p.subtract);
            Console.WriteLine(ex(2, 3)); //subtract method is executed            
        }
 
        public int add(int a, int b)
        {
            return (a + b);
        }
 
        public int subtract(int a, int b)
        {
            return (a - b);
        }
    }
}

Monday, May 3, 2010

C# programming language

--- Arrays section (C#) ---
 
Create new array
 
Create new array to store values.
 
int[] cat = new int[5];
// cat = 0, 0, 0, 0, 0
 
string[] s = new string[10];
// s = null, null, ...
 
Initialize array
Create new int or string array with certain values.
 
int[] cat = {1, 4, 6};
string[] a = {"dog", "cat", "plant"};
 
Assign array
Set element in array to value.
 
cat[0] = 3;
cat[1] = 4;
cat[4] = 7;
 
Check array size
Use array's length property, then access elements.
 
if (cat.Length == 3)
{
    // 3 elements
}
 
Sort array
Sort an array alphabetically (A - Z).
 
string[] a = new string[]
{
    "z", "a", "b"
};
Array.Sort(a);
// "a", "b", "z"
 
Use 2D array
Use a two-dimensional array to store a grid of values.
 
int[,] i = new int[2, 2];
i[0, 0] = 0;
i[0, 1] = 1;
i[1, 0] = 2;
i[1, 1] = 3;
// 0, 1
// 2, 3
 
Convert List to array
Use instance method ToArray() to convert List to equivalent array.
 
List e = new List();
e.Add(1);
e.Add(2);
int[] a = e.ToArray();
// a = 1, 2
 
Loop through List
Iterate through each item in an array or list.
 
List e = new List();
e.Add(1);
e.Add(2);
foreach (int i in e)
{
    // 1, 2
}
 
Reverse array
Reorder elements in array backwards.
 
int[] a = {5, 6, 1};
Array.Reverse(a);
// 1, 6, 5
 
--- Methods section (C#) ---
 
Ref parameter
Allow another method to directly change value.
 
class C
{
    void Method()
    {
        int a = 4;
        Method2(ref a);
        // a = 5
    }
    void Method2(ref int p)
    {
        p = 5;
    }
}
 
Out parameter
Allow another method to directly change value.
With compile-time checking.
 
class C
{
    void Method()
    {
        int a;
        Method2(out a);
        // a = 5
    }
    void Method2(out int p)
    {
        p = 5;
    }
}
 
--- Strings section (C#) ---
 
Split string
Divide string into separate parts.
 
string c = "one,two";
string[] s = c.Split(',');
// s[0] = "one"
// s[1] = "two"
 
String new lines
Declare a string with newlines in it. Use "" for a quote.
 
string s = @"line 1
line 2
line 3";
 
Combine strings
Add strings together (also called concatenation).
Use overloaded + operator.
 
string s1 = "cat";
string s2 = "dog";
string c = s1 + " and " + s2;
// c = "cat and dog"
 
Compare strings
See if two strings have equal characters and lengths.
 
string s1 = "cat";
string s2 = "dog";
string s3 = "cat";
if (s1 == s2)
{
    // not true
}
if (s1 == s3)
{
    // success
}
 
Empty string check
See if string is empty or null (has no value).
 
string s1 = "";
string s2 = null;
string s3 = "cat";
if (string.IsNullOrEmpty(s1))
{
    // true
}
if (string.IsNullOrEmpty(s2))
{
    // true
}
if (string.IsNullOrEmpty(s3))
{
    // not true
}
 
Get string length
Find number of characters in string.
 
string c = "cat";
if (c.Length == 3)
{
    // true
}
 
Append strings quickly
Use StringBuilder and convert back to string.
 
StringBuilder b = new StringBuilder();
b.Append("Text");
b.Append(" more");
string r = b.ToString();
// r = "Text more"
 
Uppercase entire string
Uppercase each letter in string.
 
string s = "cat";
s = s.ToUpper();
// s = "CAT"
 
Uppercase first letter
Uppercase the first letter in string.
 
string s = "cat";
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
string u = new string(a);
// u = "Cat"
 
Convert string to int
Take string containing digits and convert it to int value.
 
 
string s = "105";
int i = int.Parse(s);
// i = 105
 
string s2 = "105.5";
double d = double.Parse(s2);
// d = 105.5
 
Substring of string
Get part of string based on indexes.
 
string s = "developer";
string b = s.Substring(0, 7);
// b = "develop"
 
Remove whitespace
Trim whitespace at beginning and ending of string.
 
string s = " cat  ";
string t = s.Trim();
// t = "cat"
 
Change string characters
Modify the letters in string in-place.
 
string s = "cat";
char[] a = s.ToCharArray();
    // a = 'c', 'a', 't'
a[0] = 'h';
    // a = 'h', 'a', 't'
string s2 = new string(a);
    // s2 = "hat"
 
 
--- Classes section (C#) ---
 
Declare constructor
Create new constructor for class.
 
class C
{
    public C(int a)
    {
        // initialize
    }
}
 
Cast safely
Use as operator or is operator.
Convert from one type to another.
 
void Method(object a)
{
    if (a is MyClass)
    {
        // correct type
    }
}
void Method2(object a)
{
    MyClass m = a as MyClass;
    if (m != null)
    {
        // correct type
    }
}
 
Null reference
Causes exception in programs. Null variable used.
 
 
string s = null;
if (s.Length == 0)
{
    // exception raised
}
 
New object
Create a new object of a kind.
 
class C
{
    // impl.
}
class Program
{
    void Main()
    {
        C name = new C();
    }
}
 
Singleton
Make a single object. One instance per AppDomain.
 
class S
{
    private static readonly _inst = new S();
    public static S Instance
    {
        get { return _inst; }
    }
    S()
    {
        // init
    }
}
 
Properties, Accessors, Getters, setters
Create properties to access fields of classes publicly.
 
class C
{
    public int P { get; set; }
}
void Method(C name)
{
    name.P = 4;
    int i = name.P;
    // i = 4
}
 
--- File/IO section (C#) ---
 
 
Read file lines
Read in each line of file into array.
 
string[] lines = File.ReadAllLines("file.txt");
// lines[0] = "..."
// lines[1] = "..."
 
 
Read text file
Read in entire file containing text.
 
string f = File.ReadAllText("file.txt");
// f = "..."
 
 
Read lines separately
Read file line-by-line with StreamReader.
Fastest and lowest memory.
 
using (StreamReader s = new StreamReader("file.txt"))
{
    string t;
    while ((t = s.ReadLine()) != null)
    {
        // t = "..."
    }
}
 
 
Append to file
Add text to end of file on disk.
 
File.AppendAllText("file.txt", "..." + Environment.NewLine);
 
Write file
Write text to file on disk, replacing any existing files.
 
File.WriteAllText("file.txt", "...");
 
Directory exists
See if folder exists on file system. Add using System.IO;
 
if (Directory.Exists("C:\\f"))
{
    // ...
}
 
File exists
See if file exists on disk at path.
 
if (File.Exists("file.txt"))
{
    // ...
}
 
--- Hashtables section (C#) ---
 
Use Dictionary
Use the generic Dictionary object with string keys.
 
 
Dictionary d = new Dictionary();
d.Add("cat", 2);
d.Add("dog", 4);
if (d.ContainsKey("cat"))
{
    // true
}
if (d.ContainsKey("hat"))
{
    // not true
}
 
Lookup Dictionary value
Get value from hashtable/Dictionary based on key.
 
 
Dictionary d = new Dictionary();
d.Add("cat", 2);
if (d.ContainsKey("cat"))
{
    int v = d["cat"];
    // v = 2
}
 
Scan Dictionary values
Use KeyValuePair on Dictionary to list each key/value combo.
Use this style to convert to string.
 
 
 
foreach (KeyValuePair p in d)
{
    // p.Key, p.Value
}
 
Use Hashtable
Implements older version of Dictionary, slower but required sometimes.
 
 
Hashtable h = new Hashtable();
h.Add(400, "Blazer");
 
string s = h[400] as string; // Cast
if (s != null) // True
{
    Console.WriteLine(s);
}
 
--- Language section (C#) ---
 
Namespaces
Put at top of file. 
 
using System;
using System.IO;
using System.Linq;
using System.Text;
 
Current time
Get current time using DateTime.
 
 
DateTime d = DateTime.Now;
string s = d.ToString();
// s = "8/20/2008 4:18:52 PM"
 
Debug message
Write diagnostics message to console.
 
 
using System.Diagnostics;
class C
{
    void Method()
    {
        Debug.WriteLine("...");
    }
}
 
Enums
Use enum type to assign names to numbers.
 
 
enum E
{
    None,
    Cat,
    Dog
};
void Method()
{
    E name = E.Cat;
    if (name == E.Dog)
    {
        // not true
    }
}
 
Loop through numbers
Use the for loop to loop through range of values.
 
 
 
for (int i = 0; i <>
{
    // 0, 1, 2, 3, ... 99
}
 
Catch exceptions
Detect errors and try to recover from them.
 
try
{
    int i = 1 / int.Parse("0");
}
catch (Exception)
{
    // log error
}
 
Switch statement
Compare value against constant values. Faster than if.
 
switch(v)
{
    case "cat":
    case "tiger":
        {
            // feline
            break;
        }
    case "dog":
    default:
        {
            // other
            break;
        }
}
 
 
 
 
 
--- Interfaces section (C#) ---
 
Interfaces, code contracts
Define required methods for classes so they can be swapped.
 
public interface IName
{
    void Method();
}
class C : IName
{
    public void Method()
    {
        // ...
    }
}
class D : IName
{
    public void Method()
    {
        // ...
    }
}
 
Use interfaces
Use classes by their common interfaces. Improves code reuse.
 
void Method()
{
    C name = new C();
    Method2((IName)name);
 
    D name2 = new D();
    Method2((IName)name2);
}
void Method2(IName i)
{
    // ...
}

Mobiles