Showing posts with label C#.NET. Show all posts
Showing posts with label C#.NET. Show all posts

Wednesday, November 11, 2009

Calling Parent Method from child control using Events & Delegates.

Before starting we should very clear about event and delegate

Event: it's handler which will call the delegate and it will call the method.

Delegate: it's a function pointer, it will point to the particular function.

Let me explain about calling parent method from the child control.


Step 1: create one aspx pages and usercontrol pages.


step 2:

In the usercontrol create one button and lable. The scenoria is like this when user click on the button has to call the child method as well as the parent method.

Step 3:

Create one user control with the following code.


Childcontrol.ascx

<asp:Button ID="btnShow" runat="server" />
<asp:Label ID="lblShow" runat="server"></asp:Label>



Childcontrol.ascx.cs

public delegate void callDelegate();
public event callDelegate callEvent;

protected void Page_Load(object sender, EventArgs e)
{
btnShow.Click += delegate
{
lblShow.Text = "Hi how are u";
this.showData();
};
}
protected virtual void showData()
{
if (this.callEvent != null)
{
this.callEvent();
}
}


Step 4:


Create one aspx page with name of Parent with the following code.

parent.aspx


<%@ Register Src="~/UserControl/Childuser.ascx" TagPrefix="child" TagName="UC" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblParent" runat="server"></asp:Label>
<child:UC id="UC1" runat="server"></child:UC>
</div>
</form>
</body>
</html>


parent.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
UC1.callEvent += new Childuser.callDelegate(UC1_callEvent);
}

void UC1_callEvent()
{
lblParent.Text = "Hi Parent";
}












Monday, November 9, 2009

Base Pages using C#.Net

Now i am come with the scenario clearing the session on each page writing the code.
for clearing the session in common place.
we can use some thing called base pages. so that we can keep the code in seprate place.
Step 1:
Create one class file with the name of basepages.cs.
This will contain the one method which will clear the session objects permanently.
Example:
public class BasePages:System.Web.UI.Page

{
public void clearSession()

{ if (Page.User.Identity.IsAuthenticated == false)
{ Session.Abandon();
Response.Redirect("login.aspx");
}
}
}
step 2
Create one login with the extension of .Aspx page.in the code behind just inherit that base class method.
public partial class SessionCheck : Performance.BasePages

{
protected void Page_Load(object sender, EventArgs e)
{
base.clearSession();
}
}








Monday, October 26, 2009

Calling method from one user control from other usercontrol with out using property.

Take this scenorio, i have button and event in the first user control.

and i have label in the other usercontrol.

when i click on the button have to assign some value for label of other usercontrol with

out using the property


Step 1:

create first user control with following control and method.

<asp:Button ID="btnSubmit" onclick="btnSubmit_Click" runat="server" Text="Submit" />

public void btnSubmit_Click(object sender, EventArgs e)
{
test2 t2 = (test2)Page.FindControl("test2");

t2.callBTN(sender, e);

}
step 2:


create second user control with label with assigning value.

<asp:Label ID="lbltest" runat="server"></asp:Label>


public void callBTN(object sender, EventArgs e)
{
lbltest.Text = "DDDD";
}


Monday, July 13, 2009

ExcelDataReader

hi guys, This is one of the best approuch for converting excel in to dataset. I am using this in our project. This exceldatareader will read very faster than any other approach so far.

So that we are using in our project. Its very good approach.. let's download in the below url


http://www.codeplex.com/ExcelDataReader


Then include in your project. Just include in your project as a DLL. Then access all the classes.









Parent Child Display using Asp.net 2.0



I have comeacross some of friends needed this code to create parent and child combination in the webpage.

So thought of sharing them have created sample code for displaying the parent and child combination.

I am using Parent control as a Repeater control and child as a Gridview control.

Please go throgh the example:

Aspx Code:

<asp:Repeater ID="grdMulti" runat="server" OnItemDataBound="grdMulti_RowDataBound">
<ItemTemplate>
<table width="100%" border="1" style="border-style:solid">
<tr>
<td>
<table width="100%">
<tr>
<td>
<img id="imgExpand" runat="server" src="Image/add_up.gif" onclick="javascript:showChild(this)"
style="vertical-align: top" />
<img id="imgCollapse" runat="server" src="Image/del_up.gif" onclick="javascript:showChild(this)"
style="display: none; vertical-align: top" />
</td>
<td>
<asp:Label ID="lblServiceAddress" runat="server" Text='<%# Eval("ServiceId") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ServiceName") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("ServiceAddress") %>'></asp:Label>
</td>
</tr>
</table>
</td>
</tr>
<tr id="ShowRow" runat="server" style="display:none">
<td>
<table width="100%">
<tr>
<td>
<div id="Show" runat="server" style="display: none">
<asp:GridView ID="grdChild" runat="server" Width="100%">
</asp:GridView>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>


