Friday, August 22, 2008

WPF Layout with Grid

WPF layout system helps in having fine grained control over the placing of controls.

Since I am more into the web domain I am most comfortable with the Grid which is the most versatile of the built in layout panels available in WPF.
Grid mimics the familiar html Table tags.
Here I am creating a Grid with 3 rows.


















I am add two columns using ColumnDefinitions.






















Now if a add a button to the Grid it will appear in the first row and column (zero based index). If I again add one more button to the grid the second button the take the precedence and hides the first button. It is possible to specify in which column the control should appear using Grid.Column and specifying the column number as sholwn in the figure below.














We can also specify the column number using Grid.Column.



















 <Window x:Class="WPFLayout.MainWindow"  
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
     xmlns:local="clr-namespace:WPFLayout"  
     mc:Ignorable="d"  
     Title="Shalvin" Height="450" Width="800">  
   <Grid ShowGridLines="True">  
     <Grid.RowDefinitions>  
       <RowDefinition Height="50"/>  
       <RowDefinition Height="50"/>  
       <RowDefinition Height="50"/>  
     </Grid.RowDefinitions>  
      <Grid.ColumnDefinitions>  
        <ColumnDefinition Width="150"/>  
        <ColumnDefinition Width="150"/>  
        <ColumnDefinition Width="150"/>  
      </Grid.ColumnDefinitions>  
     <Button>Shalvin.com</Button>  
     <Button Grid.Column="1">shalvinpd.blogspot.com</Button>  
   </Grid>  
 </Window>  

Thursday, August 14, 2008

Wpf and Windows Forms Controls Interop

Though WPF is a Wonderful technology, at times programmers get frustrated with the lack of certain controls. One such control is the DataGrid or GridView. Silverlight 2 infact has a DataGrid, hope in the next release of WPF it will be as feature rich as Windows Forms.

It is very much possible to use Windows Forms controls in WPF.

Start out by dragging a WindowsFormsHost into WPF Windows.


Create an object of System.Windows.Forms..DataGrid and set the Child Property of WindowsFormsHost to the newly created DataGrid object. WindowsFormsHost can have only one child as is obvious form the Child Property.

System.Windows.Forms.DataGrid dg = new System.Windows.Forms.DataGrid();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
windowsFormsHost1.Child = dg;
}

Now you can work with the DataGrid just like you work with it in Windows Forms.

Here is the complete code for connecting the DataGrid to a DataSet.

using System.Data;
using System.Data.SqlClient;

using System.Windows.Forms;

System.Windows.Forms.DataGrid dg = new System.Windows.Forms.DataGrid();

SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
windowsFormsHost1.Child = dg;

cnn = new SqlConnection(@"Integrated Security=sspi;Initial Catalog=Shalvin;Data source=.\sqlexpress");
cnn.Open();
da = new SqlDataAdapter("select * from Categories", cnn);
da.Fill(ds, "Cat");
dg.DataSource = ds.Tables["Cat"];
}

Sunday, July 6, 2008

.Net Code Access Security Introduction

CAS is the programatically means by which you secure the resouce of a system like file system, printer, registry, etc. in contrast to Role Base Security (RBS).

RequestOptional is used to grant permission to a resource.
RequestRefuse is used to revoke permission to a resource.

In following example I am going to restrict writing to C drive. Incase if user tries to write to C drive programatically he is receive an exception.

using System.Security.Permissions;
using System.Security;
using System.IO;

[assembly: FileIOPermissionAttribute(SecurityAction.RequestRefuse , Write="c:\\")]namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
StreamWriter sw;

private void button1_Click(object sender, EventArgs e)
{
sw = File.CreateText("c:\\Shalvin.txt");
sw.WriteLine("Hello");
sw.Close();
}


For a detailed coverage of Code Access Security refer http://www.codeproject.com/KB/security/UB_CAS_NET.aspx
Courtesy : Jeevan Baby, Indiaoptions

Thursday, June 26, 2008

My .Net Videos in Youtube/Google videos

