February 24, 2011

Generics example in C#

Create 4 student objects with attributes Id,Name .
Add those in Generic List.


//Below is the code


using System;

using System.Collections.Generic;
class Student
{
   int s_Id;
   public int STUDENTID
   {
        get { return s_Id; }


        set { s_Id = value; }
   }


   string S_Name;
   public string STUDENTNAME 
   {
       get { return S_Name; }


       set { S_Name = value; }
   }
       
    public Student(int SID, string SNAME)
   {
     this.s_Id=SID;
     this.S_Name=SNAME ;


   }


}


// Main class as follows:

class Program
{
  static void Main(string[] args)
  {
    // add student objects in generic List
    List<Student > StudentList = new List<Student>();


    StudentList.Add(new Student (1,"test1"));
    StudentList.Add(new Student(2, "test2"));
    StudentList.Add(new Student(3, "test3"));
    StudentList.Add(new Student(4, "test4"));


    //traverse through the list
    foreach (Student s in StudentList)
    {
      Console.WriteLine("Studnet Id");
      Console.WriteLine(s.STUDENTID);


      Console.WriteLine("Studnet Name");
      Console.WriteLine(s.STUDENTNAME);
      Console.WriteLine("");
      Console.WriteLine("");
      Console.WriteLine("");
    }
    Console.ReadLine();
  }
}


Below is the o/p

Multicast Delegate Example in C#

//Below Example Defines MultiDelegateToMethod which holds reference to below three methods
void  Add(int num1, int num2)
void  Multiply(int num1, int num2)
void  Divide(int num1, int num2)




//Invoke MultiDelegateToMethod  to call all three methods one by one




using System;
namespace MultiCastDelegates
{
    public delegate void  MultiDelegateToMethod(int x, int y);
    public class Math
    {
        public static void  Add(int num1, int num2)
        {
            Console.WriteLine("Addition Is {0} ", num1 + num2);
           
        }
        public static void Multiply(int num1, int num2)
        {
            Console.WriteLine("Multiplication  Is {0} ", num1 * num2);
        }
        public static void Divide(int num1, int num2)
        {


            Console.WriteLine("Division Is {0} ", num1 / num2);
        }
    }
    public class DelegateApp
    {
        public static void Main()
        {
            MultiDelegateToMethod aDelegate = new MultiDelegateToMethod(Math.Add);
            aDelegate = aDelegate + new MultiDelegateToMethod(Math.Multiply);
            aDelegate = aDelegate + new MultiDelegateToMethod(Math.Divide);
          
            //Invoke Add,Multiply ,Divide by just invoking aDelegate 
            aDelegate(10, 5);
          
        }
    }
}


Below is the o/p


February 19, 2011

Inheritance Example C#

*Create a class called Circle that contains calculations for a circle based on its radius. It calculates the
*Diameter,
*Circumference,
*Area.
*
*Then Create a class called Sphere inherits from the Circle class and calculates below based on its radius.
*Area
*Volume
 
*Get Below calculations for both the Circle and sphere
*Diameter,
*Circumference,
*Area
*Get Below calculations for sphere
*Volume


Program.cs

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


namespace ConsoleApplication1
{
    class Circle
    {
        private double _radius;


        public double Radius
        {
            get {
                if (_radius < 0)
                {
                    return 0.0;
                }
                else
                {
                    return _radius;


                }
            
            
            }
            set 
            {
                _radius = value; 
            }
        }
        public double Diameter
        {
            get { return Radius * 2; }
        }
        public double Circumference
        {
            get { return Diameter * 3.14159; }
        }
        public double Area
        {
            get { return Radius * Radius * 3.14159; }
        }
    }




    class Sphere : Circle
    {
        new public double Area
        {
            get { return 4 * Radius * Radius * 3.14159; }
        }


        public double Volume
        {
            get { return 4 * 3.14159 * Radius * Radius * Radius / 3; }
        }
    }
    class Program
    {


        void ShowCircle(Circle cObj)
        {
            Console.WriteLine("Circle ");
            Console.WriteLine("Radius: " + cObj.Radius);
            Console.WriteLine("Diameter: " + cObj.Diameter);
            Console.WriteLine("Circumference:" + cObj.Circumference);
            Console.WriteLine("Area:     " + cObj.Area);
        }


