Create Dynamic Image Buttons

| Posted in

0

Introduction

We've all had that problem - designing our web sites to have a certain look and feel. Unfortunately, not every visitor will view the site the way you intended. This is due to the fact that different operating systems render native browser controls differently. The buttons in OS X have the aqua look while the buttons in Windows 2000 look gray and outdated.

Using the AnyButton

Until now, to enforce a consistent look, a popular option is using images as buttons. This is a great alternative except that when it comes time to add new buttons or modify existing ones, you better have Photoshop [and the time] handy to get it done.

I've created a control called the AnyButton which derives from System.Web.UI.WebControls.ImageButton. This button uses image templates as skins. It will take a .jpg, .gif or .png as a template. It is really easy to use, and best of all, looks just like a real button.

The control takes in a single image as a template. The button supports 3 different states - default, hover, and press. Moreover, each button supports 3 different skins - 1 for each state. This allows you to create as many types of buttons as you'd like by subclassing the base Button class. For instance, you could have an XPButton, AquaButton, AmazonComButton, etc. The best part is, you don't have to use Photoshop to create your buttons - if you see a button on a site you like, screen shot it, crop out the middle part and you're pretty much ready to go.

Here's an example using the XP button as a skin:

This is the default state template that I will assign to the button

This is the hover state template that I will assign to the button

And this is the press state template that I will assign to the button

As you can see, the red lines dictate how to slice the button. These lines must be the exact RGB color 255, 0, 0 or #FF0000.

Each button has a ButtonConfig class as a property. The ButtonConfig class contains all the information about the button templates. Here's an example using all button states, generating a button that resembles the XP Silver button:

///


/// Default button templated to resemble the XP Button
///

public class XPButton : AnyButton
{
public
XPButton()
{
this.EnableHover = true
;
this.EnablePress = true
;
}
public
XPButton(Page page)
{
this
.Page = page;
this.EnableHover = true
;
this.EnablePress = true
;
}
protected override void
OnInit(EventArgs e)
{
Initialize();
base
.OnInit(e);
}
protected override void
OnLoad(EventArgs e)
{
base
.OnLoad(e);
}
protected void
Initialize()
{
Font f = new
Font("Tahoma", 8, FontStyle.Regular);
ButtonConfig buttonConfig = new
ButtonConfig();
buttonConfig.TemplatePath = this
.AbsResourcesPath + "/default.png";
buttonConfig.Font = f;
buttonConfig.VerticalTextOffset = 1;
buttonConfig.FontColor = Color.Black;
this
.Config = buttonConfig;
ButtonConfig hoverConfig = new
ButtonConfig();
hoverConfig.TemplatePath = this
.AbsResourcesPath + "/hover.png";
hoverConfig.Font = buttonConfig.Font;
hoverConfig.VerticalTextOffset = buttonConfig.VerticalTextOffset;
hoverConfig.FontColor = buttonConfig.FontColor;
this
.HoverConfig = hoverConfig;
ButtonConfig pressConfig = new
ButtonConfig();
pressConfig.TemplatePath = this
.AbsResourcesPath + "/press.png";
pressConfig.VerticalTextOffset = buttonConfig.VerticalTextOffset + 1;
pressConfig.HorizontalTextOffset = buttonConfig.VerticalTextOffset + 1;
pressConfig.Font = hoverConfig.Font;
pressConfig.FontColor = buttonConfig.FontColor;
this
.PressConfig = pressConfig;
}
}

This example is pretty straight forward. One thing to note is the VerticalTextOffset and HorizontalTextOffset properties being utilized in the press config. To get a true pressed effect, the text should move to the bottom right 1 pixel by 1 pixel.

This XPButton class comes packaged along with the AnyButton assembly. When the buttons are requested, they need to be saved to a directory. The path to this output directory is defined in the web.config file as follows:

<appSettings>
<
add key="Oxford.Web.AnyButton.OutputPath" value="~/resources/"
/>
appSettings>

In this example, I'm setting the output path to be the in the /resources folder of my web application root. This setting must exist or a null reference exception will be thrown. The ASPNET user must have read/write access to this directory.

So far so good, right? Using the control is the easiest part. Have a look:

<%@ Register TagPrefix="btn" Namespace="MyNamespace" Assembly="MyAssembly" %>
<btn:XPButton Runat="server" Text="Click Me"/>

The last thing you need to do is add This is the result of the previous call:

As you can see, 3 images where created; 1 for each state. Any subsequent requests for an XPButton with text "Click Me" will now be redirected to the already-generated button image. To clear the cache of images, simply delete the output directory.

Additional Properties:

  • AlphaPng
    If you are using png files and you want to enforce transparency, set the AlphaPng setting to true. This is necessary because IE does not support alpha png (right on MS). When AlphaPng is true, a special css filter will be added only to IE users (Firefox, Safari, etc users will not be affected).
  • TextWidth
    Use this property when you want to enforce a certain width regardless of actual width of the text.
  • OnClientClick
    Handy little property that can be set in the markup adding client side function call when the button is pressed.
  • AntiAliasText
    True by default, applies anti-aliasing and ClearType effect.
  • CausesPostback
    By default, an ImageButton (from which this control derrives) is a submit button. To disable posting back, set this CausesPostback to false.

File uploader in C#

| Posted in

0

This is very basic level small user control, in which we can discuss how to create web user control.

To create user controls follow the steps:

  1. Right click on project
  2. Click on Add
  3. Select New Item
  4. Select Web User Control
  5. Specify some Name

I have given name to this file as "uploader.ascx" and kept this file under "userControl" for simplicity purpose.

On this page I am having following controls:

  1. <INPUT id="fileUpload" type="file" Runat="server" NAME="fileUpload">

  2. <asp:label id="lblMessage" runat="server" Width="416px" Font-Size="10" Font-Name="verdana">asp:label>

  3. <asp:button id="btnSave" runat="server" Text="Upload..">asp:button>

At the code behind of above file I am having following function

public string uploadFile(string fileName,string folderName)

{

if(fileName=="")

{

return "Invalid filename supplied";

}

if(fileUpload.PostedFile.ContentLength==0)

{

return "Invalid file content";

}

fileName = System.IO.Path.GetFileName(fileName);

if(folderName=="")

{

return "Path not found";

}

try

{

if (fileUpload.PostedFile.ContentLength<=2048000)

{

fileUpload.PostedFile.SaveAs(Server.MapPath(folderName)+"\\"+fileName);

return "File uploaded successfully";

}

else

{

return "Unable to upload,file exceeds maximum limit";

}

}

catch(UnauthorizedAccessException ex)

{

return ex.Message + "Permission to upload file denied";

}

}

The above function takes care of following things before uploading file to the folder

  1. Invalid file name supplied.
  2. If file not exists or content length 0.
  3. Folder name exists.

Error Handling

While uploading done with UnauthorizedAccessException and returned with the message

On upload button click I am having following code

private void btnSave_Click(object sender, System.EventArgs e)

{

string strFilename, strMessage;

strFilename = fileUpload.PostedFile.FileName.ToString();

strMessage = uploadFile(strFilename,ConfigurationSettings.AppSettings["folderPath"]);

lblMessage.Text = strMessage;

lblMessage.ForeColor = Color.Red;

}

I have made use of Web.config file, in which I have added attribute as follows under:

<configuration>
<appSettings>
<add key="folderPath" value="Images">add>
appSettings>

i.e. I have set up path of folder to upload image

To access control in project, I have added page called as "uploadTester.aspx" to the project in which I have added following line:

<%@ Register TagPrefix="img" TagName="Uploader" src="userControl/uploader.ascx"%>

Which says that this control is register to this page with specified source.

And in HTML code I have added following code inside form tag:

<img:Uploader runat="server" id="Uploader1">img:Uploader>

That's all about

General:

To upload any of the file in respective folder user need to have permission for writing to the folder so please follow the following steps to prevent from the error.

Set permission to virtual directory by following steps in IIS

  • Right Click on virtual directory which you have created for this project. Under directory Tab you will find
    1)Read
    2)Log Visits
    3)Index this resources
    Are marked as checked (enables) in addition to this make
    4)Write access enabled or checked
  • Click on apply
  • Click on ok

This will set right permission to entire virtual directory, this way we can minimize error from the front end for permission / access denied.

Other way to solve permission denied issue is to go to actual folder "images" by using physical path and follow these steps:

  • Right click folder
  • Sharing Tab
  • Enable share this folder radio button
  • Click Apply
  • Click Ok

If u are using this code on 2000 server you should do following:

  • Right click respective folder
  • Go to security tab
  • Select Everyone user
  • Apply full control
  • click on ok

Presenting Child Data along with Parent Row in Data Grid

| Posted in

0

Introduction

Data Grid gives a richer UI presentation for the web applications. Most of the time there may be requirement to show one or more child data that belong to the parent row in a column with in the Data Grid. Though this article doesn't explain how to have hierarchal layout in the Data Grid itself. It gives the sample code for defining a Repeater control inside the Template Column and have that Repeater bind to the child data of the parent row.

Data Grid HTML Code:

<asp:datagrid id="dataGrid1" runat="server" Width="792px"
OnItemDataBound="dataGrid1_ItemDataBound" AutogenerateColumns="False"
cellpadding="0" PagerStyle-Mode="NumericPages" PagerStyle-PageButtonCount="20"
PageSize="20" AllowPaging="True"AllowSorting="True"
OnSortCommand="dgAccountBalance_Sort">

<Columns>

-- First Column With ID as hidden column -->

<asp:BoundColumn DataField="ID" Visible="False" HeaderText="ID">
<
HeaderStyle Width="190px" HorizontalAlign="Center" >HeaderStyle>
asp:BoundColumn>

-- Second Column defined as Check Box in a Template Column -->

<asp:TemplateColumn HeaderText="Select" HeaderStyle-Width="40px" >
<
ItemStyle Width="40px">ItemStyle>
<
ItemTemplate>
<
input type="checkbox" runat="server" id="chkSelected"
checked ='<% # DataBinder.Eval(Container.DataItem, "Selected") %>' NAME="chkSelected"/>
ItemTemplate>
asp:TemplateColumn>

-- Third Column bound to the Field Description -->

<asp:BoundColumn DataField="Description" SortExpression="Description"
HeaderText="Description">
<
HeaderStyle HorizontalAlign="Center">HeaderStyle>
<
ItemStyle Wrap="True" Width="2000px">ItemStyle>
asp:BoundColumn>

-- Fourth Column a Numeric column for displaying Currenty with DataFormat -->

<asp:BoundColumn DataField="Amount" SortExpression="Amount" ReadOnly="True"
HeaderText="Amount" DataFormatString="{0:$#,##0.0000;($#,##0.0000)}">
<
HeaderStyle HorizontalAlign="Center" Width="70px">HeaderStyle>
<
ItemStyle HorizontalAlign="Right" Wrap="False">ItemStyle>
asp:BoundColumn>

-- Fifth Column That displays the child record of the row inside a Repeater control -->