Asp .Net Ajax Videos
Asp.Net Ajax II : TextBoxWatermarkExtender
Asp .Net Ajax III : ConfirmButtonExender
Asp .Net Ajax III : SliderExtender
Asp .Net Ajax V : MaskEditExtender






Asp .Net 2.0 Membership Vidoes
Asp.Net 2.0 Membership I : LoginStatus LoginName
ASP.Net 2.0 Membership II : LoginView Control
ASP.Net 2.0 Membership III - CreateUserWizard
ASP.Net 2.0 Membership IV Roles
aspnet_regsql : Adding Membership tables to Sql Server
WPF
WPF I : Button - Shalvin
Asp .net State Management
Asp .Net Query String
ASP.Net (VB.Net) Session Variable ArrayList
Asp .Net Profile



Asp .Net Controls
Asp.Net I : Introduction and Button Control
ASP.Net Controls - II : TextBox
Asp.Net III : ListBox Inline Page Mode IsPostBack
Asp.Net IV : Label AssociateControlId AccessKey
Implementing Date Selection Functionality using Multiple Combo Boxes
C#
String.Format
C# Error Handling - Shalvin P D
VB .Net
VB.Net 2008 Controls III :ListBox
VB .Net 2008 Controls V : NumericUpDown
VB .Net 2008 Controls VI : Simple Calculator

Google Videos
Creating Window Service in C#
C# (Windows Forms) MultiThreading


WPF Creating Class C#
Ado .Net
Introduction to Ado .Net
Ado .Net ExecuteScalar
Asp .Net
Displaying DataReader Contents in a RadioButtonList

Asp.Net (VB.Net) DropDownList DataTextField DataValueField

Asp.Net (VB.Net) Displaying DataReader contents in a RadioButtonList

ASP.Net DataList HyperLink with Wizard
FileUpload Control
Asp.Net C# DataSet GridView

ASP.Net (C#) Tracing

Asp .Net 2.0 Membership videos
ASP.Net Membership Authentication, Authorization and Role based security
Asp.Net 2.0 Membership V Denying Anonymous users
Asp.Net 2.0 Membership VIII Protecting a folder












C# Windows Forms
PrintDocument and PrintPreview Control

Gdi+
I : DrawString DrawLine
II : FillRectangle FillEllipse
III : Custom Pen
IV : HatchBrush
V: Color.FromArgb
VI :ScreenSaver : Random Class and Timer Control

VII : Working with Bitmaps

Gdi+ (ASP.Net) XII : Bitmap DrawString

Multithreading and Miscellaneous
Multithreading in Windows Forms
Code Access Security

Compression and Decompression in .Net
Win32 Api Visual Basic 6 : SwapMouseButton
Reflection in .Net : Displaying all properties, methods and events of a type


Xml
XmlDocument in VB .Net

Extracting xml from Sql Server tables

Sql Server
Sql Server 2005 : Creating Tables and Relationships (Sql)
Sql Server WHERE Clause and Stored Procedures
Web Service
Creating and consuming Web Service
Web Parts
Asp .Net Web Parts : Design Mode and Brose Mode

Saturday, June 21, 2008

Creating Asp .Net Custom Controls

Custom Controls are reusable dlls.
Start out by creating a class library in C#. Add reference to System.Web. We are overriding the Render method of System.Web.UI.Control class and using HtmlTextWriterClass we are outputing Text to the browser.

using System.Web;
using System.Web.UI;

namespace HelloCustomCtl
{
 public class HelloCtl : Control 
 {
  protected override void Render(HtmlTextWriter writer)
  {
   writer.Write("Shalvin");
  }
 }
}

Build the project.

Testing the Custom Control

Start ASP .Net, preferably add a new tab to the toolbox. Right click the tab and select Choose Item. Click on the browse button navigate to the bin folder of previously created class library and select the dll.
Now the control will appear in the toolbox and you can use it in your project.

WebControl With Properties
Since WebControl class provides the properties, methods, and events that are common to all Web server controls, this control eventually will have a set of common properties found in common controls.
Along the way we are implementing two properties Text and Location that can be set from propeties window while using the control.

using System.Web.UI;
using System.Web.UI.WebControls;

public class MultiTdCtl : WebControl
{

private string mText;
public string Text
{
get { return mText ; }
set { mText = value; }
}

private string mLocation;
public string Location
{
get
{
return mLocation;
}
set
{
mLocation = value;
}
}

protected override void RenderContents(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Border, "1");
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(mText); writer.RenderEndTag ();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.WriteLine(mLocation);
writer.RenderEndTag();
writer.RenderEndTag();
writer.RenderEndTag();
}
}

