.Net Hive

A blog about Microsoft .Net Platform & other industry happenings

Custom Events in ASP.NET User Controls

Hello Everyone,

Yesterday I was working on a user control and I came across a situation where I wanted to notify the parent page when ever the button in the user control get clicks.

This situation calls for a requirement of having a custom event associated with the user control I can then use in the host page, which encapsulates the user control.

Here is the core source code to required to achieve this functionality:

CustomUserControl.ascx.cs

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

public partial class CustomUserControl : System.Web.UI.UserControl
{
public event EventHandler SubmitClick;

protected void btnSubmit_Click(object sender, EventArgs e)
{
this.OnSubmitClick(e);
}

protected void OnSubmitClick(EventArgs e)
{
if (SubmitClick != null)
{
SubmitClick(this, e);
}
}
}

Because I needed the event to be executed when ever the submit button get executed, there for I invoked the method at the Submit button click. You can change it according to your requirement.

HostWebPage.aspx.cs

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

public partial class HostWebPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
userCustomControl.SubmitClick += new EventHandler(userCustomControl_SubmitClick);
}

void userCustomControl_SubmitClick(object sender, EventArgs e)
{
//DO ANY WORK
}
}

I tried to make this example as simple as possible. Let me know if this helped. Any suggestion or queries are welcome.

Happy Reading

Waqas Ahmed

Advertisements

Filed under: ASP.NET, , , ,

Socket / Network Programming in C#

Today I have decided to give a quick tutorial on Sockets/Network programming in C#. For this I have taken an example of a simple Client/Server application scenario. Where a Socket listen on a specific port and waits for the client to be connected. Once the client is connected, The client application will send a test message to the server application. I will try to achieve this functionality using minimal code and to give a concept of how socket programming works.

Hope this will be helpful. Following is the server application code.

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

class SocketServer
{
  public static void Main()
  {
    StreamWriter streamWriter;
    StreamReader streamReader;
    NetworkStream networkStream;
    TcpListener tcpListener = new TcpListener(3333);
    tcpListener.Start();
    Console.WriteLine("Server Started. Waiting for Client Connection at port 3333");
    Socket serverSocket = tcpListener.AcceptSocket();
    try
    {
        if (serverSocket.Connected)
        {
            while (true)
            {
                Console.WriteLine("Client Connected at port 3333");
                networkStream = new NetworkStream(serverSocket);
                streamWriter = new StreamWriter(networkStream);
                streamReader = new StreamReader(networkStream);
                Console.WriteLine(streamReader.ReadLine());

            }
        }
        if (serverSocket.Connected)
            serverSocket.Close();
        Console.Read();
    }
    catch (SocketException ex)
    {
        Console.WriteLine(ex);
    }
  }
}

When the above code is executed, it will try to listen on port 3333 and will wait for an incoming connection from a client application. Upon start, server application will display a message “Server Started. Waiting for Client Connection at port 3333”. As soon as the server application recives the connection from client application, it show the message “Client Connected at port 3333”.

Now let’s see how our client application code looks like. Our client application will try to connect at port 3333. Following is the Client Application Code:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

class SocketClient
{
  static void Main(string[]args)
  {
    TcpClient tcpClient;
    NetworkStream networkStream;
    StreamReader streamReader;
    StreamWriter streamWriter;
    try
    {
        tcpClient = new TcpClient("localhost", 3333);
        networkStream = tcpClient.GetStream();
        streamReader = new StreamReader(networkStream);
        streamWriter = new StreamWriter(networkStream);
        streamWriter.WriteLine("Client connected at port 3333");
        streamWriter.Flush();
    }
    catch (SocketException ex)
    {
        Console.WriteLine(ex);
    }
    Console.Read();
  }
}

When the above client application code will execute, it will look for an opened connection from a server application at port 3333. As soon as it finds the connection, it will establish the connection with it and will send a message “Client connected at port 3333”. This test message will be displayed on server application console.

A Port is an integer that identifies a process running over a network for the purpose of providing a service. A socket is the end point of a two way communication between two processes running over a network. Microsoft .NET provides excellent support for writing programs that leverage the power of Sockets to implement programs that can run over a network to communicate and share data and information. 

In this entry we tried look at how we can work with Sockets using Microsoft .NET and how we can implement a simple client-server program that can communicate over a network. 

Your comments and suggestions are welcome.

Happy reading!

Waqas Ahmed

Filed under: .Net, Code Snippets, , ,