<asp:TemplateColumn HeaderText="Child Data" HeaderStyle-HorizontalAlign="Center">
<
ItemStyle HorizontalAlign="Left" Wrap="True">ItemStyle>
<
ItemTemplate>
<
asp:Repeater ID="rptChild" OnItemDataBound = "rptChild_ItemDataBound" runat = "server"
DataSource = '<%# ((System.Data.DataRowView)Container.DataItem).Row.GetChildRows("relationParentChild") %>'>
<
ItemTemplate>
<
asp:LinkButton ID="linkChild" Runat="server"
CommandArgument=<%# DataBinder.Eval(Container.DataItem, "[\"ChildID\"]")%>
OnClick="linkChild_Click">
<%# DataBinder.Eval(Container.DataItem, "[\"ChildFieldNameToDisplay\"]")%>
asp:LinkButton>
ItemTemplate>
asp:Repeater>
ItemTemplate>
asp:TemplateColumn>

Columns>

<PagerStyle PageButtonCount="20" Mode="NumericPages">PagerStyle>
asp:datagrid>

Code Required in the Code Behind Page:

private void Page_Load(object sender, System.EventArgs e)
{
System.Data.DataSet ds = Get Data Set();
// This Data Set should be populated with two tables one for the Parent Row Data
// and the second for the child data to be displayed in the repeater control
ds.Relations.Add("relationParentChild",ds.Tables[0].Columns["ID"],ds.Tables[1].Columns["FKID"]);
DataView dv = ds.Tables[0].DefaultView;
dataGrid1.DataSource = dv;
}

Code Explanation:

Add the data grid control to the page and set it's properties like width,autogeneratecolumns, the events etc, as required. Then define the Bound Column and the DataField Name for those columns. These columns will be just displayed as Text. If some data needs to be presented in special controls like the Check Box as shown in the example have it defined in the Item Template Column. The code also shows how we can set the Data Format String for the column.

The Repeater should be declared inside the Item Template column in the grid.(inside a Item Template). The data source for the Repeater is set as ((System.Data.DataRowView)Container.DataItem).Row.GetChildRows("relationParentChild") inside the Server Tag. This will get the child rows of the row to which the Data is being Bound

In this example we are displaying a link button inside the Repeater and clicking on the link will take to appropriate page as required. This can be changed to as per the need. To access the child table's field this syntax is used DataBinder.Eval(Container.DataItem, "[\"ColumnNameinChildTable\"]")%

CommandArgument attribute used in the example is used to get the querystring to open up the page for the selected child link.

SOAP, .NET, and COM - An Introduction: Part I

| Posted in

0

SOAP is a protocol specification to invoke methods on servers, services, components and objects. The available procedure of using XML and HTTP as a method invocation mechanism is implied by SOAP. A small number of HTTP headers that facilitate firewall/proxy filtering are authorized by the SOAP specification. The SOAP specification also mandates an XML vocabulary that is used to represent method parameters, return values, and exceptions.

To exchange structured and typed information between peers in a decentralized, distributed environment using XML, SOAP presents an uncomplicated mechanism. SOAP defines a simple mechanism for expressing application semantics by providing a modular packaging model and encoding mechanisms for encoding data within modules instead of defining any application semantics such as a programming model or implementation specific semantics. This allows SOAP to be used in a large variety of systems ranging from messaging systems to RPC.

An Overview to SOAP

SOAP, (the Simple Object Access Protocol), is XML syntax to exchange messages. Moreover, since it is XML, it is independent from both language and platform. In addition, SOAP is a fundamental part of .NET, Microsoft's new development platform, and to understand what SOAP is and how it works it will be important for developers to move towards .NET.

In SOAP, there are four parts:

* The SOAP envelope construct: Defines an overall framework to express what is in a message, who should deal with it, and whether it is optional or mandatory.
* The SOAP encoding rules: Defines a serialization mechanism that can be used to exchange instances of application-defined datatypes.
* The SOAP RPC representation: Defines a convention that can be used to represent remote procedure calls and responses.
* The SOAP binding: Defines a convention to exchange SOAP envelopes between peers using an underlying protocol for transport.

Simply, SOAP is a well-documented wire protocol. Microsoft is getting behind SOAP and in future, probably will offer some type of implementation. However, other vendors can also do the same. For instance, the Perl implementation of SOAP is not tied to COM or Windows in any way, and if a modern version of Perl is available, can be used on any platform where. SOAP does not attach anyone to a particular platform. It provides a practical way to communicate over the Internet that is easy to implement on any platform.

Functionally, SOAP is very similar to IIOP which the underlying protocol used by most CORBA products. DCOM has additional protocol functionality such as garbage collection, causality that is not present in IIOP or SOAP. However, DCOM's extended functionality generally only needed in server-server communications and is not required in client-server communications. An advantage of both IIOP and DCOM side, SOAP packets be likely to be larger on the wire and can be somewhat more resource intensive to parse/generate.

A set of conventions for exchanging XML messages defined by the specification, such as rules for encoding data structures, an extensibility mechanism, a binding to the HTTP protocol, and conventions for RPC style invocations. For all SOAP messages that are exchanged between a web service and its client, SOAP defines the outer element. Namespace indicates to an XSLT processor that the XML is in fact a transform, just as the stylesheet element in the XSLT.

Moreover, the Envelope element in the SOAP namespace indicates to a SOAP processor that the XML is in fact a SOAP message. After that the processor can seek the individual pieces of the message, such as a mandatory Body element that has the actual request and an elective Header element that has extension elements. Below, a framework SOAP message is demonstrated.



<-- Headers go here -->
soap:Header>

<-- Request goes here -->
soap:Body>
soap:Envelope>

An extensibility mechanism is provided in the Header element in SOAP. This element can have any number of namespace qualified child elements. To the base SOAP protocol, each of these elements is some form of extension. Possibly one element holds data associated with conversation or session management between a client and a server. Another element might contain authentication information or even information pertaining to an ongoing transaction and another may contain locale information. Whatever their content or semantics each header element modifies the SOAP protocol in some way, also they providing extra context for the processing of the body of the message. It will be important to the client that the server honors them for some extensions; authentication is a good example to this.

SOAP Basics

At first, SOAP was based on HTTP, in Version 1.0 of the specification. Later on this changed, to allow for a wider variety of transport protocols (such as SMTP), or messaging protocols in the latest revision of the specification, Version 1.1 and Version 1.2. Two major design goals are outlined in the original SOAP specification: 1) Provide a standard object invocation protocol built on Internet standards, using HTTP as the transport and XML for data encoding, and 2) Create an extensible protocol and payload format that can evolve. Simplicity and extensibility are very important goals for SOAP. SOAP completely avoids several additional aspects of distributed object architectures.

* Distributed garbage collection-orphaned objects
* Pipelined messages or multiple call requests.
* Remote object activation
* Bi-Directional HTTP communications-callbacks
* Objects-by-reference
* Security

The individual SOAP implementation's architect designs the areas which the specification has not addressed, into a specific implementation. To solve some challenging real world issues that encumber existing distributed protocols and architectures is SOAP's objective. While existing protocols do address the items mentioned, and SOAP does not, SOAP addresses areas in which existing protocols fall short, such as scalability and the capability to share disparate yet interoperable using SOAP architectures.

SOAP Fundamentals

Actually, SOAP is based upon its technical worth; it is mainly the mixture of textual information shared via the Internet. SOAP processing is very much aligned with the Internet if you use HTTP as your SOAP transport protocol. SOAP specifies a stateless programming model with this processing. That means, object clients request services from a remote entity, which responds with the pertinent information. Currently, HTTP is a persistent technology and if a business interacts with the Internet in any meaningful fashion, it has to handle HTTP data. At the very least, HTTP processing is well understood and widely put into action. Some aspects of using SOAP, as with any tool, can be seen as advantages. In following list you may find some of the advantages of using SOAP.

* SOAP is built upon technologies, rather than vendor-specific technologies, and facilitates true distributed interoperability. At least not at this time, the SOAP market is not conquered by single vendor.
* The SOAP specification can ultimately consolidate the various HTTP tunneling protocols (IIOP and RMI to name two) into a single specification. This makes implementations easier and potentially more interoperable. SOAP typically uses HTTP but at least with the 1.2 version of the specification, it does not require its use.
* SOAP will likely work out of the box in a wide range of user locations that enable HTTP port 80 POST access.
* Loosely Coupled distributed applications are encouraged by SOAP.
* Unless significant serialization changes are made to the SOAP specification, changes to the SOAP infrastructures will likely not affect applications using the protocol.

When you choose remoting architecture, possibly there are many design facets that you need to consider about them. The following list includes some of them.

1. Scalability
2. Performance
3. Activation
4. State Management
5. Garbage Collection
6. Security

The wire protocols are not necessarily responsible for any or every design facet of the entire remoting architecture. For instance, not all of them implement security. However, for some or all these design facets, each protocol provides some level of support. Some protocols transmit security information as an integral part of their data packets, whereas others rely upon external systems to assure a secure connection. Beginning with scalability, each of these design issues is discussed to try to apply the same definition to all the wire protocols. SOAP simply is a wire protocol, unlike the other distributed object architectures. To compare SOAP with these other architectures; you need to apply the SOAP protocol as part of a distributed architecture of its own. On the other hand, even as a wire protocol, SOAP offers many advantages.





Figure 3.1 - SOAP Architecture

SOAP Messages

Since now we have covered SOAP at a high level, let us examine the most important detail of SOAP: the structure of a message. For messages, SOAP primarily uses XML syntax. A SOAP message contains a payload, the application-specific information. Here is an example of a SOAP message as an actual XML document:

<soap:Envelope xmlns:soap=http://schemas.xmlsoap.org/soap/envelope/
soap:encodingStyle="http://schemas.xmlsoap.org/soap/
encoding/">
<
soap:Header>
<
h:from xmlns:h="http://www.ets-
oftware.com/Header">
testuser@mydomain.comh:from>
soap:Header>
<
soap:Body>
<
w:GetMainIdentity xmlns:w="http://www.ets-software.com/Authors/">
<
w:nickname>XSLT-Authorw:nickname>
w:GetMainIdentity>
soap:Body>
soap:Envelope>


Figure 3.2 - SOAP Messages Architecture

Let us take a quick look at the XML of the message before we go into the contents of the SOAP message. As you may know, SOAP messages heavily rely on XML Namespaces. All of the elements in this document are prefixed with a namespace, and there is a good reason why the SOAP specification uses namespaces so extensively. All the elements of the message must be scoped in some fashion to avoid conflicts in the names of elements in order for a SOAP message to carry any arbitrary XML payload.

The namespace prefix soap is used on most of the elements in the above message. In the fallowing example, the prefix is associated with the namespace URI http://schemas.xmlsoap.org/soap/envelope/. It identifies the elements that are part of a standard SOAP message. The choice of soap is not relevant like all namespace prefixes. As in the fallowing, the namespace prefix could have been something else entirely:

<trial:Envelope xmlns:trial =http://schemas.xmlsoap.org/soap/envelope/
trial:encodingStyle="http://schemas.xmlsoap.org/
soap/encoding/">
<
trial:Header>
<
h:from xmlns:h="http://www.ets-
software.com/Header">
testuser@MyDomain.comh:from>
trial:Header>
<
trial:Body>
<
w:GetMainIdentity xmlns:w="http://www.ets-software.com/Authors/">
<
w:nickname>XSLT-Authorw:nickname>
w:GetMainIdentity>
trial:Body>
trial:Envelope>

If the namespace is the default namespace for the document, the namespace prefix could also be eliminated. As shown below, the default namespace is assigned using just the xmlns attribute:

<Envelope xmlns=http://schemas.xmlsoap.org/soap/envelope/
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<
Header>
<
h:from xmlns:h="http://www.ets-
software.com/Header">
testuser@MyDomain.comh:from>
Header>
<
Body>
<
w:GetMainIdentity xmlns:w="http://www.ets-software.com/Authors/">
<
w:nickname>XSLT-Authorw:nickname>
w:GetMainIdentity>
Body>
Envelope>

All three of these messages are acceptable and equivalent. It is better to use the soap namespace prefix for elements for better readability. All of the elements in the message that are associated with the soap namespace are standard elements of a SOAP message, as are the attributes. Any other elements are related to either message extensions or the message payload.

A traditional versioning model is not defined in SOAP based on major and minor version numbers. A SOAP message MUST have an Envelope element associated with the "http://schemas.xmlsoap.org/soap/envelope/" namespace. The application MUST treat a message as a version error and discard it if this is received by a SOAP application in which the SOAP Envelope element is associated with a different namespace. However, if the message is received through a request/response protocol such as HTTP, the application MUST respond with a SOAP VersionMismatch faultcode message using the SOAP "http://schemas.xmlsoap.org/soap/envelope/" namespace.

<soap:Envelope xmlns:soap=http://schemas.xmlsoap.org/soap/envelope/
soap:encodingStyle="http://schemas.xmlsoap.org/soap/
encoding/">
<
soap:Header>
<
h:from xmlns:h="http://www.ets-
software.com/Header">
testuser@MyDomain.comh:from>
soap:Header>
<
soap:Body>
<
w:GetMainIdentity xmlns:w="http://www.ets-software.com/Authors/">
<
w:nickname>XSLT-Authorw:nickname>
w:GetMainIdentity>
soap:Body>
soap:Envelope>

How WebParts on a page communicate with each other

| Posted in

0

Introduction:

In this tutorial we will describe how to make WebParts on a WebParts Page communicate with each other. So will see how to use ConnectionsZone and how to enable WebParts to talk to each other by connecting them.

Assumptions:

This tutorial assumes that you know how to work with web forms, creating user controls and connecting to data sources using SqlDataSource Control. Also you should know how to use WebPartZone control and to know what are WebParts and WebParts Pages.

How to implement connections between 2 WebParts:

The scenario is, we have 2 web parts, one display a drop down list of publishers, and the other display grid view of titles related to a specific publisher. So whenever I change the selection from the drop down list, the grid view should repopulated with the titles related to the selected publisher. This is very simple scenario just to show you how to implement WebParts Connections.

Preparing the WebParts Page:

  1. Create new WebForm, Name it WebPartsConnections.aspx, Also create 2 user controls, name them as UCPublishers.ascx & UCTitles.ascx.

  2. Open UCPublishers.ascx, drag and drop SqlDataSource control -name it sdsPubs- into it as well as a DropDownList -name it cmbPubs- and set its AutoPostBack Property to ture.

  3. Configure the SqlDataSource to select [pub_id] and [pub_name] from publishers table in pubs Database sample.



  4. Open UCTitles.ascx, drage and drop SqlDataSource control -name it sdsTitles- into it as well as a GridView -name it dvTitles-. Also drag and drop a HiddenField Control -name it hfSelectedPublisherID-

  5. Configure you SqlDataSource to select [title], [price] and [pubdate] from [titles] table in Pubs sample database, with pub_id as parameter. Configure the parameter to be a control parameter, and its value populated tom the HiddenField Control.



  6. Now Open your WebPartsConnections.aspx, Insert table with one column and one row.

  7. Drag and drop WebPartManager Control into the page-name it wpManager-

  8. Drag and drop 2 WebPartZone controls into the table, name them as wpzTop & wpzBottom.

  9. Drag and drop the UCPublishers.ascx from the solution explorer into the wpzTop. Do the same for UCTitles.ascx but drop it into wpzBottom. You can configure the Zones to use AutoFormat Professional Style.

  10. You can now Test the page. Notice that there is nothing happens when you change the publisher.

Building the Connection:

To implement the connection functionality between WebParts, we should create an Interface. This interface would be implemented by both UCPublishers.ascx as Connection Provider, and UCTitles.ascx as Connection Consumer. This interface serves as a contract for the communication between the provider and consumer.
We will name our Interface as ISelectedPublisher:
  1. Right click on App_Code and select New Item. (Create ISelectedPublisher.cs)

    public interface ISelectedPublisher
    {
    //ID of the selected publisher
    string
    SeletedPublisherID{get;}
    }

  2. Now open your UCPublishers.ascx in Code-View and implement the ISelectedPublisher as the following

    public partial class UCPublishers : System.Web.UI.UserControl, ISelectedPublisher
    {
    #region ISelectedPublisher Members
    //Get the Selected Value from the DropDownList that holds Publishers
    public string
    SeletedPublisherID
    {
    get { return cmbPubs.SelectedValue; }
    }
    #endregion
    [ConnectionProvider("SelectedPublisher", "SelectedPublisher")]
    public ISelectedPublisher GetSelectedPublisher()
    {
    return this;
    }
    }

    Essentially, we are implementing the ISelectedPublisher interface and creating a provider connection point by using the ConnectionProvider attribute. So we implemented the SelectedPublisherID property to return the selected publisher id from the DropDownList.

    Also we created the GetSelectedPublisher method. It is marked as ConnectionProvider, The first parameter to the ConnectionProvider attribute assigns a friendly name to the provider connection point. The second parameter assigns a unique ID to the provider connection point. Note the returned object is "this", which mean to consider the control instance itself as the connection provider.

  3. It is time to implement the Consumer now, so open the Code-View of your UCTitles.ascx and Consume the connection provided by the Provider:

    public partial class UCTitles : System.Web.UI.UserControl
    {
    private ISelectedPublisher _publisher = null;

    [ConnectionConsumer("SelectedPublisher", "SelectedPublisher")]
    public void SetSelectedPublisher(ISelectedPublisher selectedPublisher)
    {
    _publisher = selectedPublisher;
    }
    protected override void OnPreRender(EventArgs e)
    {
    base.OnPreRender(e);
    if (_publisher != null)
    {
    hfSelectedPublisherID.Value = _publisher.SeletedPublisherID;
    }
    }
    }


    Essentially, we are using the ConnectionConsumer attribute to define a consumer connection point -The SetSelectedPublisher Method-, and allowing it to act as a receiver of the ISelectedPublisher interface. The publisher that is received is then appended to the hidden field in the UCTitles.ascx Control on the PreRender event. The first parameter to the ConnectionConsumer attribute assigns a friendly name to the consumer connection point. The second parameter assigns a unique ID to the consumer connection point.

  4. Now Select the WebPartManager Control in your page -wpManager-

  5. From the property window, select ellipses beside the StaticConnections property. Configure it as the following.



    The ConsumerID is the ID of the Consumer Control, in our case it is the UCTitles Control which has the default ID UCTitles1.

    The ProviderID is the ID of the Provider Control, in out case it is the UCPublishers Control which has the dfault ID UCPublishers1.

    ConsumerConnectionPointID and ProviderConnectionPointID are the Attributes parameters mentioned earlier.



  6. Now its time to test your Page. Run it and change the publisher, you will notice that the Titles is changed in the GridView to display the publisher's Titles.

Working with ConnectionsZone:

Now we will Connect and Disconnect the WebParts Connections on the fly during runtime. To do so we need to use ConnectionsZone.

  1. Drag and drop ConnectionsZone Control into your page any place

  2. Add LinkButton to you page, -name it btnEditConnection- and set the text to "Edit Connection".

  3. Double click on it to implement its click event handler.

    protected void btnEditConnection_Click(object sender, EventArgs e)
    {
    if (btnEditConnection.Text == "Edit Connection")
    {
    wpManager.DisplayMode = WebPartManager.ConnectDisplayMode;
    btnEditConnection.Text = "View Page";
    }
    else
    {
    wpManager.DisplayMode = WebPartManager.BrowseDisplayMode;
    btnEditConnection.Text = "Edit Connection";
    }
    }

  4. Again run your page and click on the button. From the any of the WebParts Menu on the top right corner of the WebPart select Connect. Note that the Connection Zone Appears now. Test your page to see what you can do on the fly with Connection Zone and WebParts




Now we almost cover most of the basic features of WebParts and WebParts Pages. Hope this WebPart Tutorial series enrich your knowledge about WebParts and WebParts framework in ASP.Net 2.

Working with WebParts Page, WebPart Zones & WebParts

| Posted in

0

Introduction:

This tutorial considered to be the second part of the first tutorial Creating a Simple WebPart Page and use WebServer controls as WebParts. Here we will see how can we remove and add WebParts during run time, adding personalizable properties to your WebParts and modifying there values also in run time.

WebPart Zones:

There are 4 types of WebPart Zones. Zones is used to host (anchor or dock) WebParts. In the previous tutorial we had a look at WebPartZone. At this tutorial we will have a look at the other another two WebPart Zones, CatalogZone & EditorZone.

Modification to old project:

In the new project, have cut the XmlDataSource control -xdsRSS- and the DataList Control -dlstRss- to a newly created UserControl named UCtrlRSSReader.ascx. The same I did for SqlDataSource control -sdsTitles- and the GridView Control -gvTitles- which were saved on the UserControl UCtrlTitles.ascx.

Working with the CatalogZone:

Open the pervious project and apply the following modifications:

  1. Add another column to the table, so the table will contain 4 columns now.

  2. Drag and drop CatalogZone Control from control from the Toolbox (under the WebParts tab) into the new column cell, rename it to wpczCatalog and set its Auto format to Colorful.



  3. Drag and drop PageCatalogPart Control into the CatalogZone Control wpczCataog, rename it wpcPageCatalog.



  4. Drag and drop DeclarativeCatalogPart Control into the CatalogZone Control wpczCataog, rename it wpcDeclarativeCatalog.

  5. From DeclarativeCatalogPart Tasks smart tag, Select Edit Template.

  6. Then drag and drop UCtrlRSSReader from your solution explorer into the WebPartsTemplate area of wpcDeclarativeCatalog control, and click End Template Editing in the smart tag.



  7. Switch to Source view and add Title attribute to your UserControl you have just dropped, set its value to "RSS Reader". Be careful to edit the correct control:







  8. Drag and drop a DropDownList into your Web From but out of the table area, rename it to cmbWebPartPageMenu. Then add the following items to it.

    Normal View
    Design View
    Edit View
    Manage WebParts



  9. Set the AutoPostBack property of the DropDownList Control to true. and double click on it to implement it default event SelectedIndexChanged:

    protected void cmbWebPartPageMenu_SelectedIndexChanged(object sender, EventArgs e)
    {
    switch (cmbWebPartPageMenu.SelectedIndex)
    {
    case 0:
    wpManager.DisplayMode = WebPartManager.BrowseDisplayMode;
    break;
    case 1:
    wpManager.DisplayMode = WebPartManager.DesignDisplayMode;
    break;
    case 2:
    wpManager.DisplayMode = WebPartManager.EditDisplayMode;
    break;
    case 3:
    wpManager.DisplayMode = WebPartManager.CatalogDisplayMode;
    break;
    case 4:
    wpManager.DisplayMode = WebPartManager.ConnectDisplayMode;
    break;
    default:
    wpManager.DisplayMode = WebPartManager.BrowseDisplayMode;
    break;
    }
    }

  10. Now run your page, select Manage WebParts option and note the changes on the page.



    Click on Declarative Catalog link and notice the the deference.

    For any WebPart on the the page, click on its menu at the top right corner, and select Close. Notice the changes on the Catalog Zone. you will fine the Page Catalog is increased. Click on Page Catalog link and notice the change on the zone. You can add any WebPart listed to your page, by checking the checkbox of the WebPart, selecting the WebPart Zone and then click Add.

Hope by now you understand the deference between DeclarativeCatalogPart and PageCatalogPart. As DeclarativeCatalogPart contains WebParts that is possible to be added to the page and you defined them during design time. But they may not exists physically on the page. While PageCatalogPart contains all WebParts hosted on the Page.

Now let's work with the EditorZone Control.

Working with the EditorZone and add personalizable properties to WebParts:

  1. As we did while working with CatalogZone Control, drag and drop EditorZone Control into the 4th column just underneath the CatalogZone control, rename it to wpezEditor. Also set the Auto Format to Colorful.

  2. Drag and drop PropertyGridEditorPart & AppearanceEditorPart into the EditorZone control. rename the controls to wpPropertyGrid & wpAppearanceEditor.

  3. Open your UCtrlTitles.ascx control and switch to Code-Behind. We want to make one of the columns of the GridView inside that control to be optional for view. We will configure the Price Column for this.

  4. Declare a class level Boolean variable and name it _showPriceColumn as the following.

    private bool _showPriceColumn = false;

  5. Create a property for this variable. Mark the property with the following attributes:

    Personalizable() to be able to personalize the property for the WebPart.
    WebBrowsable() to be able to edit its value while in editing mode.
    WebDisplayName("Show Price Column") to display friendly name on the property grid wpPropertyGrid.

    [Personalizable(), WebBrowsable(), WebDisplayName("Show Price Column")]
    public bool ShowPriceColumn
    {
    get { return _showPriceColumn; }
    set { _showPriceColumn = value; }
    }

  6. Now override the OnPreRender Method of your control as the following:

    protected override void OnPreRender(EventArgs e)
    {
    base.OnPreRender(e);
    gvTitles.Columns[2].Visible = ShowPriceColumn;
    }

  7. Save your work and test the project. From the drop down list option, select Edit View. Then for your Titles or Books WebPart, select Edit from the top right corner menu or it. Notice that the Appearance and Property Grids Displayed. Also notice that the price column is not visible.



  8. Check the Show Price Column checkbox in the property grid. and click apply, Notice that the Price Column on the GridView is now visible.

Give yourself 10 min to examine the whole solution running.

Creating a Simple WebPart Page and use WebServer controls as WebParts-1

| Posted in

0

Introduction:

Portal web sites such as MY MSN and MSN Spaces, often organize their data into discrete units that support a degree of personalization. Information is organized into standalone parts [WebParts], and users can rearrange those parts to suit their individual working styles. Such personalization also lets users hide parts that contain information in which they have no interest. What's more, users can save their settings so that the site will remember their preferences the next time they visit the site. In ASP.NET 2.0, you can now build web portals that offer this kind of modularization of information and personalization using the new Web Parts Framework.

Scope of this Tutorial:

Here we will see how to add web parts to a web part page. Developing advanced WebParts from scratch is out of this tutorial scope. This tutorial also may has subsequent tutorial that explains more about Web Parts Framework.

Assumptions:

This tutorial assumes you are familiar with Data Access Controls and Data Binding Controls such as SqlDataSource and GridView. Also it requires SQL Sever 2005 Express Edition and Visual Web Developer. If you don't have SQL Server Express 2005, install ASPNETDB in your SQL Server instance using aspnet_regsql tool. and configure your application to use this instance as your personalization provider.

How to create WebParts Page:

To create a WebParts Page, you need to work with a specific ASP.Net 2.0 Controls:

  • WebPartManager Control, which manages all Web Parts controls on a WebParts Page and must be the first control that you add to the page.

  • WebPartZone Control, which contains and provides overall layout for the Web Part controls that compose the main UI of a page. This control serves as an anchor for Web Part controls. Multiple controls of this control forms the WebParts Page.

    The WebPartZone may contains one or more WebParts.

To create a WebPart Page:

  1. Create a home page for the Web Parts. Launch Visual Studio 2005 and create a new web site project.

  2. While in design view, drag and drop a WebPartManager control from the toolbox (under the WebParts tab) onto the default Web Form, rename it to wpManager.

    WebParts Controls Tab

  3. From Layout menu item, select Insert Table, insert table with 3 columns and 1 row. This is where the Web Parts on your page are to be located.

  4. Drag and drop a WebPartZone control from the Toolbox (under the WebParts tab) into each of the table's three cells. Each WebPartZone control will serve as the docking area for one or more Web Parts. A Web Part zone is an area where Web Parts are anchored. It also defines the default layout and appearance of each Web Part within that zone.

  5. Set the ID property for each WebPartZone Control to be wpzLeft, wpzMiddle and wpzRight. Then for each one set the Auto format to Professional.

    Auto Format

  6. Save your form.

You have created your WebParts Page. Now you want to add WebParts to your page, and manage them at run time so you can rearrange WebParts positions.

Next we will add 2 WebParts, one will display Information from SQL Server Database. While the other one will display data from XML file.

Adding WebParts to the WebParts Page:

  1. Drag and drop SqlDataSource control into you Web Form, rename it to sdsTitles. Configure it to retrieve data from Titles Table in Pubs Database. [you can use SQL Server 2000 or SQL Server 2005 any Edition].

    sdsTitles Code

  2. Drag and drop GridView into wpzLeft WebPartZone control, rename it to gvTitles. Configure gvTitles to user sdsTitles as a Data Source.

  3. Switch to the Source View and add title attribute to the GridVew -gvTitles- control and set its value to "Titles".



    Set Auto format for the GridView control to classic, also set the Paging and Sorting options, and set PageSize property to 5.

    GridView Settings

  4. Drag and drop XmlDataSource control to your Web Form, rename it to xdsRSS. Configure it to use the RSS.xml that is attached with the demo project, or use any other well-formed XML file you wish.

    xdsRSS Configuration

  5. Drag and drop DataList into wpzMiddle, and rename it to dlstRss. Switch to source view and configure your DataList as the following.

    dlstRss Source View

  6. Now test your page. You will be able to see the two Web Parts, minimize them or close them only. On the following steps you'll be able to create to move them and rearrange them.

  7. Drag and drop LinkBotton to your page, not into any Web Part Zone, rename it to btnDesign. and set its text property to "Design View"

  8. Double click on the button to add click event handler, then add the following code in the event handler method:

    protected void btnDesign_Click(object sender, EventArgs e)
    {
    if (btnDesign.Text == "Design View")
    {
    wpManager.DisplayMode = WebPartManager.DesignDisplayMode;
    btnDesign.Text = "Page View";
    }
    else
    {
    wpManager.DisplayMode = WebPartManager.BrowseDisplayMode;
    btnDesign.Text = "Design View";
    }

    }

  9. Now Run your application, note when you click on the button you can now rearrange you web parts on the page.

Conclusion:

Now have explored the basics of creating WebParts Page and adding WebParts to it at design/development time. This demo showed that every Control in ASP.Net 2.0 can be a web part without customization or extra code. Same for Custom User Controls; as you can put any controls we have just worked with into a user control, then drag and drop you user control into the WebPartZone and you will get your user control as WebPart.

WebParts is special kind of WebServer Controls. It has more advanced feature. Hope we will be able to discuss them in subsequent tutorials.

Select/Deselect all Checkboxes at Server side in ASP.NET using C#

| Posted in

0

Introduction:-

Some time we come across with the scenario where we need the function to select\deselect the checkboxes
from the server side code.The following code is going to describe the scenarion where we have one Panal Control which is having the multiple checkboxe

Code sample :-

//Drag and drop a panal control in asp.net web page

//Following will be the auto generated code with user defind controlName

protected System.Web.UI.WebControls.Panel PnlTimeExpence;

//Decleare one checkbox object

CheckBox chkList1;

//write a code to add dyanamic checkboxes

..
..

.. //code to add dyanamic controls(checkboxes). Check link above for adding dynamic checkboxes.

..

..

//Now we have a Panel control ready with multiple checkboxes.

//Fuction to select\Deselect checkboxes

private void SelectAllCheckBoxControls(Control parent,bool checkedVal)

{

try

{

string strLeave=string.Empty;

foreach (Control child in parent.Controls)

{

if (child.GetType().ToString().Equals("System.Web.UI.WebControls.CheckBox"))

{

CheckBox chk = (CheckBox)child;

chk.Checked=checkedVal;

}

}

}

catch(Exception exp)

{

throw new Exception("SelectAllCheckBoxControls " + exp.Message);

}

}

//Generate event on which we want to perform the select\deselect operation

//Following code is using a checkbox control to select \deselect the Event

private void chkReport_CheckedChanged(object sender, System.EventArgs e)

{

try

{

//Calling a userdefind function

SelectAllCheckBoxControls(PnlTimeExpence,chkReport.Checked);

}

catch(Exception exp)

{

throw new Exception("chkReport_CheckedChanged " + exp.Message);

}

}

Generate Dynamic Checkbox in ASP.Net using C#

| Posted in

0

Introduction

As a programmer we need to know about the static as well as dynamic controls. It's not necessary that always we will be using the static controls. Many programmers are having a mind setup like if they want the dynamic controls they have to write many lines of code but it's not like that.

Suppose we want to add dynamic control to a Panal control.So, what is the approach for that?

Following code will explain how to create the dynamic checkboxes.

Source Code:

//Drag and drop panal on the Webpage.

//After drag and drop following code will be generated automatically

protected System.Web.UI.WebControls.Panel PnlControl;

//Declare a CheckBox

CheckBox chkList1;

private void Page_Load(object sender, System.EventArgs e)

{

.

.

//Page load code goes here

.

.

}

#region dyanamic checkboxes