Javscript:

<script language="javascript">
function showChild(obj) {
var imgId = obj.id, grdId, grdObj, objImg = document.getElementById(imgId), imgChangeId, imgChangeObj, rowid;
if (obj.id.indexOf('Expand') > 0) {
grdId = obj.id.replace('imgExpand', 'Show');
rowid = obj.id.replace('imgExpand', 'ShowRow');
imgChangeId = obj.id.replace('imgExpand', 'imgCollapse');
imgChangeObj = document.getElementById(imgChangeId);
grdObj = document.getElementById(grdId);
rowobj=document.getElementById(rowid);
if (objImg != null) {
objImg.style.display = 'none'
}
if (grdObj != null) {
grdObj.style.display = 'block'
}
if (imgChangeObj != null) {
imgChangeObj.style.display = 'block';
}
if (rowobj != null) {
rowobj.style.display = 'block';
}
}
else {
grdId = obj.id.replace('imgCollapse', 'Show');
rowid = obj.id.replace('imgExpand', 'ShowRow');
imgChangeId = obj.id.replace('imgCollapse', 'imgExpand');
imgChangeObj = document.getElementById(imgChangeId);
grdObj = document.getElementById(grdId);
rowobj = document.getElementById(rowid);
if (grdObj != null) {
grdObj.style.display = 'none'
}
if (objImg != null) {
objImg.style.display = 'none'
}
if (imgChangeObj != null) {
imgChangeObj.style.display = 'block';
}
if (rowobj != null) {
rowobj.style.display = 'none';
}
}
}
</script>

C#

public partial class MultiGrid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable DTParent = new DataTable();
DataColumn dc1 = new DataColumn("ServiceId");
DataColumn dc2 = new DataColumn("ServiceName");
DataColumn dc3 = new DataColumn("ServiceAddress");

DTParent.Columns.Add(dc1);
DTParent.Columns.Add(dc2);
DTParent.Columns.Add(dc3);
DataRow DR = null;
for (int i = 0; i <>
{
DR = DTParent.NewRow();
DR[0] = i.ToString();
DR[1] = "bal";
DR[2] = "Address";
DTParent.Rows.Add(DR);
}
grdMulti.DataSource = DTParent;
grdMulti.DataBind();
}

}

protected void grdMulti_RowDataBound(object sender, RepeaterItemEventArgs e)
{
GridView GRDChild = (GridView)e.Item.FindControl("grdChild");
if (GRDChild != null)
{
DataTable DTChild = new DataTable();
DataColumn dc1 = new DataColumn("ServiceId");
DataColumn dc2 = new DataColumn("ServiceName");
DataColumn dc3 = new DataColumn("ServiceAddress");

DTChild.Columns.Add(dc1);
DTChild.Columns.Add(dc2);
DTChild.Columns.Add(dc3);
DataRow DR = null;
for (int i = 0; i <>
{
DR = DTChild.NewRow();
DR[0] = i.ToString();
DR[1] = "bal";
DR[2] = "Address";
DTChild.Rows.Add(DR);
}
GRDChild.DataSource = DTChild;
GRDChild.DataBind();
}
}
}







Wednesday, July 1, 2009

Better Sound in Framework 3.0

In previous version we have system.media namespace. it nice to see this in frame work 2.0.

Using this namespace can play wav files. At a time can run only one file in the media player.

But we can't mix multiple files.


But now in frame work 3.0 come with new namespace for running the sound files. The new name space is system.media.SoundPlayer. In this we will run all the media extension like .wav,.mp3..
also simultaneously can run the files.


String Split for new line in C#

Today one of my friend faced problem in sorting. Spliting the new line('\r\n')
in the given text.

This is will be very use full for beginners.

Example:

string[] strSplit=new string[1];
strSplit[0]="\r\n";
string[] strarrayemail = txtEmail.Text.Split(strSplit,StringSplitOptions.RemoveEmptyEntries);
Array.Sort(strarrayemail);
txtEmail.Text =string.Empty;
foreach (string str in strarrayemail)
{
txtEmail.Text += str + "\r\n";
}

Monday, June 22, 2009

C# 4.0 -Optional Parameters

I was really excited, when i have seen upcoming feature in c# 4.0, After come across some article, This feature will be very useful.


Optional Parameters

Let’s say I have a class Employee and I provide few overloads of the constructor to enable making certain parameters as optional as follows:

Older Method

public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Qualification { get; set; }
public string MiddleName { get; set; }

