Sharing knowledge in Project Portfolio Innovation Management (PPIM) and various Technology.
Wednesday, November 11, 2009
Calling Parent Method from child control using Events & Delegates.
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
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.
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
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.
Wednesday, July 1, 2009
Better Sound in Framework 3.0
String Split for new line in C#
Monday, June 22, 2009
C# 4.0 -Optional Parameters
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)
{
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
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
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
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
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
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
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 StateSession 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!