        void ShowSphere(Sphere sobj)
        {
            Console.WriteLine("Sphere");
            Console.WriteLine("Radius:     " + sobj.Radius);
            Console.WriteLine("Diameter: " + sobj.Diameter);
            Console.WriteLine("Circumference: " + sobj.Circumference);
            Console.WriteLine("Area:     " + sobj.Area);
            Console.WriteLine("Volume: " + sobj.Volume);
        }
        static void Main(string[] args)
        {
            Circle c = new Circle();
            Sphere s = new Sphere();
            Program p = new Program();


            Console.WriteLine("Enter Circle Radius");
            double circleRadius =double.Parse (Console.ReadLine() );


            Console.WriteLine("Enter Sphere Radius");
            double sphereRadius = double.Parse(Console.ReadLine());


            c.Radius = circleRadius;
            p.ShowCircle(c);






            s.Radius = sphereRadius;
            p.ShowSphere(s);
                       
        }
    }
}


Below is the o/p

February 16, 2011

Pass command line arguments in C#

When running your console application if you  want to pass  certain command line arguments
From the Project menu choose Properties. Navigate to Debugging. Now you can see theCommand Line Arguments field in the right pane, as in the image below: enter something 




below is the code to fetch those arguments



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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(args[0]);
            Console.WriteLine(args[1]);
        }
    }
}


and then start the program using ctrl+F5
Below 'll be the o/p



February 10, 2011

Picasa Integration In ASP.NET Part1

Integrate the photo Album Uploaded in Picasa in ASP.NET Application.
1.) Download Client Libraries For .NET Provided by Google that use the Picasa Web Albums Data API.from the below Link
http://code.google.com/apis/picasaweb/code.html
It will install the sdk on below path
C:\Program Files\Google\Google Data API SDK




2.) Create ASP.NET application and From bin Add refrences of
Google.GData.Client.dll
Google.GData.Extensions.dll
Google.GData.Photos.dll


from the below path
C:\Program Files\Google\Google Data API SDK\Redist


3.) Write The code for Integrating Picasa Album Into ASP.NET Application


Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PicasaWebIntegration._Default"
    Theme="Main" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Picasa Web Integration</title>
    <link rel="stylesheet" href="css/vlightbox1.css" type="text/css" /> 
    <link rel="stylesheet" href="css/global.css" type="text/css" /> 
<link rel="stylesheet" href="css/visuallightbox.css" type="text/css" media="screen" /> 
    <script src="js/jquery.min.js" type="text/javascript"></script> 
    <script src="js/visuallightbox.js" type="text/javascript"></script> 
    <script src="js/vlbdata.js" type="text/javascript"></script> 
</head>
<body>
    <form id="form1" runat="server">
   
    </form>
</body>
</html>


Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace PicasaWebIntegration
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {


          
            if (Request.QueryString["reset"] == "y")
                PhotoManager.Reset();
        }


        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {


            string[] m_Photos;
            string[] m_Original_Photos;
            PhotoManager.GetAlbums();
            m_Photos = PhotoManager.GetPhotos();
            m_Original_Photos = PhotoManager.GetOriginalPhotos();
            for (int i = 0; i < m_Photos.Length; i++)
            {
                HyperLink hp = new HyperLink();
                
                Image img = new Image();
                img.ImageUrl = m_Photos[i];
                hp.Controls.Add(img);
                hp.NavigateUrl = m_Original_Photos[i];
                hp.CssClass = "vlightbox";
                form1.Controls.Add(hp);


                Literal lit = new Literal();
                lit.Text = "                 ";
                form1.Controls.Add(lit);
                
            }
           
        }


        protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }


       




    }
}

PhotoManager.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using Google.GData.Photos;


namespace PicasaWebIntegration
{
    public class PhotoManager
    {
        private static Albums m_albums;
        private static PicasaService m_picasaService;
        private static String[] myImages;
        private static String[] myThumnailsImages;


        public static PicasaService PicasaService
        {
            get
            {
                if (m_picasaService == null)
                    m_picasaService = new PicasaService("PhotoBrowser");
                return m_picasaService;
            }
        }