public Employee(string firstName, string lastName)
{
FirstName= firstName;
LastName= lastName;
Qualification= "N/A";
MiddleName= string.Empty;
}
public Employee(string firstName, string lastName, string qualification)
{
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName= string.Empty;

}
public Employee(string firstName, string lastName, string qualification,
string middleName)
{
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName= middleName
}
}

Newer Method

public Employee(string firstName, string lastName,
string qualification = "N/A", string middleName = "")
{
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName = middleName;
}

Tuesday, March 24, 2009

Generating javascript Id through C# (Instead of using control.clientID)

protected void Page_PreRender(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),string.Empty,string.Format("{0}"), string.Format("var gridUniqueID = '{0}'; ", uwgDailyView.UniqueID))
}

Monday, April 7, 2008

Reset all control values in .NET Web pages.

private void ResetFields()
{

foreach (Control ctrl in this.Controls)

{if (ctrl is TextBox)

{

TextBox tb = (TextBox)ctrl;

if (tb != null)

{ tb.Text = string.Empty;

}

} else

if (ctrl is DropDownList)

{ DropDownList dd = (DropDownList)ctrl;

if (dd != null)

{

dd.SelectedIndex = 0;

}

}

}

How to Show Binary Files in the Browser using ASP.NET and VB.NET

This article explains how to show binary files as well as .doc .xls files in browser. We have seen in many sites that user can open .gif, .jpg, .doc and .xls files by clicking a link. The binary format file as well as .doc .xls is displayed in the browser
1)Create an asp.net web project. Name the project as ShowBinary
2) Add a file of type (.gif,.jpg,.doc,.xls) to the project
3) Specify a Start page for the application4) Use following code snippet in the form load event handler

Private Sub Page_Load(sender as object, e as System.EventArgs)
Response.ContentType = “Application/pdf” ‘ Specify Content Type
Dim fpath as string = Mappath(“Mypdf.pdf”) ‘ Specify Physical Path of the file
Response.writefile(fpath)
End Sub

Breaking out a loop in two ways

The two ways described below.
1) firstway is using "break" keyword
2) Second way is using variable declaration.

//First way
for (int i = 0; i < 5; i++)
{
Response.Write("bala");
break;
}
//Second Way
bool br = false;
for (int j = 0; j < 2&& br == false; j++)
{
Response.Write("testingbala");
br = true;
}

Nullable DataType in Dotnet Framework 2.0

Nullable Data Type
If you dont have the value for nullable datatype, it will return automatically null as a value.
Example 1:
int? var1 = null;
int var2 = 5;
var1 = var2;
if (var1.HasValue == true) //Using HasValue properties will will findout "var1" variable having value or null.
{
Response.Write("bala");
}
else
{
Response.Write("bala1");
}
Output:
bala

Example 2:

float? a = 436;
float? b = null;
if (a.HasValue) Response.Write("testing");
if (b.HasValue) Response.Write("testi"); else Response.Write("test");

Output:
testingtest

Sunday, March 16, 2008

verbatim literal

Another useful feature of C# strings is the verbatim literal

which is a string with a @ symbol prefix, as in @"Some string". Verbatim literals make escape sequences translate as normal characters to enhance readability. To appreciate the value of verbatim literals, consider a path statement such as "c:\\topdir\\subdir\\subdir\\myapp.exe". As you can see, the backslashes are escaped, causing the string to be less readable. You can improve the string with a verbatim literal, like this: @"c:\topdir\subdir\subdir\myapp.exe".

Cracking .NET Assemblies

Cracking .NET Assemblies

This is nice articale for cracking the .net assemblies
http://www.grimes.demon.co.uk/workshops/fusionWSCrackThree.htm#Cracking_Whidbey_Assemblies

Monday, February 25, 2008

Encrypt and Decrypt configuration files using Code

How to encrypt connection string in asp.net stored in web.config.
Using System.web.configuration;
Protected void button_click(object sender,eventargs e)
{
string webconfigpath="~";
configuration config=webconfigurationmanager.openwebconfiguration(webconfigpath);
configurationsection configsection=config.Getsection("connectionstrings");
configsection.sectionInformation.protectsection("Dataprotectionconfigurationprovider");
config.save();
}

How to decrypt connection string in asp.net stored in web.config.
Using System.web.configuration;
Protected void button_click(object sender,eventargs e)
{
string webconfigpath="~";
configuration config=webconfigurationmanager.openwebconfiguration(webconfigpath);
configurationsection configsection=config.Getsection("connectionstrings");
configsection.sectionInformation.Unprotectsection();
config.save();
}

Tuesday, February 19, 2008

What's new in C# 3.0

1)Implicit typed local variables
Local variables can be declared as type var, whose actual type of the variable is determined by the compiler based on the data schema (see Listing 1). It's mainly used to store anonymous types in LINQ.

