June 25, 2011

Code to Populate Selected Row in Details View From ASP.NET Grid View


Example11 .aspx
<%@ Page Language="C#" ErrorPage ="~/Error.aspx" AutoEventWireup="true" CodeFile="Example11.aspx.cs" Inherits="Example11" %>


<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" 
              OnSelectedIndexChanging="GridView1_SelectedIndexChanging" 
            AutoGenerateSelectButton="true" 
            onselectedindexchanged="GridView1_SelectedIndexChanged">
        </asp:GridView>
        <asp:DetailsView ID="DetailsView1"  runat="server" Height="50px" Width="125px">
        </asp:DetailsView>
    </div>   
    </form>
</body>
</html>



Example11 .aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using NLog;


public partial class Example11 : System.Web.UI.Page
{
    SqlConnection connObj = new SqlConnection();
    DataSet ds;
    SqlCommand objCommand;
    SqlDataAdapter objAdapter;


    protected void Page_Load(object sender, EventArgs e)     
    {
        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();

//Bind Data To grid View
            connObj.Open();
            ds = new DataSet();
            objCommand = new SqlCommand("Select * from student", connObj);
            objAdapter = new SqlDataAdapter(objCommand);
            objAdapter.Fill(ds);
            connObj.Close();


            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
    }

    protected void GridView1_SelectedIndexChanging(object sender, EventArgs e)
    {
     
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = GridView1.SelectedRow;
        int id =int.Parse ( row.Cells[1].Text );

//Bind selected row from  grid View to Details View                connObj.Open();
        ds = new DataSet();
        objCommand = new SqlCommand("Select * from student where Student_ID= " + id, connObj);
        objAdapter = new SqlDataAdapter(objCommand);
        objAdapter.Fill(ds);
        connObj.Close();


        DetailsView1 .DataSource = ds.Tables[0];
        DetailsView1.DataBind();


    }
}



Below is the Connection String in web.config file.


<add name="DotNetTrainingConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=DotNetTraining;Integrated Security=True" providerName="System.Data.SqlClient"/>

See the below o/p on 10 as selected row from the Grid









June 23, 2011

Code Example for Anonymous type and Type Inference in C#


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


namespace ConsoleApplication7
{
   class Program
    {
        static void Main(string[] args)
        {
            var P = new { firstname = "ABC" };//P object of anonymost class 
            Console.WriteLine(P.firstname);
        }
    }
}

Code example for Collection Initializers – C# 3.0

Quick way to add items in collection
below is the example


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


namespace ConsoleApplication7
{
  public   class Person
    {
        private string _firstName;
        public string firstName{get { return _firstName; }set { _firstName = value;} }
            
        
    }




    class Program
    {
        static void Main(string[] args)
        {
            List<Person> obj=new List<Person> 
            {
                new Person {firstName ="ABC"},
                new Person {firstName ="Test"}


            };


            foreach (Person p in obj)
            {
                Console.WriteLine(p.firstName);




            }
        }
    }
}

Object Initializers – C# 3.0

lQuick way to create an instance and set a bunch of properties

See the below example


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


namespace ConsoleApplication7
{
    class Person
    {
        private string _firstName;
        public string firstName{get { return _firstName; }set { _firstName = value;} }
            
        
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person obj = new Person { firstName = "ABC" };
            Console.WriteLine(obj.firstName);
        }
    }
}

June 20, 2011

Code Example for Interface and Abstract Class in C#


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


namespace ConsoleApplication2
{




    interface EMPLOYEE
    {
         int GetID
        {
            get;


            set;
        }


         string GetName
         {
             get;


             set;
         }




         string  GetDepName
         {
             get;
         }


         int GetDepID
         {
             get;
         }
    }




    public  abstract class EMP:EMPLOYEE 
    {
        int ID;
        String  NAME;


        public EMP()
        {


        }
       public EMP(int id,String name)
        {
            this.ID =id;
            this.NAME = name;


        }
        public  int GetID
        {
            get{


                return this.ID;
            }


            set{


                this.ID=value ;
            }
        }


        public string  GetName
        {
            get
            {


                return this.NAME ;
            }
            set
            {


                this.NAME = value;
            }
        }




           public abstract string  GetDepName
           {
            get;
           }


         public  abstract  int GetDepID
        {
            get;
        }
       
    }


    public class SalesEmp : EMP
    {
        int DepartmentID;
        String DepartmentName;