        public static bool TryGetAlbum(string id, out Album album)
        {
            if (m_albums == null)
                InitializeAlbums();
            return m_albums.TryGetItem(id, out album);
        }


        public static Albums GetAlbums()
        {
            if (m_albums == null)
                InitializeAlbums();
            return m_albums;
        }


        public static void Reset()
        {
            InitializeAlbums();
        }


        private static void InitializeAlbums()
        {
            m_albums = new Albums();


            AlbumQuery albumQuery = new AlbumQuery();
           albumQuery.Uri = new Uri(PicasaQuery.CreatePicasaUri(ConfigurationManager.AppSettings.Get("PicasaWebUserId")));
           // AlbumQuery query = new AlbumQuery(PicasaQuery.CreatePicasaUri("btilokani@gmail.com"));
            albumQuery.Access = PicasaQuery.AccessLevel.AccessPublic;


            //PicasaFeed feed = PicasaService.Query(albumQuery);


            /* if (feed != null && feed.Entries.Count > 0)
            {
                foreach (PicasaEntry entry in feed.Entries)
                {
                    Album album = new Album();
                    album.Title = entry.Title.Text;
                    album.Summary = entry.Summary.Text.Replace("\r\n", "<br/>");
                    album.FeedUri = entry.FeedUri;
                    album.ThumbnailUrl = entry.Media.Thumbnails[0].Attributes["url"].ToString();
                    album.NumberOfPhotos = ((GPhotoNumPhotos)entry.ExtensionElements[5]).IntegerValue;


                    m_albums.Add(album);
                }
            } */


            PhotoQuery query = new PhotoQuery(PicasaQuery.CreatePicasaUri("PICASA USER ID", "ALBUM NAME"));
            query.Access = PicasaQuery.AccessLevel.AccessPublic;


            PicasaFeed feed = PicasaService.Query(query);


            myImages = new String[feed.Entries.Count];
            myThumnailsImages = new String[feed.Entries.Count];
            int i = 0;


            foreach (PicasaEntry entry in feed.Entries)
            {
                //Console.WriteLine(entry.Title.Text);
                //PhotoAccessor ac = new PhotoAccessor(entry);
                String url = entry.Content.AbsoluteUri;
                myImages[i] = url;
               
                
                String thumbUrl=entry.Media.Thumbnails[0].Attributes["url"].ToString(); 
                myThumnailsImages[i]=thumbUrl;
                 i++;
            }


        }
        //Return Thumbnail Images
        public static String[] GetPhotos()
        {
            return myThumnailsImages;
        }


        //Return Original Images
        public static String[] GetOriginalPhotos()
        {
            return myImages;
        }
    }
}

Albums.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Google.GData.Photos;
using System.Collections.ObjectModel;


namespace PicasaWebIntegration
{
    public class Albums: KeyedCollection<string, Album>
    {
        protected override string GetKeyForItem(Album item)
        {
            return item.FeedUri;
        }


        public bool TryGetItem(string feedUri, out Album matchingAlbum)
        {
            matchingAlbum = null;
            if (Dictionary != null && Dictionary.TryGetValue(feedUri, out matchingAlbum))
                return true;
            else
                return false;
        }
    }
}


Album.CS
using System.Collections.Generic;

using System;


namespace PicasaWebIntegration
{
    public class Album
    {
        private string m_feedUri;
        private string m_title;
        private string m_summary;
        private string m_thumbnailUrl;
        private int m_count;


        public string Title
        {
            get { return m_title; }
            set { m_title = value; }
        }


        public string FeedUri
        {
            get { return m_feedUri; }
            set { m_feedUri = value; }
        }


        public string ThumbnailUrl
        {
            get { return m_thumbnailUrl; }
            set { m_thumbnailUrl = value; }
        }


        public string Summary
        {
            get
            {
                return m_summary;
            }
            set
            {
                m_summary = value;
            }
        }


        public int NumberOfPhotos
        {
            get
            {
                return m_count;
            }
            set
            {
                m_count = value;
            }
        }
    }
}


add below in web.config file

web.config
<appSettings>
<add key="PicasaWebUserId" value="PICASAUSERID"/>
</appSettings>