// This is an integer
var nId = 1234567;
//This is a string
var strFullname = "John Charles Olamendy Turruellas";

Wednesday, February 13, 2008

How to use DbProviderFactory and DbConnection

Refer this

http://www.developer.com/net/net/print.php/11087_3530396_2

Example

DbProviderFactory Factory = DbProviderFactories.GetFactory("DDTek.Oracle");DbConnection Conn1 = Factory.CreateConnection();

Conn1.ConnectionString ="Host=Accounting;Port=1521;User ID=scott;Password=tiger; " + "Service Name=ORCL;Min Pool Size=50";

Conn1.Open();// Pool A is created and filled with connections to the //

minimum pool size

DbConnection Conn2 = Factory.CreateConnection();

Conn2.ConnectionString = "Host=Accounting;Port=1521;User ID=Jack;Password=quake; " + "Service Name=ORCL;Min Pool Size=100";

Conn2.Open();// Pool B is created because the connections strings differDbConnection Conn3 = Factory.CreateConnection();

Conn3.ConnectionString = "Host=Accounting;Port=1521;User ID=scott;Password=tiger; " + "Service Name=ORCL;Min Pool Size=50";Conn3.Open();//

Conn3 is assigned an existing connection that was created in // Pool A when the pool was created for Conn1

Friday, February 8, 2008

Statemanagement Using C#.Net

State Management is a process of maintaining the state of the control or variable after page postback from server or between pages. In Asp.Net we are having many ways to maintain the state management. Basically it is dividied into server side and client side state management. Depends on the resource that we have to plan. They are as follows....

1. Session state

2. Hidden Variables

3. Query String

4. Cookies

5. ViewState

6. Caching

Out of which session state and caching are server side state management. others are client side state management.

1. Session State

Session State is responsible for maintaining the state of a variable between pages and page postback. There are two types of session state. They are
a. Application state
b. Session state
An object that is instant in application state will be available to the entire application. The lifetime of that instance will be available as long as application exists. Synatax for it is

Application.lock();
Application["Name"] = "Senthil";
Application.unlock();
string strName = Application["Name"].ToString();

and an instance created in session state will be available for that session (i.e browser).


Session["RoleID"] = "ADMIN";
string strRole = Session["RoleID"].ToString();

Session state can stored in three places
a. InProc - same system
b. StateServer - storing values in other server. Use " net start aspnet_state" for configuring the state server.
c. SQLServer - In database - use "aspnet_regsql" for configuring the sql server.


This can be set in web.config

<configuration> <system.web> <sessionstate mode="InProc" stateserver="129.23.33.53" sqlserver="" cookieless="true" /> </system.web></configuration>


To get more info about state management, set the trace to on

<configuration> <system.web> <trace enable="true" pageoutput="true" />
</system.web>


If pageoutput is set to false, then we find the contents in trace.axd file which is available in the root folder.

2. Hidden variables

Hidden controls are for storing few informations and retrieving it when page gets submits. We cannot get one hidden value in another page. The syntax for hidden variables are as follows.

<input type="hidden" name="hid" value="">
<%=Request.Form("hid")%>

3. QueryString

Easiest way to transfer data between pages is the querystring. But we cannot transfer a bulk of data through it. Basically querystring has two keywords ? and &.


Example

document.frm.action="login.aspx?Name=" & strName & "?Role=ADMIN"
<%= Request.QueryString["Name"] %>

4. Cookies

Cookies are client side and it is used to store few values in the client machine. We cannot create cookies in server side. Many browsers restrict using cookies in the websites. The class that supports cookies in dotnet are HttpCookies.

5. ViewState

ViewState are used to maintain the state of the control. It can be set page wise or control wise. To set it by page wise


<% @ Page EnableviewState="True" %>


For setting viewstate control wise set the viewstate property to true.

The value of the control would be retained once the pages get postback.

6. Caching

Caching too places a part in state management. Its similar to session state but the only difference is we have to set the duration for it.
Caching can be done by page levels or application levels.

Syntax for page level caching[CODE]

<% outputcache duration="10" valuebyParam="none" />[CODE]

Thursday, February 7, 2008

Displaying images in URL

Create a image which you want to display on the url.


Go to favicon.comThere you have a browse option.Select the image from your local machine

using the browse optionClick submitIt will create a small icon and it will display on the page.

Right click and save as "favicon.ico"

Give the exact file name as favicon.ico.Normally it opens in paint.


Now paste that image in your website root directory and on your masterpagewithin <head></head> tags copy and paste the below given link tag:

<link rel="shortcut icon" href="favicon.ico" />

Thats it! You can view it on the url!