        public SalesEmp()
        {


        }
        public SalesEmp(int DepId,String DepName)
        {
            this.DepartmentID = DepId;
            this.DepartmentName = DepName;


        }
      
        public override  int GetDepID
        {
            get
            {


                return this.DepartmentID;
            }
        }


        public override  string GetDepName
        {
            get
            {


                return this.DepartmentName;
            }
        }


    }




    public class TechEmp : EMP
    {
        int DepartmentID;
        String DepartmentName;


        public TechEmp()
        {


        }
        public TechEmp(int DepId, String DepName)
        {
            this.DepartmentID = DepId;
            this.DepartmentName = DepName;


        }


        public override int GetDepID
        {
            get
            {


                return this.DepartmentID;
            }
        }


        public override string GetDepName
        {
            get
            {


                return this.DepartmentName;
            }
        }


    }


    
    class Program
    {
        static void Main(string[] args)
        {
            EMPLOYEE se = new SalesEmp(1, "SALE");
            EMPLOYEE te = new TechEmp (2,"TECHNICAL");


            se.GetName = "EMP1";
            se.GetID = 1;


            te.GetName = "EMP2";
            te.GetID = 2;


            Program obj = new Program();
            obj.EmployeeBelongTo(se);
            obj.EmployeeBelongTo(te);
        }


        public void EmployeeBelongTo(EMPLOYEE E)
        {


            Console .WriteLine ("{0} belongs to {1} department",E.GetName,E.GetDepName);
        }
    }






}

code example for Upcasting/Downcasting in C#


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


namespace ConsoleApplication2
{


    public  class EMP
    {
        int ID;
        String  NAME;


        public EMP()
        {


        }
       public EMP(int id,String name)
        {
            this.ID =id;
            this.NAME = name;


        }
        public  int GetID
        {
            get{


                return this.ID;
            }


            set{


                this.ID=value ;
            }
        }


        public string  GetName
        {
            get
            {


                return this.NAME ;
            }
            set
            {


                this.NAME = value;
            }
        }


       
    }


    public class SalesEmp : EMP
    {
        int DepartmentID;
        String DepartmentName;


        public SalesEmp()
        {


        }
        public SalesEmp(int DepId,String DepName)
        {
            this.DepartmentID = DepId;
            this.DepartmentName = DepName;


        }
      
        public int GetDepID
        {
            get
            {


                return this.DepartmentID;
            }
        }


        public string GetDepName
        {
            get
            {


                return this.DepartmentName;
            }
        }


    }








    class Program
    {
        static void Main(string[] args)
        {
            EMP e = new EMP();
            SalesEmp se = new SalesEmp(1, "SALE");


            e = se;//upcasting




            if (se is EMP)
            {
                se.GetName = "ABC";
                se.GetID = 123;


            }


            SalesEmp s1 = (SalesEmp)e;//downcasting
           
            Console.WriteLine(s1.GetID);
            Console.WriteLine(s1.GetName);
            Console.WriteLine(s1.GetDepID);
            Console.WriteLine(s1.GetDepName);
        }
    }
}


below is the o/p


Code Example for Abstract Class in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
    public abstract class EMP
    {
        public abstract int SALARY
        {
            get;
        }
        public string Company
        {
            get
            {
                return "ICON Training";
            }
        }
      
    }
    public class SalesEmp : EMP
    {
        public override int SALARY
        {
            get
            {
                return 2000;
            }
        }
    }
    public class TechEmp : EMP 
    {
        public override int SALARY
        {
            get
            {
                return 5000;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            SalesEmp se = new SalesEmp();
            Console.WriteLine(se.SALARY);
            TechEmp te = new TechEmp();
            Console.WriteLine(te.SALARY);
        }
    }
}

Code Example for Method Overriding /Hiding

//Method Overriding


using System;

public class Rect
{
    public virtual void getArea()
    {
        Console.WriteLine(" Rect");
    }
}

public class Square : Rect
{
    public override  void getArea()
    {
        Console.WriteLine("Square ");

    }
}
class TestClass
{
    public static void Main()
    {
        Square sq = new Square();
        Rect r = sq;
        r.getArea();
        sq.getArea();


    }
}
below 'll be the 0/p
Square
Square