I give credit for this Post to Alano's Blog(http://aocampo.com/blog/index.php) AS I have taken help from that blog 
and modified it according to my need

Below is The 0/p


Next Part Is Instead of getting one album , Fetch all the albums form Picasa Gallery
 Picasa Integration In ASP.NET Part2
on the below link
http://www.dotnetissues.com/2011/06/picasa-integration-in-aspnet-part2.html

February 5, 2011

Code Sample to write and consume WCF Service

Below are 3 major steps in WCF
  1. Create the Service.(Creating) 
  2. Binding an address to the service and host the Service. (Hosting) 
  3. Consuming the Service.(Consuming) 
Creating the Service
define below 3 contracts(describes all the available operations that a client can perform on the service.)
ServiceContract:
define the service contract. We can apply this attribute on class or interface

OperationContract:
indicate explicitly which method is used to expose as part of WCF contract. We can apply OperationContract attribute only on methods

Data Contract



defines the custom data types that are passed into and out of the service.


Steps To Create WCF Service
1.) Select WCF service Application Template Project
2.)In the solution explorer, under the App_code folder you can find the two files: "IService.cs" and "Service.cs". 

"IService.cs" class file defines the contracts.
 "Service.cs" implements the contracts defined in the "IService.cs". 
  Contracts defined in the "IService.cs" are exposed in the service.  



App_Code/Iservice.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;


// NOTE: If you change the interface name "IService" here, you must also update the reference to "IService" in Web.config.
[ServiceContract]
public interface IService
{


[OperationContract]
string GetData(int value);


    //written by Tanvi
    [OperationContract]
    string GetString(String theString);


[OperationContract]
Student GetStudentUsingDataContract(Student obj);



}


// To add composite types to service operations.
[DataContract]
public class Student
{
string   name ;
int  age ;


[DataMember]
    public int Age
{
        get { return age; }
        set { age = value; }
}


[DataMember]
public string Name
{
        get { return name; }
        set { name = value; }
}
}

App_Code/service.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;


// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class Service : IService
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}


    public Student GetStudentUsingDataContract(Student obj)
{


        return obj;
}




    public string GetString(String theString)
    {
        return "Hello First WCF Service" + theString;
    }
}


service.svc
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>






3.) Build The soultion




Hosting the Service

Host this serivce by creating the virtual directory in IIS and browse the *.SVC file
Now the http://tanvi/TestWCFService/Service.svc is the address of the created web service

Consuming the Service
1.) Create New ASP.NET web application
2.)In the solution explorer click on "Add service Reference" and add the service created in the STEP1.  
3.) Once The Reference is added we can use it as we use WebService.
     By Using the namespace and Creating the object of the class

     Below is the code in ASP.NET application to consume the above created service

Default2 .aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     Service Call from Code-Behind:<br />
            <asp:TextBox ID="fld_String" runat="server" />
<asp:RegularExpressionValidator ID="rv" ErrorMessage="Enter Number" runat="server" ControlToValidate ="fld_String" SetFocusOnError ="true" ForeColor="Red"  ValidationExpression="^\d*$"></asp:RegularExpressionValidator><br />
            <asp:Button ID="btn_Submit" runat="server" Text="Submit" 
                    onclick="btn_Submit_Click" /><br />
            <asp:Literal ID="lit_Display" runat="server" /><br />
             <asp:Literal ID="lt_studnet" runat="server" />
    </div>
    </form>
</body>
</html>

Default2 .aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }
    protected void btn_Submit_Click(object sender, EventArgs e)
    {
        ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
        lit_Display.Text = obj.GetData(int.Parse (fld_String.Text));
        Response.Write ("<br/>");
        //
        ServiceReference1.Student obj1 = new ServiceReference1.Student();
        obj1.Name = "Test";
        obj1.Age = 32;
        ServiceReference1.Student obj2 = obj.GetStudentUsingDataContract(obj1);
       // Response.Write(obj2.Name);
       // Response.Write("<br/>");
        //Response.Write(obj2.Age.ToString ());
        lt_studnet.Text = obj2.Name + " is" + obj2.Age.ToString() + " years old";
    }
}


Below is the o/p