Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, June 26, 2011

Namespace in C# and its Advantages

Namespaces are a way of grouping type names and reducing the chance of name collisions. A namespace can contain both other namespaces and types. The namespace keyword is used to declare a scope.

We can organize our types based on their bahaviour and functionalities. For example consider the following example. Suppose you have a collection of songs, how will you store it in your computer? normally one do this by creating root folder named "Songs" then create sub folders based on song types, then create subfolders for albums etc....

Have a look on the following C# example to understand the advantages of the namespace.

namespace Songs
{
public class Songs
{
public void PlayAll()
{
Console.WriteLine("Playing all songs..");
}
}
namespace English
{
public class Titanic
{
public void Play()
{
Console.WriteLine("Playing titanic..");
}
}
}
namespace Malayalam
{
public class Urumi
{
public void Play()
{
Console.WriteLine("Playing urumi.....");
}
}
}
}

Saturday, April 30, 2011

Live Stock Market Quotes (NSE) in .NET(C#)

This program extracts live stock price information from yahoo website. It can be included in our application to get usage of NSE stock quotes.

I have tried a lot to find a webservice which give NSE stock quotes, unfortunately I didn't find any. So I came into this decision to make a program which uses other websites like yahoo, rediff and msn. Finally I got a solution by writing the following application.

This program will give you live NSE stock quotes.

  [DataContract]
    public class StockQuote
    {
        [DataMember]
        public decimal LastPrice { set; get; }

        [DataMember]
        public decimal PreviousClose { set; get; }

        [DataMember]
        public decimal Open { set; get; }

        [DataMember]
        public DateTime LastTraded { set; get; }

        [DataMember]
        public string LastTradedString { set; get; }

        [DataMember]
        public decimal DayLow { set; get; }

        [DataMember]
        public decimal DayHigh { set; get; }

        [DataMember]
        public decimal FiftyTwoWeekLow { set; get; }

        [DataMember]
        public decimal FiftyTwoWeekHigh { set; get; }


    }

    [DataContract]
    public enum Exchange
    {
        NSE, BSE
    }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;

namespace StocksToBuy
{
    public class YahooStockQuote
    {
       

        public StockQuote GetQuote(string symbol, Exchange exchange)
        {
            try
            {
                string url = "http://in.finance.yahoo.com/q?s=";
                if (exchange == Exchange.NSE)
                    url += symbol.ToUpper() +
                    ".NS";
                else
                    url += symbol.ToUpper() +
                    ".BO";
                string webPage = null;
                HttpWebRequest webRequest;
                HttpWebResponse webResponse;
                webRequest = (HttpWebRequest)WebRequest.Create(url);
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                Stream pageStream = webResponse.GetResponseStream();
                StreamReader sr = new StreamReader(pageStream);
                webPage = sr.ReadToEnd();
                pageStream.Close();
                sr.Close();
                webResponse.Close();
                int startIndex;
                int endIndex;
                int tempStartIndex;
                int tempEndIndex;
                string temp;
                // Last Traded Value 
                startIndex = webPage.IndexOf("Last Trade:</th><td class=\"yfnc_tabledata1\"><big><b>") + 52;
                endIndex = webPage.IndexOf("</b>", startIndex);
                temp = webPage.Substring(startIndex, endIndex - startIndex);
                tempStartIndex = temp.IndexOf('>') + 1;
                tempEndIndex = temp.IndexOf('<', tempStartIndex);
                string lastPrice = temp.Substring(tempStartIndex, tempEndIndex - tempStartIndex);

                // Last Trade Time 
                startIndex = webPage.IndexOf("Trade Time:</th><td class=\"yfnc_tabledata1\">", endIndex) + 44;
                endIndex = webPage.IndexOf("</td>", startIndex);
                temp = webPage.Substring(startIndex, endIndex - startIndex);
                tempStartIndex = temp.IndexOf('>') + 1;
                tempEndIndex = temp.IndexOf('<', tempStartIndex);
                string lastTradeTime = temp.Substring(tempStartIndex, tempEndIndex - tempStartIndex);

                // Previous close 
                startIndex = webPage.IndexOf("Prev Close:</th><td class=\"yfnc_tabledata1\">", endIndex) + 44;
                endIndex = webPage.IndexOf('<', startIndex);
                string previousClose = webPage.Substring(startIndex, endIndex - startIndex);

                //Open price 
                startIndex = webPage.IndexOf("Open:</th><td class=\"yfnc_tabledata1\">", endIndex) + 38;
                endIndex = webPage.IndexOf('<', startIndex);
                string open = webPage.Substring(startIndex, endIndex - startIndex);

                //Day Low and Day High 
                startIndex = webPage.IndexOf("Day's Range:</th><td class=\"yfnc_tabledata1\">", endIndex) + 45;
                endIndex = webPage.IndexOf("</td>", startIndex);
                temp = webPage.Substring(startIndex, endIndex - startIndex);
                tempStartIndex = temp.IndexOf("\">") + 2;
                tempEndIndex = temp.IndexOf('<', tempStartIndex);
                string dayLow = temp.Substring(tempStartIndex, tempEndIndex - tempStartIndex);
                tempStartIndex = temp.IndexOf("\">", tempEndIndex) + 2;
                tempEndIndex = temp.IndexOf('<', tempStartIndex);
                string dayHigh = temp.Substring(tempStartIndex, tempEndIndex - tempStartIndex);

                //52 Week Low and 52 Week High 
                startIndex = webPage.IndexOf("Range:</th><td class=\"yfnc_tabledata1\"><", endIndex) + 39;
                endIndex = webPage.IndexOf("</td>", startIndex);
                temp = webPage.Substring(startIndex, endIndex - startIndex);
                tempStartIndex = temp.IndexOf('>') + 1;
                tempEndIndex = temp.IndexOf('<', tempStartIndex);
                string Fifty2WeekLow = temp.Substring(tempStartIndex, tempEndIndex - tempStartIndex);
                tempStartIndex = temp.IndexOf('>', temp.IndexOf('-')) + 1;
                tempEndIndex = temp.IndexOf('<', tempStartIndex);
                string Fifty2WeekHigh = temp.Substring(tempStartIndex, tempEndIndex - tempStartIndex);




                return new StockQuote
                {
                    LastPrice = Convert.ToDecimal(lastPrice),
                    DayHigh = Convert.ToDecimal(dayHigh),
                    DayLow = Convert.ToDecimal(dayLow),
                    FiftyTwoWeekHigh = Convert.ToDecimal(Fifty2WeekHigh),
                    FiftyTwoWeekLow = Convert.ToDecimal(Fifty2WeekLow),
                    LastTraded = Convert.ToDateTime(lastTradeTime),
                    LastTradedString=lastTradeTime,
                    Open = Convert.ToDecimal(open),
                    PreviousClose = Convert.ToDecimal(previousClose)
                };
            }
            catch
            {
                return new StockQuote();
            }
        }
    }
}

Friday, August 20, 2010

Enums in C#

Enums in C#


Enums are basically a set of named constants. i.e. these are basically a group of named constants defined under a common name.
Enums are value types and are created on the stack and not on the heap.

Eg:

using System;
public enum Colors
{
red,
green,
blue,
}


public class Mainclass
{
public static void Main()
{
string color = Colors.red.ToString();
Console.WriteLine("Color is:" + color);
int id = (int)Colors.blue;
Console.WriteLine("Color value:" + id);
}
}


Each enum type has a corresponding value type called underlying type of the enum type.

Unsafe Code ( Using Pointer) in C#

Unsafe Code ( Using Pointer in C#)

C#.NET hides most of memory management, but in some cases we need direct access to the memory, then unsafe code is used.


Eg:
using System;
class Mainclass
{
public static void Main()
{
int a = 5;

unsafe
{
int* ptr;
ptr = &a;
*ptr = 20;
}
Console.WriteLine("a = " + a);
}
}



Eg:

using System;
unsafe class Mainclass
{
public static void Main()
{
int a = 5;
int* ptr;
ptr = &a;
*ptr = 20;


Console.WriteLine("a = " + a);
}
}

Thursday, August 19, 2010

Parameter Arrays in C#

Parameter array.


Parameter arrays allows us to pass a variant  number of arguments into a method. All incoming arguments will consider as a single dimensional array. Have a look on the following example.
using System;


class Mainclass
{
public static void Main()
{
Test obj = new Test();
obj.Add(10, 20);
obj.Add(10, 20, 30);
obj.Add(1, 2, 3, 4, 5, 6);
}
}


class Test
{
public void Add(params int[] ar)
{
int sum = 0;
foreach (int i in ar)
{
sum = sum + i;
}
Console.WriteLine("Sum : " + sum);
}
}

Reference Parameters in C#

Reference Parameter


These are input/output parameters; they can be used for passing value into a function as well as to get back value from a function.

using System;
class Test
{


public void Inc(ref int a) // here a is a reference parameter. It refer the same memory address of passing arguement.
{
a = a + 10;
Console.WriteLine(a);
}
}



class Mainclass
{
public static void Main()
{
int x = 10;
Test obj = new Test();
obj.Inc(ref x); // arguement x and parameter a will be using the same memory reference.
Console.WriteLine("From Main " + x);
}
}

Output Parameters in C#

Output Parameter


A function can return only a single value. But when we using output parameters it is possible to return multiple values.
Note: output parameters must be assigned with value before leaving method, otherwise it will results in a compilation error.
Eg

using System;
class Test
{


public void Cal(int a, int b, out int c, out int d) // a and b are input parameters. c and d are output parameters.
{
c = a + b;   // set value for output parameter c.
d = a - b;   // set value for output parameter d.}


}

class Mainclass
{
public static void Main()
{
int n1 = 10, n2 = 30, sum, dif;
Test obj = new Test();
obj.Cal(n1, n2, out sum, out dif);
Console.WriteLine("Sum is {0} and Difference is {1} ", sum, dif);
}
}

Input Parameters in C#

Input Parameter


It is used to receive values, means it just pass values.

e.g

using System;
class Test
{
public void Increment(int a) // here a is an input parameter it just takes value from the Main method.
{
a = a + 10;
Console.WriteLine("a=" + a);
}
}


class MainClass
{
public static vod Main()
{
int x = 10;
Test obj = new Test();
obj.Increment(x); // passing value into the method.
Console.WriteLine("x=" + x);
}
}

Partial Class in C#

Partial class:


It is possible to split the definition of a class over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.

Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace. All the parts must use the partial keyword. All of the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public, private, and so on.

Eg;

using System;
partial class Test
{
private int x;
}


partial class Test
{
public Test()
{
x = 10;
}
}


partial class Test
{
public void Print()
{
Console.WriteLine("X is : {0}", x);
}
}

class Mainclass
{
public static void Main()
{
Test obj = new Test();
obj.Print();
}
}

Tuesday, August 17, 2010

Working with Configuration Files in C#

Configuration


A common issue when developing applications is how to retrieve configuration information, such as database connection strings, event log names, or other parameters.

The System.Configuration namespace provides the functionality for reading configuration files.

The location for application settings depends on the type of application you are creating. For web applications, settings are stored in the web.config, in console or WinForms gui applications, settings are stored in app.config file.

appSettings Section

An application configuration file follows a specific XML schema. The appSettings section is a predefined section of the configuration file designed to make it very easy to retrieve a value based on a given name. This is the easiest way to add application-specific settings into an application configuration file. The appSettings section of the configuration file consists of a series of "add" elements with "key" and "value" attributes.

Eg: Create a console application and add app.config file.

< configuration >< appSetting s>
< add key="SourceFile" value="d:\test\source.txt" / >
< add key="DestinationFile" value="d:\test\destination.txt" />
< /appSettings>
< / configuration >

--------

string source = ConfigurationSettings.AppSettings["SourceFile"];
string dest = ConfigurationSettings.AppSettings["DestinationFile"];
Console.WriteLine(source);
Console.WriteLine(dest);

Or

NameValueCollection nvc = ConfigurationManager.AppSettings;
Console.WriteLine(nvc["SourceFile"]);
Console.WriteLine(nvc["DestinationFile"]);

Eg:

< connectionStrings >
< add name="MyConnetion" providerName="System.Data.SqlClient" connectionString="data source=.\sqlexpress;initial catalog=MYDB;integrated security=true" / >
< / connectionStrings >

string constr = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
Console.WriteLine(constr);

Or

ConnectionStringSettingsCollection coll = ConfigurationManager.ConnectionStrings;
foreach (ConnectionStringSettings cs in coll)
{
if (cs.ProviderName == "System.Data.SqlClient")
{
Console.WriteLine(cs.ConnectionString);
}
}

Monday, August 16, 2010

Jagged array in C#

Jagged array:


A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays".

Declaration:       int[][] array;


Initialization:      array=new int[3][];
                        array[0]=new int[2];
                        array[1]=new int[5];
                        array[2]=new int[3];

 
Eg:
 
using System;

class jaggedarray
{
int[][] ja;


public void Accept()
{
Console.WriteLine("Enter the size of jagged array :");
int jsize = Convert.ToInt32(Console.ReadLine());
ja = new int[jsize][];
for (int i = 0; i < jsize; i++)
{
Console.WriteLine("Enter size of Single dimension array ");
int ssize = Convert.ToInt32(Console.ReadLine());
ja[i] = new int[ssize];
Console.WriteLine("Enter {0} elements ", ssize);
for (int j = 0; j < ssize; j++)
{
ja[i][j] = Convert.ToInt32(Console.ReadLine());
}
}
}


public void Display()
{
Console.WriteLine("Jagged Array Is :");
foreach (int[] a in ja)
{
foreach (int n in a)
{
Console.Write(n + "\t");
}
Console.WriteLine();
}
}
}


class Mainclass
{
public static void Main()
{
jaggedarray obj = new jaggedarray();
obj.Accept();
obj.Display();
}
}

Friday, August 13, 2010

Read & Write operations using Console class

Console Class:


In this class we use two important methods named WriteLine() and ReadLine(). This class contained in the System namespace.

Eg: Print a message

class WriteString
{
public static void Main()
{
   System.Console.WriteLine("Welcome to C#.")
}
}

Eg: read a string

using System;
class WriteString
{
public static void Main()
{
   Console.WriteLine("Enter a string ");
   string str = Console.ReadLine();
   Console.WriteLine("You entered = " + str);
}
}

WriteLine() pumps a text string to the output stream. ReadLine() allows you to receive information from the input stream. The ReadLine(0 method returns a string value.