Integrating jQuery in ASP.NET

Almost all of you have tried ASP.NET AJAX for Ajax related operations. But there are times when you need something more from ASP.NET AJAX, and unfortunately you cannot. These are the times you ask for alternatives.

The available alternatives for AJAX behavior in your application belong to open source community. Some of the open source frameworks for AJAX are

My personal favorite is jQuery. There are many reasons for that. One very important one is related to the UI flexibility provided by jQuery.

So, I have decided to run down a simple example for all of you where we will utilize jQuery in ASP.NET application to fetch the Server Side DateTime. Note that we will be developing this demo application in ASP.NET 1.1, to prove a point that how easy it is to integrate jQuery in already deployed application as compare to ASP.NET AJAX.

Some of the Pre-requisites, you should care about is the one and only jQuery library itself. You can get the library from here jQuery Download [http://jqueryui.com/download]. One great thing you will notice, when you will go to download section; it allows you to select/deselect different features of the framework along with theme selection as well. This feature helps the developer to avoid bulky packages and be functionality centric. You should also bookmark the website, as you will need it later on for different knowledge base articles regarding the framework. Also, the forums and discussion boards are very active and usually you get the response to your questions quite quickly.

Coming to the demo, first we have to include the jQuery library in the default.aspx

<script type=”text/javascript” src=”jquery-1.1.js”>

First we will define the action which will get triggered when user will click on “Get Server Time”

$(function() {
    $(“a#runSample1”).click(function() {
        $.get(“GetServerTime.aspx”, function(response) {
            alert(response);
         });
    });
});

For your reference, let’s take a look at when we just did.

This code will be executed on page onload event.

$(function() {

This  code, we are binding an event with the “onclick” event of the hyperlink. Which user will click?

$(“a#runSample1”).click(function() {

The above code allows us to define that, when user clicks the link “Get Server Time”, the action will get fired and will call a proxy page which we will create later on. That proxy page will return the server time into the response object which we just mentioned in the above code. And it will be displayed in message box.

$.get(“GetServerTime.aspx”, function(response) {
    alert(response);
});

Now proceeding to the proxy page “GetServerTime.aspx”. On this page, we don’t need the HTML. Therefore, we will only keep the top declaration and will remove rest of the HTML

<%@ Page Codebehind=”GetServerTime.aspx.cs” AutoEventWireup=”false” Inherits=”AJAXJQuerySample.GetServerTime” %>

The code behind of the proxy page will be

private void Page_Load(object sender, System.EventArgs e)
{
    Response.Expires = -1;
    //required to keep the page from being cached on the client’s browser
    Response.ContentType = “text/plain”;
    Response.Write(DateTime.Now.ToString());
    Response.End();
}

In the page_load method, Response.Expires = -1, allowes us to make sure that page wont get cached in the browser.

Response.ContentType = “text/plain”;
Response.Write(DateTime.Now.ToString());
Response.End();

The above code just set the content of the response to plain text and writes the current time to the response stream.

This is it. Now, we can run our sample application and click the “Get Server Time” link, this should give us the current time in an alert box:

 

Demo Screenshot

Demo Screenshot

Hope this will be hlpful to get you started. Let me know about it.

Waqas Ahmed

Filed under: ASP.NET, , , ,

Data Access with ADO.NET 3.5 – Extensions

In our last post, we looked into objectives of the ADO.NET 3.5 which get shipped with VS 2008 Service Pack1. To achieve those objectives, we have some very good language extensions for ADO.NET 3.5. in C# and VB.

  • LINQ extension for VB 9.0 and C# 3.0 language provides a set of standard query operators to query many different kind of data sources using SQL like syntax. This extension for VB and C# implements LINQ pattern.
  • LINQ to Object is the default implementation for LINQ. It enables the developer to execute queries against a data persisted in memory that implements IEnumerable or IQueryable interface.
  • LINQ to SQL extension to LINQ to Objects provide an O/RM tool to generate and manage classes for business objects and to persist their instances in SQL Server tables.
  • LinqDataSource server control introduced in ASP.NET 3.5 simplifies the headache to bind data enabled web controls to business objects created with LINQ to SQL.

Later on we will discuss each of the above mentioned extensions individually, to look under the hood of ADO.NET 3.5 and it’s working.

Until than happy reading 🙂

Waqas Ahmed

Filed under: .Net, , , ,

Pages

Categories

Archives

.Net Hive @ Twitter

Blog Directory by Blog Flux
Computers/Tech blogs