With C# 3.0 the lengthy getter and setter code is not required in fact you replace the code with the following :

public string Text
{
get;
set;
}
public string Location
{
get;
set;
}

..writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(Text); writer.RenderEndTag ();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.WriteLine(Location);

Creating Composite Control

using System.Web;
using System.Web.UI.WebControls;

namespace CompositeCtl
{
public class CompositeCtl : CompositeControl
{
    Label lbl;
    TextBox txt;

   protected override void CreateChildControls()
    {
        lbl = new Label { Text = "Name" };
        this.Controls.Add(lbl);


        txt = new TextBox();
        this.Controls.Add(txt);
    }
}
}
Composite Control 2
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CompositeCtlEg
{
   public class ShalvinCompositeCtl : CompositeControl
    {
       Label lbl, lblMessage;
       TextBox txt;
        Button btn;
        protected override void CreateChildControls()
        {
            lblMessage = new Label { Text = "" };
            this.Controls.Add(lblMessage);
            lbl = new Label { Text = "Name" };
            this.Controls.Add(lbl);

            txt = new TextBox();
            this.Controls.Add(txt);

            btn = new Button { Text = "Shalvin" };
            btn.Click +=new EventHandler(btn_Click);
            this.Controls.Add(btn);
        }

        void btn_Click(object sender, EventArgs e)
        {
            lblMessage.Text = "Hello " + txt.Text;
        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
           
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.AddAttribute(HtmlTextWriterAttribute.Colspan, "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
           lblMessage.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            lbl.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            txt.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            btn.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderEndTag();
            
            writer.RenderEndTag();
        }
    }
}

Wednesday, June 18, 2008

Session Asp .Net : Storing DataSet

This blog is an add on to my youtube vide ASP.Net (VB.Net) Session Variable ArrayList - Shalvin
Session state allows values to be stored in one page and accessed through out the site. Session state allows complex data to be stored whereas Query String supports only string value.
The session data is stored in the memory of Web Server.

Asp .Net uses an unique 120 bit identifier for tracking sessions. This ID is the only piece of information that is transmitted between the web server and the client. When the client presents the session ID, ASP.NET looks up the corresponding session, retrieves the serialized data from the state server, converts it to live objects, and places these objects into a special collection so they can be accessed in code. This process takes place automatically.
It is possible to store large amounts of data in a Session Variable. In this example I am constructing a dataset and assigning the contents to a Session variable and passing the showing the data of session variable on another page.

This example makes use of appSettings section of web.config to store connectionstring information. If you are not familiar with appSettings visit my blog Web.config's appSettings section to avoid hard coded memory variable

//web.config




//Default.aspx


using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
 SqlConnection cnn;
 SqlDataAdapter da;
 DataSet ds = new DataSet();
 protected void Page_Load(object sender, EventArgs e)
 {
  cnn = new SqlConnection(ConfigurationManager.AppSettings.Get	("Cnn"));
cnn.Open(); da = new SqlDataAdapter("select ProductName, UnitPrice from Products", cnn); da.Fill(ds, "Prod");
Session["Prod"] = ds.Tables["Prod"];
} protected void btnShowCart_Click(object sender, EventArgs e) { Response.Redirect("ShoppingCart.aspx");
} }

protected void Page_Load(object sender, EventArgs e)
{
 GridView1.DataSource = (DataTable)Session["Prod"];
 DataBind();
}

Related Blogs
Query String Asp .Net : Working with multiple values

ASP.Net 2.0 Profile

Query String Asp .Net : Working with multiple values

Query string is the part of URL that can be used to send data as parameters. Let's first analyze the query string generated by Google on making a search for 'Shalvin'

http://www.google.co.in/search?hl=en&q=Shalvin.Here two values are passed as query string.