//Function to generate the dyanamic checkboxes

private void AddCheckboxes(string strCheckboxText)

{

try

{

if(PnlTimeExpence.HasControls())

{

return;

}

for(int intControlIndex=0;intControlIndex=5;intControlIndex++)

{

chkList1 =new CheckBox();

chkList1.Text = strCheckboxText;

chkList1.ID="Chk"+intControlIndex;

chkList1.Font.Name = "Verdana";

chkList1.Font.Size = 9;

PnlControl.Controls.Add(chkList1);

PnlControl.Controls.Add(new LiteralControl("
"));

}

}

catch(Exception exp)

{

throw new Exception(exp.Message);

}

}

#endregion

Developing a Visual WebGui gateway

| Posted in

0

Introduction

Visual WebGui basically leverages the WinForms object model giving the developer a new development experience developing rich internet applications like outlook web access. This object model by say covers 90% of what you need in order to create an outlook web access application. So how do we bridge the WinForms object model and web development? Through the concept of Gateways.

Background

Every WebGui component can declare it self as a WebGui gateway using the IGatewayControl interface, this allow controls to declare virtual URLs that are handles by the control by declaring actions. The IGatewayControl contains a method that gets an action name and should return a gateway handler. The gateway handler processes the request in the exact same way as an HTTP handler does, which actually means that you can also use HTTP handlers. This means that you can actually provide embedded ASPX pages that are hosted by the WinForms object model and can interact with that model making the interoperability between WebGui and legacy applications easy.

Other places you can use gateways:

  • Providing HTML based content to IFRAMES.
  • Providing a printable version of the current view.
  • Interacting with applets, flash, activeX and so on.
  • Using ASP.NET ready controls such as Janus grid.
  • Downloading files.

Visual WebGui is completely free to use and deploy for non-commercial purposes and is also available as an open source project in SourceForge.net. The Visual WebGui site has multiple free licenses that you can apply to in order to use it freely in your production site

This article creates a file list that can be previewed by selecting the file.

Using the code

In order to start developing Visual WebGui you need to download the SDK from the Visual WebGui download page. The installation will install a couple of assemblies to you GAC adding the Visual WebGui capabilities to your development enviroment. Installing the Visual WebGui SDK will add a two new projects to your Visual Studio (WebGui Application and WebGui Control Library). The WebGui Application project will create you a ASP.NET new project that one class named Form1.cs instead of the WebForm1.aspx file usualy created by the ASP.NET project template. Inheriting from the Gizmox.WebGUI.Forms.Form class the Form1.cs automaticly causes this file to have a WinForms like design time behavior. When you enter the design surface of the Form1.cs class you will have an aditional WebGUI toolbox available in the toolbox pane. These components can be draged to the design surface and be used exactly as WinForms components are used on a WinForms design surface. In the properties pane of any givven component you can change the component attributes including layout properties such as Dock and Anchoring which are WinForms way of layouting components and are fully supported by Visual WebGui.

Before you can run your application you need to have your form registerd in Visual WebGui web.config configuration section to a virtual page and have Visual Studio start page set to this virtual page. Visual WebGui uses a ".wgx" IIS script map extension that needs to be added to the IIS with the same definitions as the ".aspx" script map extension but without the check file exist check box as Visual WebGui uses virtual pages mapped to Gizmox.WebGUI.Forms.Form inherited classed. After setting these configurations you can start debugging your application exactly as you debug a WinForms application.

Step 1 - Creating a new WebGui Application project

Open the new project dialog and select the WebGui Application project. In the project name textbox enter WebGUIGateway and press OK.Visual WebGui will create you a new WebGui Application project that is both ASP.NET and WinFroms, as the structure is that of ASP.NET and the form classes behave like a WinForm form forms. Double clicking the Visual WebGui form1.cs page will open the design surface that is exactly the same as the WinForm design surface. The Visual Studio tool box has an added pane named WebGUI and you can find there Visual WebGui components which are identical to WinForms components. You can drag and drop components on the design surface exactly as you do in a WinForms application and the Visual WebGui designer will generate the code with in the InitializeComponent method.

Step 2 - Creating the main form

From the WebGUI toolbox pane drag a listview component on to the design surface and in the properties pane make it docked to the top. Drag a splitter and dock it to the top as well. Docking the splitter to the top will cause it to change the list view height. Drag an htmlbox and change it's docking to fill. Add the list view two columns for the file name and the file extension. Now you have the UI part of this tutorial ready.

Step 3 - Populating the list view

Go to the form properties and change to event view. Double click the Load event handler and the designer will create you an empty event handler. Add the code bellow to handler that will populate the listview with file list from a given path. Update the path to a valid path with gif images on your computer. Notice that the code generates list items and in the Tag property sets the full path of the file.

private void Form1_Load(object sender, System.EventArgs e)

{

DirectoryInfo objDir = new DirectoryInfo(@"C:\Inetpub\wwwroot\images");

foreach (FileInfo objFile in objDir.GetFiles("*.gif"))

{

ListViewItem item = listView1.Items.Add(objFile.Name);

item.SubItems.Add(objFile.Extension);

item.Tag = objFile.FullName;

}

}

Step 3 - Creating a gateway handler

A gateway handler is actually a class that inherits from IGatewayHandler, which has one method called ProcessGatewayRequest. The ProcessGatewayRequest method handles the request just as an IHTTPHanlder inherited class. In the ProcessGatewayRequest method you can actually write any thing you want into the response and in this case the handler take the path it got in the constructor and writes that file to the response. Create this class in your project.

using System;

using System.Web;

using Gizmox.WebGUI.Common.Interfaces;

namespace WebGUIGatway

{

public class FileHandler : IGatewayHandler

{

private string _path;

public FileHandler(string path)

{

_path = path;

}

#region IGatewayHandler Members

public void ProcessGatewayRequest(IContext objContext, IRegisteredComponent objComponent)

{

HttpContext.Current.Response.WriteFile(_path);

}

#endregion

}

}

Step 4 - Creating a gateway

In order to use gateways you need to have a control inherit the IGatewayControl interface which is under the namespace Gizmox.WebGUI.Common.Interfaces. A single control can expose multiple gateways. The control gateways are identified by an action code. The action code serves as a page name allowing gateways to be referenced by name. In order to reference to a gateway you need to create a GatewayReference object. GatewayReference can be constructed using a component and an action code that together will provide a unique gateway reference. So let's go ahead and make our form a gateway by implementing the IGatewayControl interface. The IGatewayControl has one method called GetGatewayHandler that has an action argument. Using the action parameter we can return different gateway handlers for different actions. So let's go and use the gateway handler we created before on an action named "OpenFile". Notice that in the path constructor we use the current selected item Tag property to get the path of the selected file.

public IGatewayHandler GetGatewayHandler(IContext objContext, string strAction)

{

IGatewayHandler handler = null;

switch (strAction)

{

case "OpenFile":

if (listView1.SelectedItem != null)

{

handler = new FileHandler((string)listView1.SelectedItem.Tag);

}

break;

}

return handler;

}

Step 5 - Using the gateway

Go back to the designer and select the list view control. From the properties of the list view go to the event section and double click the SelectedIndexChanged event. In the SelectedIndexChanged event handler let's create a GatewayReference object that can be found in the Gizmox.WebGUI.Common.Gateways namespace. Pass the constructor of the GatewayReference a reference to the form control and specify the action code of the gateway. When calling upon the ToString method of the GatewayReference class we get a relative path to the specified gateway. Use the relative path to set the htmlbox to show the current gateway. Calling the Update method on the HtmlBox will cause it to reload the control.

private void listView1_SelectedIndexChanged(object sender, System.EventArgs e)

{

GatewayReference reference = new GatewayReference(this, "OpenFile");

htmlBox1.Url = reference.ToString();

htmlBox1.Update();

}

Display hierarchal data in web form by using ASP.Net repeater

| Posted in

0

This below code shows how to display hierarchal data from multiple tables by using ASP.Net repeater control. This article shows hierarchal data from Categories, Products, Orders and Order Details tables of Northwind database.

Stored Procedure to get multiple recordset from Northwind Database :

The following stored procedure is used to get records from Categories, Products, Orders and Order Details table of Categories Id 4 and 6 only.

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
ALTER PROCEDURE GetOrderDetails
AS

-------- Get Category List -------------------
select
categoryid,
categoryname
from
categories
WHERE CategoryID IN (4,6)
order by
categoryname

-------- Get Product List ------------------------------
select
categoryid,
productid,
productname
from products
WHERE CategoryID IN (4,6)
order by productname

-------- Get Order List ---------------------------------
SELECT
OD.ProductID,
OD.OrderID,
dbo.Orders.OrderDate,
OD.Quantity,
OD.UnitPrice,
OD.Quantity*OD.UnitPrice Revenue
FROM
dbo.[Order Details] OD
INNER JOIN dbo.Orders
ON OD.OrderID = dbo.Orders.OrderID
where OD.ProductId IN (select productid from products WHERE CategoryID IN (4,6))
ORDER BY dbo.Orders.OrderDate
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

NRepeater.aspx.cs

===============

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient ;

namespace NestedRepeater

{

///

/// Summary description for NRepeater.

///

public class NRepeater : System.Web.UI.Page

{

protected System.Web.UI.WebControls.Repeater rptCategory;

private DataSet _dsOrderList;

private SqlCommand _cmd;

private SqlDataAdapter _da;

private SqlConnection _con;

private string _strFilter;

private int _productId;

private string _conStr = "server=(local); uid=sa;pwd=;database=northwind";

private void Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

if (!Page.IsPostBack )

{

GetDataSet();

}

}

private void GetDataSet()

{

_con = new SqlConnection(_conStr);

_cmd = new SqlCommand();

_cmd.CommandType = CommandType.StoredProcedure ;

_cmd.CommandText = "GetOrderDetails";

_cmd.Connection = _con;

_da = new SqlDataAdapter(_cmd);

_dsOrderList = new DataSet();

_da.Fill(_dsOrderList);

/*

Dataset _dsOrderList is populated with three recordset

Table[0] : Categories

Table[1] : Products

Table[2] : Orders

*/

// Create relationship between CategoryId of Categories table and CategoryId of Products table

_dsOrderList.Relations.Add("categoryProduct",_dsOrderList.Tables[0].Columns["CategoryId"],_dsOrderList.Tables[1].Columns["CategoryId"]);

_dsOrderList.Relations["categoryProduct"].Nested = true;

// Bind main repeater i.e. rptCategory with dataset categories table

rptCategory.DataSource = _dsOrderList.Tables[0].DefaultView ;

rptCategory.DataBind();

_con.close();

}

// GetOrderDetails method get executed on ItemBound event on rptProduct repeater

protected void GetOrderDetails( object source, RepeaterItemEventArgs e)

{

//**** Get ProductId current populated row of rptProduct repeater

_productId = (int) DataBinder.Eval(e.Item.DataItem,"ProductId");

//**** set filter string to get filtered records from order table

_strFilter = "ProductId=" + _productId.ToString();

//**** get default view of filter rows of order table

_dsOrderList.Tables[2].DefaultView.RowFilter= _strFilter;

//**** get reference of nested rptOrder repeater of rptProduct repeater

Repeater rpt = (Repeater) e.Item.FindControl("rptOrder");

if(rpt != null)

{

//*** bind nested rptOrder repeater with default view

rpt.DataSource = _dsOrderList.Tables[2].DefaultView ;

rpt.DataBind();

}

}

#region Web Form Designer generated code

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: This call is required by the ASP.NET Web Form Designer.

//

InitializeComponent();

base.OnInit(e);

}

///

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

///

private void InitializeComponent()

{

}

#endregion

}

}