//Method Hiding 
using System;
public class Rect
{
public virtual void getArea()
{
    Console.WriteLine(" Rect");
}}
public class Square:Rect
{
    public new  void getArea()
    {
        Console.WriteLine("Square ");
    
}
class TestClass
{
    public static void Main()
    {
        Square sq = new Square();
        Rect r = sq;
         r.getArea();
         sq.getArea();
      
}

below 'll be the 0/p
Rect
Square

June 12, 2011

Picasa Integration In ASP.NET Part2

Read Below post first where I am integrating an album from a picasa gallery
http://www.dotnetissues.com/2011/02/picasa-integration-in-aspnet-part1.html

Now Below are the changes I made to read all the albums from the gallery instead of just one.



gallery.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="gallery.aspx.cs" Inherits="gallery"
    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">
    <div class="maincontent" runat ="server" id="MainDIV"> 
    </form>
</body>
</html>


gallery.aspx.cs


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class gallery : 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)
       {
 ////Code For Multiple Albums USe NewPhotoManager
    
        string[] m_Photos;
        string[] m_Original_Photos;

        Albums m_Albums = NewPhotoManager.GetAlbums();

        int albumCount = 0;

        foreach (Album alb  in m_Albums)
        {
            albumCount++;

            Label lbl = new Label();
            lbl.Text = alb.Summary;

            //MainDIV.Controls.Add(lbl);

            System.Web.UI.HtmlControls.HtmlGenericControl h4Tag =
               new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
            //h4Tag.Attributes.Add("style", "float:left;");
            h4Tag.InnerText = lbl.Text;
            MainDIV.Controls.Add(h4Tag);

            System.Web.UI.HtmlControls.HtmlGenericControl ulTag =
               new System.Web.UI.HtmlControls.HtmlGenericControl("ul");
            ulTag.Attributes.Add("class", "portfolio-4col");
            ulTag.Attributes.Add("id", "UnOList"+albumCount);
            //ulTag.Attributes.Add("style", "float:left;");

            m_Photos = NewPhotoManager.GetPhotos(alb.Title);
            m_Original_Photos = NewPhotoManager.GetOriginalPhotos();
            
            for (int i = 0; i < m_Photos.Length; i++)
            {


                System.Web.UI.HtmlControls.HtmlGenericControl liList =
               new System.Web.UI.HtmlControls.HtmlGenericControl("li");


                /////////////////////
                System.Web.UI.HtmlControls.HtmlGenericControl dynDiv1 =
               new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
                dynDiv1.Attributes.Add("class", "portfolio-blockimg3");


                System.Web.UI.HtmlControls.HtmlGenericControl dynDiv2 =
              new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
                dynDiv2.Attributes.Add("class", "portfolio-imgbox3");


                System.Web.UI.HtmlControls.HtmlGenericControl dynDiv3 =
             new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
                dynDiv3.Attributes.Add("class", "zoom");


                HyperLink hp = new HyperLink();

                Image img = new Image();
                img.ImageUrl = m_Photos[i];
                img.Height = new Unit (86);
                img.Width = new Unit(147);
                //hp.Attributes.Add("style", "z-index:100000000;");
                img.CssClass = "boximg-pad fade";
                hp.Controls.Add(img);
                hp.NavigateUrl = m_Original_Photos[i];
                hp.Controls.Add(img);
                hp.Attributes.Add("rel", "prettyPhoto[portfolio]");
                dynDiv3.Controls.Add(hp);
                dynDiv2.Controls.Add(dynDiv3);
                dynDiv1.Controls.Add(dynDiv2);
                liList.Controls.Add(dynDiv1);
                ulTag.Controls.Add(liList);
               
             
                
            }

            MainDIV.Controls.Add(ulTag);

            System.Web.UI.HtmlControls.HtmlGenericControl spacerDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
            spacerDiv.Attributes.Add("class", "spacer");

            MainDIV.Controls.Add(spacerDiv);
        }
    }
}

    



NewPhotoManager.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;
using System.Web.Security;

/// <summary>
/// Summary description for NewPhotoManager
/// </summary>
public class NewPhotoManager
{
    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.Access = PicasaQuery.AccessLevel.AccessPublic;

        //Below Code Can be used if you want all the albums
        PicasaFeed feed1 = PicasaService.Query(albumQuery);

        if (feed1 != null && feed1.Entries.Count > 0)
        {
            foreach (PicasaEntry entry in feed1.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);
            }
        }

    }
    //Return Thumbnail Images
    public static String[] GetPhotos(String Album_Name)
    {

        /////////////////////////
        PhotoQuery query = new PhotoQuery(PicasaQuery.CreatePicasaUri("YOUR PICASAUSERID", 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 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;

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;
 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="(Your PICASAUSERID)"/>
</appSettings>

IMPORTANT POINT: Don't put spaces in AlbumName