Create a Web site with two web pages.
In the button click of Default.aspx write the following code:

protected void sumButton_Click(object sender, EventArgs e)
{ Response.Redirect("Sum.aspx?Val1=" + txtVal1.Text + "&Val2=" + txtVal2.Text); }

Here is the code for extracting the value in the second page.
protected void Page_Load(object sender, EventArgs e)
{
	Response.Write("Hello " + Request.QueryString["Name"] + " your blog is " + Request.QueryString["Blog"]);
}
 Calculator

<body>
    <form id="form1" runat="server">
    <div>
    
        Value 1<asp:TextBox ID="txtVal1" runat="server"></asp:TextBox>
        <asp:CompareValidator ID="CompareValidator1" runat="server" 
            ControlToValidate="txtVal1" ErrorMessage="Value cannot be string" 
            Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
        <br />
        <br />
        Value 2<asp:TextBox ID="txtVal2" runat="server"></asp:TextBox>
        <asp:CompareValidator ID="CompareValidator2" runat="server" 
            ControlToValidate="txtVal2" ErrorMessage="Value cannot be string " 
            Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
        <br />
        <br />
        <asp:Button ID="sumButton" runat="server" onclick="Button1_Click" Text="Button" />
    
    </div>
    </form>
</body>


Default.aspx

protected void Button1_Click(object sender, EventArgs e)
{ Response.Redirect("Sum.aspx?Val1=" + txtVal1.Text + "&Val2=" + txtVal2.Text); }

Sum.aspx
int i, j, res;
protected void Page_Load(object sender, EventArgs e)
{
    i = Int32.Parse(Request.QueryString["Val1"]);
    j = Int32.Parse(Request.QueryString["Val2"]);
    res = i + j;
    Response.Write(res.ToString());
}


Related Blog

ASP.Net 2.0 Profile

Session Asp .Net : Storing DataSet

Saturday, June 14, 2008

Ajax ASP .Net VII : Accordion Control and CollapsiblePanelExtender

First let's see Ajax in action.

The page is displaying Shalvin's content by default. Only headers of Site and Contact Info are visible.








When you click on Site and Blog header, it will show its contents and other contents are invisible as shown in the figure below.













Having seen the functionality lets try to implement it.
Working with Accordion is a bit tough in comparison to the controls I have already explained because you won't get a visual interface for working with Accordion and you have to work this control in source view.

If you are not familiar working with Asp .Net is source view visit my blog Asp .Net Introduction : Notepad way



















Inside the Accordion tag place a Panes tag. Inside Panes you can have AccodionPane. AccordionPane inturn have Header and Content. I have added a b tag for Header. In real time you have to use CSS for better look and feel.


Accordion Databinding


Accordion control would most likely be used in conjunction with database data.



Here I am creating an SqlDataSource Control that point to Northwind database's Suppliers table.



I am setting the DataSourceId property of Accordion to the SqlDataSource id and creating HeaderTemplate and ContentTemplate as shown below.



If you are not comfortable working with templated controls visit my blog Asp .net DataList.


















Result

























Here I have made the header Bold and Underline. When you click on a header you can see the contents.










Adding CSS















CollapsiblePanelExtender

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

<asp:CollapsiblePanelExtender ID="CollapsiblePanelExtender1" runat="server"
CollapseControlID="Header"
ExpandControlID= "Header"
TargetControlID="Content">
</asp:CollapsiblePanelExtender>
</div>

<asp:Panel ID="Header" runat="server" Height="16px" Width="293px">
<u>Shalvin P D </u></asp:Panel>

<asp:Panel ID="Content" runat="server">
.Net Consultant and Corporate trainer<br /> Blog :shalvinpd.blogspot.com
</asp:Panel>


Related Blogs




Ajax .Net I : Extension Controls in Visual Studio 2008


Ajax .Net II : Setting up Ajax Control Toolkit controls




Ajax .Net III : CalendarExtender Control


Ajax .Net IV : TextBoxWaterMarkExtender




Ajax .Net V : FilteredTextBoxExtender


Ajax .Net VI : ConfirmButtonExtender