ScreenShot:

Nested Repeater

Handling new line and carriage return with Textbox

| Posted in

0

Introduction

Handling newline and carriage return with Textbox while working with Databases.

The Scenario

If any data contain new line or carriage return or both, while displaying on input box, the data after these characters will not come. Though we can use TextArea for such type of data, sometime such situation comes in an unavoidable way.

In some case we need to refer to some external database and populate data depending on some predefined criteria for our further processing and submit them to another database. In such case, if we are using text box for the fields, we need to handle the newline and carraiage return characters in different way.

The GUI:

Searching and Populating the Data:

In some case we need to refer to remote database (external) and populate the data from that database depending on some predefined criteria for our further processing.

//Inside the loop of reading the records from DataReader

.

.

strEmpID = . . . ; //get the Emp ID

strName = . . . ; //get the Name

strAddress = . . . ; //get the Address

//Replacing the \n and \r with respective value to display

strAddress = strAddress.Replace("\n","\\\\n");

strAddress = strAddress.Replace("\r","\\\\r");

//strAddress can be use now for displaying

//Making the complete data for passing to the js Function for populating

//strData will used for populating the data in the input box

strData = strEmpID + "|" + strName + "|" + strAddress ;

.

.

//Now build up the java Script

strJScript = strJScript + " + strEmpID + "\" onClick="return setValues('" + strData + "');"

// setValues(strAdd) : This function will populates the data in the TextBox

.


.

Search then populated by clicking the radio button:

Submitting the data:

Before submitting the data to the dataset, we need to revert back our changes. We will replace '\\n' by (char)10 and '\\r' by (char)13.



.


.


strAddress = ReplaceForNewLineChar(strAddress);


strAddress = ReplaceForCarriageReturnChar(strAddress);


.


.

The replacement Algorithm:

public string ReplaceForNewLineChar(string strInput)

{

int tmpCounter = 0;

string strTmp1 = "";

string strTmp2 = "";

tmpCounter = strInput.IndexOf("\\n");

if (tmpCounter == -1)

{

return strInput;

}

else

{

strTmp1 = strInput.Substring(0,tmpCounter);

strTmp2 = strInput.Substring(strTmp1.Length + 2 ,strInput.Length

-(tmpCounter+2) );

strTmp1 = strTmp1 + (char)10 + strTmp2;

return ReplaceForNewLineChar(strTmp1);

}

}

public string ReplaceForCarriageReturnChar(string strInput)

{

int tmpCounter = 0;

string strTmp1 = "";

string strTmp2 = "";

tmpCounter = strInput.IndexOf("\\r");

if (tmpCounter == -1)

{

return strInput;

}

else

{

strTmp1 = strInput.Substring(0,tmpCounter);

strTmp2 = strInput.Substring(strTmp1.Length + 2 ,strInput.Length

-(tmpCounter+2) );

strTmp1 = strTmp1 + (char)13 + strTmp2;

return ReplaceForCarriageReturnChar(strTmp1);

}


}

DataSource controls in .NET 2.0

| Posted in

0

Introduction

In this article, we're going to learn how to connect a database for querying data and binding the result set to ASP.NET controls in a very easy way with no looping or control manipulation required, thus avoiding writing any data source code.

DataSource control is doing the work for me

DataSource is defined as ASP.NET controls that manage the tasks of connecting to a data source and reading and writing data. Data source controls do not render any user interface, but instead act as an intermediary between a particular data store (such as a database, business object, or XML file) and other controls on the ASP.NET Web page. It's acting as our business entities' placeholder in the application logic. The data source controls include any control that implements the IDataSource interface.

The .NET Framework includes the following data source controls:

  • ObjectDataSource. It enables you to work with a business object or other class and create Web applications that rely on middle-tier objects to manage data.
  • SqlDataSource. It allows you to connect to any data source that has an ADO.NET data provider (Microsoft SQL Server, OLE DB, ODBC, or Oracle).
  • AccessDataSource. It enables you to work with a Microsoft Access database.
  • XmlDataSource. It enables you to work with an XML file.
  • SiteMapDataSource. It is used for our site navigation.

Using a DataSource control in a Web application is fairly simple. Open a Web Form, and then, from the Toolbox at the Data tab, drag and drop a DataSource control to the form. This object represents business entities persisted in any storage medium which uses ADO.NET providers. Now, we must configure the control.

Click on the little icon, at the upper right corner for executing a configuration wizard which allows picking up a database connection according the actual connection strings in the connectionStrings section of the Web.config file (listing 1.) for query information and objects schema and writing Sql statements or defining store procedure calls for select, insert, update and delete commands. If you're using parameters, the configuration wizard presents a window for mapping some input information to these parameters. Parameters are always indicated with an @ symbol, as in @Region (listing 4.). You can define as many symbols as you want, but you must map each provider to another value. In this example, the value for the @Region parameter is taken from the ddlRegions.SelectedValue property of the DropDownList Control. (listing 4.)

The .NET Framework includes the following parameters:

  • Control property: A map to property value from another control on the page.
  • Query string: A map to a value from the current query string.
  • Session state: A map to value stored in the current user's session.
  • Cookie: A map to a parameter that can be used to bind to the value of a session variable.
  • Profile: A map to a value from the current user's profile.
  • Form variable: A map to a value posted to the page from an input control. Usually, you'll use a control property instead, but you might need to grab a value straight from the forms collection if you've disabled view state for the corresponding control.

There are some drawbacks associated to DataSource controls.

  • Data access logic is embedded in the page, so it's difficult to change issues for tuning or profiling after the application deploying.
  • Some code is duplicate because you have several DataSource control per page sometimes they have the same Sql statement.
  • Lack of flexibility because every Sql statement has separate DataSource, so if you want to provide different views for the data is very complicated.

I develop a little program for explanatory purpose.

Listing 1 is the configuration of the Web Application.

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<
connectionStrings>
<
add name="NorthwindConnectionString "
connectionString="Data Source=localhost;Initial Catalog=Northwind;
Integrated Security=SSPI"/>
connectionStrings>
...
configuration>

Listing 1. Web.config

Listing 2 is the code for the configuration of SqlDataSource1 object which is querying the database Northwind for gathering all Region which maps to current customers.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="select distinct Region from dbo.Customers">asp:SqlDataSource>

Listing 2. Form1.aspx

In listing 3, DropDownList WebControl binds all data of SqlDataSource1 which allows the customer to pick up a region. Notice that this control is able to do a postback action.

<asp:DropDownList ID="ddlRegions" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Region" AutoPostBack="True">

asp:DropDownList>

Listing 3. Form1.aspx

When you select a Region, a postback action is triggered, and the second data source retrieves all the customers in that region using the ddlRegions.SelectedValue as parameter for the query. Here's the definition for the second data source in the listing 4.

<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="select CustomerID, ContactName, Address, Country from dbo.Customers where Region=@Region">

<SelectParameters>

<asp:ControlParameter ControlID="ddlRegions" Name="Region" PropertyName="SelectedValue" />

SelectParameters>

asp:SqlDataSource>

Listing 4.

And finally in the listing 5 is the code for the configuration of the GridView control which binds the data from SqlDataSource2 in the Web Form for showing the group of customer associated to the selected region.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource2">

<Columns>

<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True"
SortExpression="CustomerID" />

<asp:BoundField DataField="ContactName" HeaderText="ContactName"
SortExpression="ContactName" />

<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />

<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />

Columns>

asp:GridView>

Listing 5.

Conclusion

This is an explanatory article for showing how to use another easy model of data access developed by the Microsoft.NET architects.

Outlook Style Menu with Collapsable Side Menu

| Posted in

0


Introduction

I have read an article at http://www.codeproject.com/useritems/XPMenu.asp which explains the dropdown XP style menu.

Just I would like to add new features,

  1. Collapsable side menu.

  2. Change the XP style menu in to Outlook style bar.(Using CSS File "SlideMenu.css")

I think that most developers suffer from the problem of the design of the menu, needs thier application GUI like Outlook or XP Style,

Therefore I think that this menu will provide solution to their problem.

Source code contains

  • SlideMenu.css file
  • menu.js file

Import Css file in your page

<LINK href="SlideMenu/images/SlideMenu.css" type="text/css" rel="stylesheet">

Collapsable side menu feature permit to hide side menu from page as a client script

Hide menu function:

<script type="text/javascript">

function lefthide()

{

var fr = parent.document.getElementById("sbCont");

if(fr.style.display=="")

{

fr.style.display="none";

change('outlookside', 'outlookBarExpand')

}

else

{

fr.style.display="";

change('outlookside', 'outlookBarcollapse')

}

}

function change(id, newClass)

{

identity=document.getElementById(id);

identity.className=newClass;

}

script>

I hope that I have succeeded in making this article and I wish to be useful to others.

Multiview Control in ASP.NET 2.0

| Posted in

0

One task common to web applications is data collections. For example one may need to collect some information from the end user, as in some sort of registration or some survey process. A rated good practice has been to often split the questions across multiple pages, so that the end user doesn't have jitters scrolling down the pages and by seeing the number of questions he/she would be made to answers. After all who likes to answers questions!!!

ASP.Net1.x offered developers to accomplish this by using panels and then selectively hiding and unhiding a set/group of controls. Or the way around was to create separate pages altogether, which sometimes became too cumbersome. ASP.Net2.0 offers the all new Multiview control to takes out the drudgery of creating multiple pages and thereby making life easier for the developers.

How To Do That?

Drag the Multiview control (located in the Standard Tab) from the toolbox onto the form, and drag two more view controls onto the Multiview. Populate the two view controls as shown below in the figure.

Multiview Control in ASP.NET 2.0

In the properties for the Multiview control set the ActiveViewIndex = 0. This means that view1 will be shown by default when the page gets loaded. All the views appearing in the Multiview control are a part of the view collection which itself is a part of the Multiview control. So by setting the ActiveViewIndex to 0 we make the first view (zeroth in the collection) to be the default view.

To add some functionality to the Next button (btnNext) double click button in the design view, and Visual Studio2005 generates the event for you in the code-file (Multiview.aspx.cs, in my case). Add the following code to the generated event: -

MultiView1.ActiveViewIndex += 1; //Make view2 as the next visible view

In the above code we are making the ActiveViewIndex of the Multiview to be 1. This is to make view2 visible, and hide view1.
Similarly double click the Back button (btnBack) and add the following line of code to the generated event:-

MultiView1.ActiveViewIndex -= 1; //Make view1 to be visible again.

Similar to the code for btnNext click event, here also we have set the ActiveViewIndex to -1, to make view1 visible and hide view2 on clicking btnBack.

The above is just some very elementary code written for illustrative purpose. Complex business logic can be written in a similar way. And any number of views can be added to the Multiview control, suiting to ones individual requirements.

Seeing It Work, Finally!!

Hit the F5 key on your keyboard to run the sample, and to see it work in completeness.

Multiview Control in ASP.NET 2.0

Multiview Control in ASP.NET 2.0

Visual WebGui application

| Posted in

0

Introduction

While web development environments such as ASP.NET and JSP have made huge strides in creating a rich environment for developing web applications, they have always targeted a very wide range of applications from content rich sites to OWA like applications. By doing so, they forced a compromise that was very painful for applications developers. Concepts like pages, html, requests and responses, which originated from the historical evolution of web development, are not really suitable for developing applications. While AJAX frameworks such as Atlas make a very nice edition to those enviroments they are still based on web development concepts which adds a great deal of complexity over desktop development concepts.

  • Download Visual WebGui SDK - 1.08Mb
  • Visual WebGui web site.

WebGui application

Background

Visual WebGui is a new AJAX framework that took a different approach to web application development, specially designed to simplify building highly complex applications like Outlook Web Access (OWA). Visual WebGui makes it possible for developers to create web applications by using full WinForms server side API that includes design-time capabilities. By adopting the WinForms object module and development concepts Visual WebGui has completely simplified the development of web applications. Alowing you to program as a VB/WinForms programmer and not as a web programmer makes much more sense when developing web applications like Outlook Web Access.

Visual WebGui is completly free to use and deploy for non-commercial purposes and is will also be available as an open source project in SourceForge.net. The Visual WebGui site has multiple free license that you can apply to inorder to use it freely in your production site

This article creates a fully AJAX enabled incremental explorer application browsing the wwwroot directories on the left pane and on the right pane the current selected folder files are displayed.

Using the code

In order to start developing Visual WebGui you need to download the SDK from the Visual WebGui download page. The installation will install a couple of assemblies to your GAC adding the Visual WebGui capabilities to your development enviroment. Installing the Visual WebGui SDK will add a two new projects to your Visual Studio (WebGui Application and WebGui Control Library). The WebGui Application project will create you a ASP.NET new project that one class named Form1.cs instead of the WebForm1.aspx file usualy created by the ASP.NET project template. Inheriting from the Gizmox.WebGUI.Forms.Form class the Form1.cs automaticly causes this file to have a WinForms like design time behavior. When you enter the design surface of the Form1.cs class you will have an aditional WebGUI toolbox available in the toolbox pane. These components can be draged to the design surface and be used exactly as WinForms components are used on a WinForms design surface. In the properties pane of any givven component you can change the component attributes including layout properties such as Dock and Anchoring which are WinForms way of layouting components and are fully supported by Visual WebGui.

Before you can run your application you need to have your form registerd in Visual WebGui web.config configuration section to a virtual page and have Visual Studio start page set to this virtual page. Visual WebGui uses a ".wgx" IIS script map extension that needs to be added to the IIS with the same definitions as the ".aspx" script map extension but without the check file exist check box as Visual WebGui uses virtual pages mapped to Gizmox.WebGUI.Forms.Form inherited classed. After setting these configurations you can start debugging your application exactly as you debug a WinForms application.

Step 1 - Creating a new WebGui Application project

Open the new project dialog and select the WebGui Application project. In the project name textbox enter WebGUIExplorer and press OK.

WebGui application

Visual WebGui will create you a new WebGui Application project that is both ASP.NET and WinFroms, as the structure is that of ASP.NET and the form classes behave like a WinForm form forms. Double clicking the Visual WebGui form1.cs page will open the design surface that is exactly the same as the WinForm design surface. The Visual Studio tool box has an added pane named WebGUI and you can find there Visual WebGui components which are identical to WinForms components. You can drag and drop components on the design surface exactly as you do in a WinForms application and the Visual WebGui designer will generate the code with in the InitializeComponent method.

WebGui application

Step 2 - Creating the main form

From the WebGUI toolbox pane drag a treeview component on to the design surface. The designer will create you a new treeview and it the properties pane you can change the component properties. From the properties pane select Dock property and change that property to Left. This will cause the designer to dock you treeview to the left. You can drag the right handle of the tree view to change the width of the treeview. Now, from the WebGUI toolbox pane select a splitter component and drag it to the design surface. By default the designer will apply left docking to a splitter which in this case works just fine. Drag a listview to the design surface and change it's docking to fill. The fill docking value causes the component to take all the remaining space.

Step 3 - Populating the tree view

Go to the properties pane of the form by clicking on the design form title while the properties pane is open. Change the properties pane mode to show events and double click the Load event. The designer will create you an empty event handler to handle the Load event. Which is executed when a Visual WebGui form is loaded. Create a new method that recieves TreeNodeCollection nodes and string path arguments. From the event handler we are going to call a the LoadFolder method with treeview1.Nodes and @"c:\inetpub\wwwroot", this will load the first level folders when the folder is loaded.

private void Form1_Load(object sender, System.EventArgs e)

{

LoadFolders(treeView1.Nodes,@"C:\inetpub\wwwroot");

}

private void treeView1_BeforeExpand(object sender, Gizmox.WebGUI.Forms.TreeViewCancelEventArgs e)

{

if(!e.Node.Loaded)

{

LoadFolders(e.Node.Nodes,e.Node.Tag as string);

e.Node.Loaded = true;

}

}

private void LoadFolders(TreeNodeCollection nodes,string path)

{

DirectoryInfo dir = new DirectoryInfo(path);

bool hasFolders = dir.GetDirectories().Length>0;

// Loop all sub directories

foreach(DirectoryInfo subdir in dir.GetDirectories())

{

// Create a new tree node

TreeNode node = new TreeNode();

node.Text = subdir.Name;

node.Tag = subdir.FullName;

node.IsExpanded = !hasFolders;

node.Loaded = !hasFolders; // This property is an extension to the WinForms API

node.HasNodes = hasFolders;

nodes.Add(node);

}

}

In the LoadFolder method we will add code that will enumarate the folders in the current path and create TreeNode objects appended to the nodes collection.

Step 4 - Populating the list view

Go to the Form1 constructor and add new column headers as shown in the next code snippet and set the UseInternalPaging property to true to enable Visual WebGui to handle paging internaly.

public Form1()

{

// This call is required by the WebGUI Form Designer.

InitializeComponent();

listView1.Columns.Add(new ColumnHeader("Name","Name"));

listView1.Columns.Add(new ColumnHeader("Extension","Extension"));

listView1.UseInternalPaging = true;

}

Go back to the designer and create a new event handler for the treeview AfterSelect event and with in the event handler you use e.Node.Tag to retrive the path that you need to show files from. Before you start adding items to the listview you should clear all the previous items.

private void treeView1_AfterSelect(object sender, Gizmox.WebGUI.Forms.TreeViewEventArgs e)

{

DirectoryInfo dir = new DirectoryInfo(e.Node.Tag as string);

listView1.Items.Clear();

// Loop all files in directory

foreach(FileInfo file in dir.GetFiles())

{

ListViewItem item = listView1.Items.Add(file.Name);

item.SubItems.Add(file.Extension);

}

}

Step 4 - Adding icons to spice up the UI

Visual WebGui has a diffrent resource management than WinForms as the execution context is diffrent handling actual images would be slightly heavy for a multithreaded enviroment and that way instead of images Visual WebGui has a concept of resource handles which are actuary references to actual resources. This way the Visaul WebGui server can optimize caching and retrival for resources as two resource handles pointing to the same resource handle are equal when compared. Visual WebGui contains some default resource handles such as IconResourceHandler and ImageResourceHandle that are references to directories defined with in the Visual WebGui configuration section. The resource handle uses java style file location method which means that folders are delimited by a dot.

Add a new using directive to the Form1.cs so you can create a resource handle object:

using Gizmox.WebGUI.Common.Resources;

Add icons to the creation of the TreeNode and the ListViewItem:

private void LoadFolders(TreeNodeCollection nodes,string path)

{

DirectoryInfo dir = new DirectoryInfo(path);

bool hasFolders = dir.GetDirectories().Length>0;

// Loop all sub directories

foreach(DirectoryInfo subdir in dir.GetDirectories())

{

// Create a new tree node

TreeNode node = new TreeNode();

node.Text = subdir.Name;

node.Tag = subdir.FullName;

node.IsExpanded = !hasFolders;

node.Loaded = !hasFolders; // This property is an extension to the WinForms API

node.HasNodes = hasFolders;

// Add icon to tree node

node.Image = new IconResourceHandle("folder.gif");

nodes.Add(node);

}

}

private void treeView1_AfterSelect(object sender, Gizmox.WebGUI.Forms.TreeViewEventArgs e)

{

DirectoryInfo dir = new DirectoryInfo(e.Node.Tag as string);

listView1.Items.Clear();

// Loop all files in directory

foreach(FileInfo file in dir.GetFiles())

{

ListViewItem item = listView1.Items.Add(file.Name);

item.SubItems.Add(file.Extension);

// Add icon to item

item.Image = new IconResourceHandle("file.gif");

}

}

Conclusion

As you can see from this example Visual WebGui simplifies application development by using WinForms as its basis. The designer, object model and syntax are exactly like WinForms which means you can quickly migrate existing WinForms projects, code and experience to the Visual WebGui platform. Creating complex, interactive browser based applications doesn't have to entail mastering AJAX, Javascript, XML or HTML. All it requires is familiarity with desktop application programming techniques which have proven themselves as productive.

SQL Server Backup file in Zip format

| Posted in

1

Introduction

This is SQL Server Backup and restore tool, the system will store the backup files in standard Zip format, the user-friendly screen let you backup and restore SQL Server database to local harddisk or remote network driver easily and quickly.The program can restore database easily.

To do:

  1. First Enter Your Sql Server username and password on corresponding Text Box.
  2. Click on Backup Button.
  3. It will take backup on folder ("application path"\Backup). if folder not found then program will create folder automatically in application path.
  4. After finish the job then check bkpfile on folder "Application path \Backup" bkp file created or not.

Important Functions

Add reference to SQL-DMO dll

You can do this by right clicking the project in Solution Explorer, then selecting 'Add Reference', COM components and the latest version of "Microsoft SQLDMO Object Library".

Available Server

public void dIsplayServerList(ComboBox cboListName)

{

try

{

SQLDMO.Application oSQLServerDMOApp = new SQLDMO.Application();

Info.informationLayer info = new Info.informationLayer();

SQLDMO.NameList oNameList;

oNameList = oSQLServerDMOApp.ListAvailableSQLServers();

for (int intIndex = 0; intIndex <= oNameList.Count - 1; intIndex++)

{

if (oNameList.Item(intIndex as object) != null)

{

cboListName.Items.Add(oNameList.Item(intIndex).ToString());

}

}

if (cboListName.Items.Count > 0) cboListName.SelectedIndex = 0;

else cboListName.Text = "(Local)";

}

catch

{

}

}

Available databases

public void dIsplayDatabases(ComboBox cboDatabase,Info.informationLayer info)

{

try

{

SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();

cboDatabase.Items.Clear();

SQLServer.Connect(info.strServerName,info.strLoginName,info.strPwd);

foreach (SQLDMO.Database db in SQLServer.Databases)

{

if (db.Name != null)

cboDatabase.Items.Add(db.Name);

}

cboDatabase.Sorted = true;

if (cboDatabase.Items.Count == 0)cboDatabase.Text = "";

}

catch (Exception err)

{

info.ErrorMessageDataLayer = err.Message;

}

}

Create backup in zip format :

public void cReateSQLDatabaseBackup(InfoSQLDMO.informationLayer InSQLDMO)

{//This is for Creating Database Backup.

try

{

DateTime dt = DateTime.Now;

String[] format = { "dd-MM-yy" };

string date;

date = dt.ToString(format[0], DateTimeFormatInfo.InvariantInfo);

string FileName = "bkp" + InSQLDMO.strdbName + date + ".bkp";

string myDocPath = InSQLDMO.strmyDocPath;

FileName = myDocPath + "\\Backup\\" + FileName;

// this.txtFile.Text = FileName;

if (Directory.Exists(myDocPath + "\\Backup"))

{

if (File.Exists(FileName) == false)

{

SQLDMO._SQLServer SqlSever = new SQLDMO.SQLServerClass();

SqlSever.Connect(InSQLDMO.strServerName, InSQLDMO.strLoginName, InSQLDMO.strPwd);

SQLDMO.Backup bak = new SQLDMO.BackupClass();

bak.Devices = bak.Files;

bak.Files = FileName;

bak.Database = InSQLDMO.strdbName;

bak.SQLBackup(SqlSever);

string DestFile = myDocPath + "\\Backup" + "\\" + "bkp" + InSQLDMO.strdbName+ date + ".zip";

zIpDatabseFile(FileName, DestFile);

if (File.Exists(FileName))

{

File.Delete(FileName);

}

InSQLDMO.ErrorMessageDataLayer = "Database Backup Process " + InSQLDMO.strdbName + " Sucessfully Completed";

}

else

{

InSQLDMO.ErrorMessageDataLayer = "The Backup file " + InSQLDMO.strdbName + " is already exists !. Do You Want to Continue..... '";

}

}

else

{

System.IO.Directory.CreateDirectory(myDocPath + "\\Backup");

SQLDMO._SQLServer SqlSever = new SQLDMO.SQLServerClass();

SqlSever.Connect(InSQLDMO.strServerName, InSQLDMO.strLoginName, InSQLDMO.strPwd);

SQLDMO.Backup bak = new SQLDMO.BackupClass();

bak.Devices = bak.Files;

bak.Files = FileName;

bak.Database = InSQLDMO.strdbName;

bak.SQLBackup(SqlSever);

string DestFile = myDocPath + "\\Backup" + "\\" + "bkp" + date + ".zip";

zIpDatabseFile(FileName, DestFile);

if (File.Exists(FileName))

{

File.Delete(FileName);

}

InSQLDMO.ErrorMessageDataLayer = "Backup Process " + InSQLDMO.strdbName + " Sucessfully Completed";

}

}

catch (Exception err)

{

InSQLDMO.ErrorMessageLogicLayer = err.Message;

}

}

Restore database in zip format:

public void cReateSQLDatabaseBackup(InfoSQLDMO.informationLayer InSQLDMO)

{//This is for Creating Database Backup.

try

{

DateTime dt = DateTime.Now;

String[] format = { "dd-MM-yy" };

string date;

date = dt.ToString(format[0], DateTimeFormatInfo.InvariantInfo);

string FileName = "bkp" + InSQLDMO.strdbName + date + ".bkp";

string myDocPath = InSQLDMO.strmyDocPath;

FileName = myDocPath + "\\Backup\\" + FileName;

// this.txtFile.Text = FileName;

if (Directory.Exists(myDocPath + "\\Backup"))

{

if (File.Exists(FileName) == false)

{

SQLDMO._SQLServer SqlSever = new SQLDMO.SQLServerClass();

SqlSever.Connect(InSQLDMO.strServerName, InSQLDMO.strLoginName, InSQLDMO.strPwd);

SQLDMO.Backup bak = new SQLDMO.BackupClass();

bak.Devices = bak.Files;

bak.Files = FileName;

bak.Database = InSQLDMO.strdbName;

bak.SQLBackup(SqlSever);

string DestFile = myDocPath + "\\Backup" + "\\" + "bkp" + InSQLDMO.strdbName+ date + ".zip";

zIpDatabseFile(FileName, DestFile);

if (File.Exists(FileName))

{

File.Delete(FileName);

}

InSQLDMO.ErrorMessageDataLayer = "Database Backup Process " + InSQLDMO.strdbName + " Sucessfully Completed";

}

else

{

InSQLDMO.ErrorMessageDataLayer = "The Backup file " + InSQLDMO.strdbName + " is already exists !. Do You Want to Continue..... '";

}

}

else

{

System.IO.Directory.CreateDirectory(myDocPath + "\\Backup");

SQLDMO._SQLServer SqlSever = new SQLDMO.SQLServerClass();

SqlSever.Connect(InSQLDMO.strServerName, InSQLDMO.strLoginName, InSQLDMO.strPwd);

SQLDMO.Backup bak = new SQLDMO.BackupClass();

bak.Devices = bak.Files;

bak.Files = FileName;

bak.Database = InSQLDMO.strdbName;

bak.SQLBackup(SqlSever);

string DestFile = myDocPath + "\\Backup" + "\\" + "bkp" + date + ".zip";

zIpDatabseFile(FileName, DestFile);

if (File.Exists(FileName))

{

File.Delete(FileName);

}

InSQLDMO.ErrorMessageDataLayer = "Backup Process " + InSQLDMO.strdbName + " Sucessfully Completed";

}

}

catch (Exception err)

{

InSQLDMO.ErrorMessageLogicLayer = err.Message;

}

}

Create file a zip :

private void zIpDatabseFile(string srcPath, string destPath)

{//This is for Zip a File

byte[] bufferWrite;

FileStream fsSource;

FileStream fsDest;

GZipStream gzCompressed;

fsSource = new FileStream(srcPath, FileMode.Open, FileAccess.Read, FileShare.Read);

bufferWrite = new byte[fsSource.Length];

fsSource.Read(bufferWrite, 0, bufferWrite.Length);

fsDest = new FileStream(destPath, FileMode.OpenOrCreate, FileAccess.Write);

gzCompressed = new GZipStream(fsDest, CompressionMode.Compress, true);

gzCompressed.Write(bufferWrite, 0, bufferWrite.Length);

fsSource.Close();

gzCompressed.Close();

fsDest.Close();

}

Create unzip a file :

private void uNzIpDatabaseFile(string SrcPath, string DestPath)

{// This is for unzip a files.

byte[] bufferWrite;

FileStream fsSource;

FileStream fsDest;

GZipStream gzDecompressed;

fsSource = new FileStream(SrcPath, FileMode.Open, FileAccess.Read, FileShare.Read);

gzDecompressed = new GZipStream(fsSource, CompressionMode.Decompress, true);

bufferWrite = new byte[4];

fsSource.Position = (int)fsSource.Length - 4;

fsSource.Read(bufferWrite, 0, 4);

fsSource.Position = 0;

int bufferLength = BitConverter.ToInt32(bufferWrite, 0);

byte[] buffer = new byte[bufferLength + 100];

int readOffset = 0;

int totalBytes = 0;

while (true)

{

int bytesRead = gzDecompressed.Read(buffer, readOffset, 100);

if (bytesRead == 0)

break;

readOffset += bytesRead;

totalBytes += bytesRead;

}

fsDest = new FileStream(DestPath, FileMode.Create);

fsDest.Write(buffer, 0, totalBytes);

fsSource.Close();

gzDecompressed.Close();

fsDest.Close();

}

Web Server Calendar Control in ASP.NET 2.0

| Posted in

0

The Calendar control is based on the .NET Framework DateTime object, and you can display any date between the years 0 and 9999 A.D.In the following article you will find that you can utilize the existing control as per you requirement.

In Visual Studio 2005 changing the template is quit easy as compare to MS VS 2003.You can see the templates below:-



Web Server Calendar Control in ASP.NET 2.0

Web Server Calendar Control in ASP.NET 2.0

Web Server Calendar Control in ASP.NET 2.0

Web Server Calendar Control in ASP.NET 2.0

Web Server Calendar Control in ASP.NET 2.0

Web Server Calendar Control in ASP.NET 2.0

Web Server Calendar Control in ASP.NET 2.0

Web Server Calendar Control in ASP.NET 2.0

After selecting the template for calender, editor will generate the following code for you:

<

asp:Calendar ID="calSource" runat="server" BackColor="#FFFFCC" BorderColor="#FFCC66" BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="#663399" Height="200px" ShowGridLines="True" Width="220px" OnSelectionChanged="calSource_SelectionChanged">
<SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />
<TodayDayStyle BackColor="#FFCC66" ForeColor="White" />
<SelectorStyle BackColor="#FFCC66" />
<OtherMonthDayStyle ForeColor="#CC9966" />
<NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />
<DayHeaderStyle BackColor="#FFCC66" Font-Bold="True" Height="1px" />
<TitleStyle BackColor="#990000" Font-Bold="True" Font-Size="9pt" ForeColor="#FFFFCC" />
asp:Calendar>

In the same way add other controls also

<

asp:DropDownList ID="drpMonthCal" runat="server" AutoPostBack="True" OnSelectedIndexChanged="drpCalMonth_SelectedIndexChanged" Width="101px">

asp:DropDownList>

<asp:DropDownList ID="drpYearCal" runat="server" AutoPostBack="True" OnSelectedIndexChanged="drpCalYear_SelectedIndexChanged" Width="104px">

asp:DropDownList>

<asp:Label ID="lblDate" runat="server" Text="Label" Width="390px">asp:Label>

Now you are ready with the web page.So you can start with the implementation.

protected

void Page_Load(object sender, EventArgs e)

{

//Hide the title of the calendar control

calSource.ShowTitle = false;

//Populate month and year dropdown list boxes which

//replace the original calendar title

if (!Page.IsPostBack)

{

Populate_MonthddList();

Populate_YearddList();

}

lblDate.Text = "Current date: " + calSource.TodaysDate;

}

private void Populate_MonthddList()

{

drpMonthCal.Items.Add("January");

drpMonthCal.Items.Add("February");

drpMonthCal.Items.Add("March");

drpMonthCal.Items.Add("April");

drpMonthCal.Items.Add("May");

drpMonthCal.Items.Add("June");