Tuesday, December 21, 2010
Tuesday, December 14, 2010
How to find if the assembly is strongly named
Approach #1: Testing for Strong Name on Command Line or in a Script
Approach #2: Viewing Strong Name Details with IL DASM
Approach #3: Viewing Strong Name Details with Reflector
for details refer
http://blog.codingoutloud.com/2010/03/13/three-ways-to-tell-whether-an-assembly-dl-is-strong-named/
Saturday, November 20, 2010
Jquery Tabs
Property
Default Value
Usage
ajaxOptions
{}
Options for remote AJAX tabs
cache
"false"
Load remote tab content only once (lazy-load)
cookie
null
Show active tab using cookie data on page load
disabled
[]
Disable specified tabs on pageload
idPrefix
"ui-tabs-"
Used when a remote tab's link element has no title attribute
event
"click"
Tabs event that triggers display of content
fx
null
Specify a transition effect when changing tabs
panelTemplate
A string specifying the elements used for the content section of a dynamically created tab
selected
0
The tab selected by default when the widget renders
spinner
"LoadingB230"
Specify the loading spinner for remote tabs
tabTemplate
A string specifying the elements used when creating new tabs dynamically
unselect
false
Hides an already selected tab when it is clicked
Property
Default Value
disabledCLass
"ui-tabs-disabled"
hideClass
"ui-tabs-hide"
loadingClass
"ui-tabs-loading"
navClass
"ui-tabs-nav"
panelClass
"ui-tabs-panel"
selectedClass
"ui-tabs-selected"
unselectClass
"ui-tabs-unselect
E.X.
If you want nothing should be selected on load
$(document).ready(function () {
var tabOpts = {
selected:null
};
$("#tabs").tabs(tabOpts);
});
else type 0,1,2 are index starts with 0
If you wanna disable TAB$(document).ready(function () {
var tabOpts = {
disables:[0]
};
$("#tabs").tabs(tabOpts);
});
disable first tab , change [0] to disable other or for mutliple [0,1] etc.
Transition Effects
$(document).ready(function () {
var tabOpts = {
fx: {
opacity:"toggle", duration:"slow" }
};
$("#tabs").tabs(tabOpts);
});
duration could be slow, normal, or fast
To only show the animation once, when a tab closes for example, we would need to nest the fx object within an array
$(function(){
//define config object
var tabOpts = {
fx: [{
opacity: "toggle",
duration: "slow"
},
null]
};
//create the tabs
$("#myTabs").tabs(tabOpts);
});
/script>
executable functions on an event
Property
Usage
add
Execute a function when a new tab is added
disable
Execute a function when a tab is disabled
enable
Execute a function when a tab is enabled
load
Execute a function when a tab's remote data has loaded
remove
Execute a function when a tab is removed
select
Execute a function when a tab is selected
show
Execute a function when the content section of a tab is shown
tab's custom binding events and their triggers
Event
Trigger
tabsselect
A tab is selected
tabsload
A remote tab has loaded
tabsshow
A tab is shown
tabsadd
A tab has been added to the interface
tabsremove
A tab has been removed from the interface
tabsdisable
A tab has been disabled
tabsenable
A tab has been enabled
Functions
$(function(){
//alert the id of the tab that was selected
function handleSelect(event, tab) {
alert("The tab at index " + tab.index + " was
selected");
}
//define config object
var tabOpts = {
select:handleSelect
};
//create the tabs
$("#myTabs").tabs(tabOpts);
});
Friday, November 19, 2010
Using Jquery in Master Pages
1) try google CDN's
link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/sunny/jquery-ui.css" rel="stylesheet" type="text/css"/>
script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript">/script>
script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript">/script>
2) Put stepone in the head section of the Master page before Head Content Placeholder
head runat="server">
title>/title>
link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/sunny/jquery-ui.css" rel="stylesheet" type="text/css"/>
link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
/head>
Tuesday, October 26, 2010
Wednesday, October 20, 2010
Request.PathInfo
Thursday, October 7, 2010
User doesnot hace permission to do this action
1) Give permission for the ASPNET to perform this action
2) or make your application run under another account than ASPNET.
Read about (1) and let me know too.
But for the second option use the impersonate setting account in the web config file that would resolve this issue. This would tell the ASPNET that use specified crenditials to update information.
identity impersonate="true" userName="xx" password="xx"/
I would also recommend following article with it.
http://support.microsoft.com/default.aspx?scid=kb;en-us;329290
Tuesday, September 28, 2010
There is a duplicate ‘system.web.extensions/scripting/scriptResourceHandler’ section defined
1) You might changed “sharepoint – 80” application pool’s .net framework version 2 to 4
2) You might have the web.config file in your site or sub site it contains the duplicate section of scriptresourceHandler, You should retain this section only on root web.config file.
Friday, September 24, 2010
Microsoft.Web.GeneratedImage.dll
This article looks at using the GeneratedImage control. Specifically, we'll see how to generate dynamic images on the fly based on a variety of inputs.
Thursday, September 23, 2010
Dueling Assembly References
follow below article
http://weblogs.asp.net/scottgu/archive/2006/07/30/Common-Gotcha_3A00_-Slow-VS-2005-Web-Site-Build-Performance-Because-of-_1C20_Dueling-Assembly-References_1D20_.aspx
VS Project Models
VS 2005 Web Site Projects and VS 2005 Web Application Projects
1)
-->provide a project-less based model for doing web development that uses that same dynamic compilation system that ASP.NET 2.0 uses at runtime
--> while a lot of web developers love the VS 2005 Web Site model because of its "just hit save" dynamic model and flexibility.
--> no namespace is generated
2)
-->project model that uses a MSBuild based build system that compiles all code in a project into a single assembly
-->a lot of enterprise developers love the VS 2005 Web Application option because it provides a lot more build control and team integration support
--> namespace is generated automatically
Saturday, September 18, 2010
To create a virtual directory in IIS 7.0 or 7.5
2) In the left pane, expand the node with the computer's name, and then expand the Sites node.
3) Right-click Default Web Site, and then select Add Application to open the Add Application window.
4) In the window, type servicemodelsamples as the alias for the virtual directory that you are creating.
5) Create the following directory: %SystemDrive%\inetpub\wwwroot\servicemodelsamples
6) Set the physical path to %SystemDrive%\inetpub\wwwroot\servicemodelsamples.
Click OK. The Web application is now created.
To set additional virtual directory properties in IIS 7.0 or 7.5
7) Click the servicemodelsamples node. Along the bottom of the window, two views are listed. Select Features View if it isn’t already selected.
8) Double-click the entry for Directory Browsing.
9) In the Actions pane, select the Enable option. This enables you to access the directory of the directory by using Internet Explorer, which helps when debugging a service.
10) Finally, you must set the security properties of the servicemodelsamples folder to allow it to be accessed by others. See below for details.
To set security properties of the folder in IIS 7.0 or 7.5
11) Navigate to %SystemDrive%\inetpub\wwwroot\servicemodelsamples.
12) Right-click the servicemodelsamples folder and click Share or Share With.
13) Click the down arrow to the left of the Add button.
14) Select the Find entry. The Select Users or Groups window opens.
15) Click Advanced.
16) Click Locations. The Locations window is now open.
17) Select the entry for the computer being used. It is important to select the local computer and not an entry for any domains or networks that are listed. After you have selected the computer, click OK.
18) Click Find Now. This populates the search results with objects associated with the local computer.
19) Find the IIS_IUSRS entry in the Name (Relative Distinguished Name) column. Select that entry and click OK to close the search results window.
20) Click OK to close the Select Users or Groups window.
21) Click Share to persist the changes.
22) After the changes to enable sharing are complete, click Done to close the File Sharing window.
Monday, September 13, 2010
How To Keep ASP.NET Session Alive
Although it is possible to increase session timeout (see ASP.NET session timeout and expiration tutorial), this is not scalable option. every session variable requires some memory on server. If website has many visitors and a lot of session variables, increasing of timeout too much could spend all available memory and decrease website performances. If session timeout is increased, server will keep all sessions, including unimportant sessions from visitors who leaved website. As better solution, you can make periodical requests from client side, which will keep session alive only if browser is still showing your page. In that purpose, we can use JavaScript, jQuery, Meta Refresh or ASP.NET Ajax
How to keep ASP.NET session alive using JavaScript
ASP.NET just remembers time of last request and it doesn't know if visitor is closed browser window or is just doing something else and will return soon. It is certainly worthless to keep session values of user who leaved website. It would be better if we could keep live sessions of visitors who still have page opened.
Solution for this is to use JavaScript that will make periodic calls to some .aspx page on website, restart session timeout and keep session alive in that way. Implementation code will use JavaScript setInterval function. It could look like this:
<%--
In this example, image will be used to keep session alive,
By changing image's src parameter, we'll make periodical requests
to web server.
--%>
In this example, RefreshSessionState.aspx page will be called every minute. This is far less than default session timeout which is 20 minutes. If you just want to keep session alive, you can set this time for 19 minutes (19 * 60 * 1000 = 1140000).
But, with smaller intervals you could know almost instantly when visitor is closed a browser. If scalability is a problem, you can delete session variables almost immediately after user closed web browser. There is no need to wait 20 minutes for session to expire. You can even decrease session timeout to low value, like 2 minutes. JavaScript from previous example will make requests every minute, and keep sessions alive for active users (users that have opened web browser), but sessions where browser is closed will expire.
Since RefreshSessionState.aspx page is called every minute, you can use ASP.NET server side code for tasks like visitor tracking, how many visitors are currently online, which page each visitor is currently browsing etc.
This option will work fine, although it has its own small drawbacks. Some users could have JavaScript disabled or have a browser that doesn't support JavaScript (like some mobile web browsers). If JavaScript is not enabled, this code would not work and session will expire. Also, rarely but theoretically possible, especially on mobile browsers is, if user's Internet connection is temporally broken JavaScript will miss few requests while user is reconnecting.
This example manipulates image's src element to make request to web server. There is a second option to make web requests in JavaScript using Http Request, but this option requires browser specific code because Internet Explorer and Firefox use different objects. IE uses ActiveX object Msxml2.XMLHTTP or Microsoft.XMLHTTP, while Firefox uses XMLHttpRequest. So, final browser compatible code becomes large. In the other hand, using image's src property to make request requires
As very similar alternative we can use jQuery for same task. In this example, I will use jQuery post function to make a request to web server. Pages requested with POST are not cached, so we don't need unique URL like in previous JavaScript example.
Code for keeping ASP.NET session alive using jQuery is very short:
Keep ASP.NET session alive using Meta Refresh
One more way to keep ASP.NET session alive is by using Meta Refresh and postback. Of course, we can't refresh complete page because that will annoy visitor, especially if he or she is completing a large form. Instead of that, place small IFRAME tag somewhere on page, and set its src parameter to helper .aspx page. Let's call that page RefreshSessionState.aspx.
HTML code on main page will be:
Code for RefreshSessionState.aspx doesn't require complicated server side code except you want some visitor tracking. Just add meta refresh tag in head section. There are few different methods, I used Response.Write:
<%@ Page Language="C#" %>
<%
Response.Write(@" Server.UrlEncode(DateTime.Now.ToString()) + @""" />");
%>
I added additional query string "x", to avoid using of cache in some browsers. Query string value will be current time, so URL will always be unique to provide complete postback.
Now, first value in content parameter represents after how much seconds will page refresh. In this example, page will refresh after 900 seconds (15 minutes). It could be any value less than session timeout. Since default session timeout is 20 minutes, this IFRAME will keep session alive while user is working something else.
Keep ASP.NET session alive using ASP.NET Ajax
To keep ASP.NET session alive, one more option is to use ASP.NET Ajax. Timer control is useful in this scenario, since it can send requests in regular time intervals. To see how it works, add to web form one UpdatePanel control and one Timer control. Here is an example markup code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ajax-Refresh.aspx.cs" Inherits="Ajax_Refresh" %>
Interval property of Timer1 is set to 10000, which is about 10 seconds. You can change this interval according to your needs.
On server side, we'll use Timer_Tick to keep session alive:
[ C# ]
using System;
public partial class Ajax_Refresh : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Set session timeout to small value, in this case
// 2 minutes, to see quickly if Timer will keep session alive
Session.Timeout = 2;
// Set some value in session
Session["Testing"] = "session is alive";
}
// Timer will make request to server in regular time intervals
protected void Timer1_Tick(object sender, EventArgs e)
{
// Write current session value into label
Label1.Text = (string)Session["Testing"];
Label1.Text += "
Last request at " + DateTime.Now.ToString();
}
}
[ VB.NET ]
Partial Class Ajax_Refresh
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Set session timeout to small value, in this case
' 2 minutes, to see quickly if Timer will keep session alive
Session.Timeout = 2
' Set some value in session
Session("Testing") = "session is alive"
End Sub
' Timer will make request to server in regular time intervals
Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
' Write current session value into label
Label1.Text = Session("Testing")
Label1.Text &= "
Last postback at " & DateTime.Now.ToString()
End Sub
End Class
Comparation of JavaScript, jQuery, Meta Refresh and ASP.NET Ajax methods
Notice that any of suggested methods (JavaScript, jQuery, Meta Refresh, ASP.NET Ajax) works only if user keeps web browser opened. If browser window is closed, session will normally expire after 20 minutes. If Session timeout is increased, ASP.NET will keep all sessions including useless sessions of visitors who leaved website. If website has high traffic, keeping of thousands of sessions could easily spend server's resources.
Refresh methods like these are more scalable than increasing of session timeout. They will keep only wanted sessions, where visitor is not closed a browser and discard others. Of course, you are not obligated to keep sessions on all website pages. Keeping sessions alive could be security problem, because there is an option that user is just forgot to close browser. In this case, it is better if session normally expire than if someone else comes to computer and gets access. You can limit this approach on just few pages where visitor needs more time to complete task.
Jquery with master pages
1)Link the below lines before the master cpntent in the master file. If its not working with the normal way
OLD:
NEW way point jquery to Web files:
2) Try goto content page. Try to make the custome .js file the same name as page e.g.
Default.aspx will have Default.js. This would help in the future.
and write the custom code in the Default .js file.
3)If you are using the User Controls in the Content pages even then you will follow the step 2:
Friday, August 27, 2010
Get Date From DateTime In SQL
Something I need to do from time to time is get just the date part of a datetime value in SQL. I found a cool way to do it on SQLJunkies today.
select convert(varchar,DateColumn,101)
The 101 means “mm/dd/yyyy” format, but there are a bunch of other codes you can use. 108 will return just the time “hh:mm:ss” for instance.
Update: 101 includes 4 digit year 'yyyy'. A code of 1 would apparently be "mm/dd/yy", according to user comments.
Tuesday, August 17, 2010
passing array to stored procedure
This article explains a simple method for passing an array from your C# ASP .NET application to an SQL stored procedure by using a bit of dyanmic SQL.
MSSQL Limitations and Arrays
MSSQL is a favorite database platform for C# ASP .NET developers. For the most part, MSSQL has everything you need for your application. However, one particular missing feature is support for arrays as inputs to stored procedures. At first glance, one may think passing in a series of input parameters, with a pre-defined limit (such as var1, var, var3, var4) would be a suitable workaround. However, there is an easier way to accept an array of parameters.
Simple Method to Pass Array to a Stored Procedure - SQL Server Side
Consider the following simple method for defining the stored procedure using dynamic SQL. The array parameter is defined simply as a string and the input will be expected to be comma-delimited. By forming the sql dyanmically with the input string, we can query against the values in the array by using the IN command.
CREATE PROCEDURE [dbo].[GetData]
@MyCodes as varchar(500) = '', -- comma delimited list of codes, -: '''ABC'', ''DEF'', ''GHI'''
AS
BEGIN
DECLARE @query as nvarchar(500)
set @query = 'SELECT * FROM DATA WHERE Code IN (@p_MyCodes)'
exec SP_EXECUTESQL @query,
N'@p_MyCodes varchar(500)',
@p_MyCodes = @MyCodes
END
OR
ALTER PROCEDURE [dbo].[sessions_GetSchedule]
-- Add the parameters for the stored procedure here
@confGuid varchar(500),
@sIDlist varchar(500)
AS
BEGIN
DECLARE @SQL varchar(500)
SET NOCOUNT ON;
SET @SQL = 'SELECT sID, sName, sDate, sEndDate, sTime, sEndTime FROM sessions WHERE confguid='+@confGuid+' and sID in ('+@sIDlist+')'
EXEC(@SQL)
And towards your input side
=========test page to pass values as query sreing============================
Response.Redirect("NewSchedule.aspx?CART=" +TextBox1.Text + ";" +TextBox2.Text+"&confGuid="+DropDownList1.SelectedValue);
pass as query string
====page where schedular is displayed===========AAA001;AAA002;==================
IMPORTANT
if (Request.QueryString["Cart"] != "")
{
string confGuid = Request.QueryString["confGuid"];
string sID = Request.QueryString["CART"];
string NewsID = sID.Replace(";", "','");
string FinalsID = "'"+NewsID+"'";
string FinalConfGuid= "'" + confGuid+ "'";
Label1.Text = FinalsID;
ScheduleGeneral1.DataSource = BAL.BAL.GetSession(FinalsID,FinalConfGuid);
ScheduleGeneral1.DataBind();
}
-===============BAL================='''AAA001'',''AAA002'''======
public static DataSet GetSession(string spInput,string confGuid)
{
DataSet ds = DAL.DAL.DataSetDAL1("sessions_GetSchedule", spInput,confGuid);
return ds;
}
========================DAL==============================
public static DataSet DataSetDAL1(string spName, string spInput,string congGuid)
{
DataSet _Ds = new DataSet();
try
{
SqlConnection con = GetConnection();
SqlCommand cmd = new SqlCommand("sessions_GetSchedule", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("@sIDlist", SqlDbType.VarChar));
cmd.Parameters["@sIDlist"].Value = spInput;
cmd.Parameters.Add(new SqlParameter("@confGuid", SqlDbType.VarChar));
cmd.Parameters["@confGuid"].Value = congGuid;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
da.Fill(_Ds);
con.Close();
if (_Ds.Tables[0].Rows.Count > 0)
{
return _Ds;
}
}
catch (Exception e)
{
e.Message.ToString(); ;
}
int count = 0;
//foreach (DataRow dr in _Ds.Tables[0].Rows)
if (_Ds.Tables[0].Rows.Count>0)
{
count = count + 1;
}
return _Ds;
}
Sunday, August 8, 2010
Jquery preventDefault
event.preventDefault();
Create Scheduler in Asp.net.C# or Databound Schedule controls
In order to display a schedular in asp.net, there is a third party tool avaliable.
Please go through this article to get details:
http://www.codeproject.com/KB/custom-controls/schedule.aspx
And Inorder to schedule an email through .net follow:
http://www.codeproject.com/KB/aspnet/Schedule_Task.aspx
sp for the scheduler
ALTER PROCEDURE [dbo].[sessions_NonTicketedScheduleDAY]
-- Add the parameters for the stored procedure here
@confGuid varchar(500),
@sDay varchar(500)
AS
BEGIN
DECLARE @SQL varchar(1000)
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--SET @SQL = 'SELECT sID, sName, sDate, sEndDate,sTime,sEndTime FROM sessions_NonTicketed WHERE confguid='+@confGuid+' and sdate between ('+@startDate+') and ('+@endDate+') '
SET @SQL = 'SELECT sID, sName, sDate, sEndDate,sTime,sEndTime,Category FROM sessions_NonTicketed WHERE confguid='+@confGuid+' and
Day(sdate)='+@sDay+''
--'SELECT sID, sName, sDate, sEndDate,sTime,sEndTime FROM sessions_NonTicketed WHERE confguid='+@confGuid+' and sdate >="'+convert(varchar(23),@startDate)+'"AND shippeddate <="'+convert(varchar(23),@endDate)+'"'
--'select * from orders where requireddate >="'+convert(varchar(23),@reqdate)+'" AND shippeddate >="'+convert(varchar(23),@shipdate)+'"'
EXEC(@SQL)
END
Also In case you wanna color codeing as per type its possible within this scheduler
Referencing an Assembly from Global Assembly Cache
http://www.kivela.be/index.php/2007/12/11/strong-signing-a-third-party-assembly-in-net/
After the strong name is assigned for any dll. If you try to reference any DLL at that point its reference is checked from GAC as per strong name or publick key token. If the strong name is matched with the SN for the DLL you are referenceing then you don't see the assemble in the bin of your project directory. else the DLL will be added to you BIN directory.
To add a reference
•In Solution Explorer, expand the project node to which a reference is to be added.
•Right-click the References node for the project and select Add Reference from the shortcut menu.
•To add a reference to a component or components, do the following:
•In the Add Reference dialog box, select the tab indicating the type of component to be referenced.
•In the top pane, select the component to be referenced, and then click the Select button.
Tip If the component you are looking for is not in the list, you may locate it using the Browse button.
The component referenced appears in the SelectedComponents pane of the dialog box.
•Repeat Step b for each additional component added.
•Click OK when references are all added.
To add assemblies to the Add References dialog box
•In Windows, click the Start button, click Run, then type regedit, to open the Registry Editor.
•Select the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.0\AssemblyFolders
•On the Edit menu, point to New, then, click Key.
•Enter a name for the key (for example, MyAssemblies).
•Select the (Default) value for the key that you just added.
•On the Edit menu, choose Modify.
•In the Edit String dialog box, select the Value data field and enter the full path to the folder where your assemblies are located.
To remove a reference
•In Solution Explorer, right-click the reference in the References node, and select Remove from the shortcut menu.
•By default, the Add References dialog box only lists assemblies that are in the Public Assemblies folder (Program Files\Microsoft Visual Studio .NET\Common7\IDE\Public Assemblies) or in the Global Assembly cache. You can add your own assemblies to the list by adding a registry key to specify their location
Strong signing a third party assembly in .net.?
E.g.
Lets say the name of the third party DLL is myTest.dll.
Step 1: Dis-assemble the assembly, as we have to asign the strong name for DLL
ildasm myTest.dll /out:myTest.il
Create a Strong Name:
sn -k myTest.snk
Step 2: Re-Assemble using your strong-name key
ilasm myTest.il /res:myTest.res /dll /key:myTest.snk /out:myTestSN.dll
for verification you can use following command,
sn -vf myTestSN.dll
Thursday, July 29, 2010
Guid to String and viceversa
Label2.Text= TypeDescriptor.GetConverter(myGuid).ConvertFrom(myGuidString).ToString();
Tuesday, July 27, 2010
Choosing Controls based on Insert ,Update ,Delete
If you want to update or delete data (but not necessarily insert new records), choose GridView, DetailsView, or FormView. Although DataList is capable of providing UI for editing, it does not take advantage of the data source’s ability to do this automatically like GridView, and you’ll need to write custom code to make it work. Refer to an ASP.NET v1 reference for more information (the topic is outside the scope of this book).
If you only want to display read-only values, you can use any of the templated controls .
Choosing a control based on formatting and layout of the data records:
If you want to display multiple data records at the same time, choose between GridView, DataList, and Repeater:
GridView: Displays each data record as a row in a table. Fields of the data record are displayed in the table cells (one field per cell, or using a template, as many fields per cells as you need). The contents of each cell are defined by the TemplateField.ItemTemplate property.
DataList: Displays each data record as a cell in a table. The number of data records per row in the table is determined by the DataList’s RepeatColumns property. The ItemTemplate property allows you to define the template rendering of each data record within the table cell.
Repeater: Displays each data record as a user-defined item, defined by the Repeater’s ItemTemplate property. There is no built-in table for layout, so the items simply flow from one to the next (within a tag, so styles are applied).
If you want to display one record at a time, choose between DetailsView and FormView:
DetailsView: Displays each data record as a table of two columns, where each row typically contains a single field (the left cell is the header and the right cell the value). Using TemplateField, you can define the contents of each value cell using the TemplateField.ItemTemplate property.
FormView: Displays each data record as a single cell in a table with one row. The contents of the table cell are defined by the FormView’s ItemTemplate property.
=================================
GridView
DataList
Repeater
DetailsView
Form View
From version 1.x?
No
Yes
Yes
No
No
Number of records shown at once
Multiple
Multiple
Multiple
Single
Single
Can update records?
Yes
No[*]
No
Yes
Yes
Can delete records?
Yes
No[*]
No
Yes
Yes
Can insert records?
No
No
No
Yes
Yes
Can select records?
Yes
No[*]
No
Yes[**]
Yes[**]
Supports paging?
Yes
No
No
Yes
Yes
Renders data record as...
Row in multicolumn table
Cell in multirow/column table
Item in a (no table)
Single table of two columns
Single cell in a one-row table
Templates are optional?
Yes
No
No
Yes
No
Supports header/footer
Yes
Yes
Yes
Yes
Yes
Template Properties
EmptyDataTemplate
PagerTemplate
TemplateField
AlternatingItemTemplate
EditItemTemplate
FooterTemplate
HeaderTemplate
ItemTemplate
GridView repeats Template Field.ItemTemplate once per row for each record in the data source.
--------------------------------------------------------------------
DetailsView
EmptyDataTemplate
PagerTemplate
HeaderTemplate
FooterTemplate
TemplateField
Alternating-ItemTemplate
EditItemTemplate
FooterTemplate
HeaderTemplate
InsertItemTemplate
ItemTemplate
DetailsView renders TemplateField.ItemTemplate for field’s data cell the current record in the data source.
--------------------------------------------------------------------
FormView
EmptyDataTemplate
PagerTemplate
HeaderTemplate
FooterTemplate
ItemTemplate
EditItemTemplate
InsertItemTemplate
FormView renders the ItemTemplate for the current record in the data source.
--------------------------------------------------------------------
DataList
HeaderTemplate
FooterTemplate
AlternatingItemTemplate
ItemTemplate
EditItemTemplate
SelectedItemTemplate
SeparatorTemplate
DataList repeats the ItemTemplate once for each record in the data source
----------------------------------------------------
Repeater
HeaderTemplate
FooterTemplate
AlternatingItemTemplate
ItemTemplate
SeparatorTemplate
Repeater repeats the ItemTemplate once for each record in the data source.
Monday, July 26, 2010
Master Details Gridview
Friday, July 23, 2010
Gridview RowCOmmand
{}
e.commandname =will give you the name of the which command name button is clicked. for e.g.
In Gridview colums we have
asp:ButtonField CommandName="Buy" Text="Buy"
asp:ButtonField CommandName="Sell" Text="Sell"
if (e.CommandName == "Buy")
{
Response.Write("You Bought: " + GridView1.DataKeys[rowIndex].Value);
}
else if (e.CommandName == "Sell")
{
Response.Write("You Sold: " + GridView1.DataKeys[rowIndex].Value);
}
e.CommandArgument:which will be the index of the clicked row within the record set.
DataFormatString for Gridview
C Currency with currency sign {0:C2} $3.14 Note rounding
E Exponential {0:E4} 3.1416E+000
F Fixed {0:F3} 3.142 Note rounding
G General {0:G3} 3.14
Same as currency but without symbol
P Percent {0:P0} %314
(Value must be 0.0314 to get %3.14)
dates and times
d (Lowercase d) Short date pattern {0:d} 1/13/2006
D (Uppercase D) Long date pattern {0:D} Friday, January 13, 2006
t (Lowercase t) Short time pattern {0:t} 2:23 PM
T (Uppercase T) Long time pattern and date {0:T} 2:23:45 PM
F (Uppercase F) Short time pattern and date {0:F} Friday, January 13, 2006 2:23:45 PM
m or M (Either case) Month and day pattern {0:m} January 13
y or Y (Either case) Year and month pattern {0:y} January 2006
To add text you as Literral String you must off HtmlEncode
DataFormatString="My prefix {0:x} My suffix"
Saturday, July 17, 2010
Get Names from Enum into Dropdownn list
public enum ProjectStatuses
{
NotStarted, InProgress, Completed
};
ddlPaymentStatus.DataSource = Enum.GetNames(typeof(ProjectStatuses));
ddlPaymentStatus.DataTextField = "Key";
ddlPaymentStatus.DataValueField = "Value";
ddlPaymentStatus.DataBind();
ProjectStatuses=Name of the Enum
ddlPaymentStatus=Name of Dropdown list
Also we can make a generic function for binding
//function to bind the dropdown list with enumeration
public static Hashtable BindToEnum(Type enumType)
{
//get the names from the enumeration
string[] names = Enum.GetNames(enumType);
//get the values from the enumeration
Array values = Enum.GetValues(enumType);
//turn this into hashtable
Hashtable ht = new Hashtable();
for (int i = 0; i < names.Length; i++)
{
ht.Add(names[i], values.GetValue(i));
}
return ht;
}
Thursday, July 8, 2010
Problem Steps Recorder
Note that they’re still in beta, and this feature is not complete. For example, it won’t record typed text, which means it is TOTALLY USELESS for command prompts or PowerShell commands or even outputs, but if properly guided, the user can add his own comments for any screenshot.
http://technet.microsoft.com/en-us/windows/dd320286.aspx
Metadata feature of .net 4.0
Suppose you need to get the state from the URL then you do :
string stateid=Page.RouteData.Values["state"] as string;
new state id should be in stateid.
Now add the metadata
Page.MetaDescription="A List of states in "+stateid;
Also we can set keywords with Page.MetaKeywards
And this would include the meatdata in the View Source section dynamically.
Thursday, July 1, 2010
How to Backup Your Internet Explorer 8 Favorites
•Step 2
Scrolls down to "Toolbars" and verify that "Menu Bar" has a check mark. If not, simple click on "Menu Bar."
•Step 3
You will now see the menu bar right on the upper left hand side. Click on "File" and scroll down to "Import and Export."
•Step 4
Select "Export to a file" and hit next. Select "Favorites" and then hit next.
•Step 5
You will see that "Favorites" is now highlight. Double click on "Favorites" so the everything below "Favorites" collapses into the "Favorites" folder and hit next.
•Step 6
You will see that the file name is called "bookmark.htm" and the file location will be "My Documents." Click Export and then finish.
•Step 7
Copy the file "bookmark.htm" to an external Hard Drive or USB/Flash drive.
Wednesday, June 30, 2010
Jquery Syntax
Demonstrates the jQuery hide() function, hiding the current HTML element.
$("#test").hide()
Demonstrates the jQuery hide() function, hiding the element with id="test".
$("p").hide()
Demonstrates the jQuery hide() function, hiding all
elements.
$(".test").hide()
Demonstrates the jQuery hide() function, hiding all elements with class="test".
$("p.test").hide()
hides all paragraphs with class="test
$("p#demo").hide()
hides the first
element with id="demo
jQuery uses a combination of XPath and CSS selector syntax.
$(document).ready(function(){
--- jQuery functions go here ----
});
This is to prevent any jQuery code from running before the document is fully loaded (is ready).
jQuery Attribute Selectors
jQuery uses XPath expressions to select elements with given attributes.
$("[href]") select all elements with an href attribute.
$("[href='#']") select all elements with an href value equal to "#".
$("[href!='#']") select all elements with an href attribute NOT equal to "#".
$("[href$='.jpg']") select all elements with an href attribute that ends with ".jpg".
$("ul li:first") The first
$("[href$='.jpg']") All elements with an href attribute that ends with ".jpg"
$("div#intro .head") All elements with class="head" inside a
Jquery
jQuery library contains the following features:
HTML element selections
HTML element manipulation
CSS manipulation
HTML event functions
JavaScript Effects and animations
HTML DOM traversal and modification
AJAX
Utilities
If you don't wanna store jquery in Project then you can ref it through Microsoft or Google
Google CDN
Microfost CDN
Tuesday, June 29, 2010
Template
After created a project or template you can export the template
File -> Export Template
this will create a zip file in the exported templates folder for VS
now you would see this template everytime you create a new projects.
Monday, June 28, 2010
VS Add Ins
AnkhSVN – Provides a Subversion client for Visual Studio
Code Rocket - Pseudocode and flowchart design and visualization.
CodeRush - Refactoring and productivity plugin
CopyAsHTML - Takes source code and creates an HTML markup that preserves indentation and coloring.
Designbox - Adds a toolbox that lets you associate initial property values with controls
Dotfuscator – Provides tools to help prevent reverse engineering
Koders – Adds a search plug-in to search the Koders database
PhatStudio – File navigation within a Visual Studio solution by typing partial filenames, and header switch
ReSharper - Refactoring support for .NET languages
Software Diagnostics Developer Edition - an integrated recorder, debugger and profiler for system dynamics
TracExplorer - Trac integration for Visual Studio 2005 and 2008
Visual Assist - Refactoring and code navigation support for native C++ and .NET (VC6/VS2003/VS2005/VS2008/VS2010)
VisualSVN - Subversion integration for Visual Studio 2003/2005/2008.
VsTortoise - A free TortoiseSVN add-in for Microsoft Visual Studio 2005/2008/2010
HgSccPackage - Mercurial Source Control Plugin for Visual Studio 2008/2010
VisualHG - Mercurial Source Control Plugin for Visual Studio 2005/2008/2010
XMLSpy – Integrates the XMLSpy IDE into Visual Studio
Bugnet Explorer Suite - Integrates Bugnet Issue and Project Management into Visual Studio and SVN
Tabs Studio - Provides multiple tab rows and customizable tab grouping. ($34, 30 day free trial)
SharpSort – C# source code members sorting and grouping
UModel - Integrates support for all 14 UML diagram types and code engineering functionality directly in Visual Studio. (VS2005/VS2008/VS2010)
WinGDB – Debug with GDB directly from Visual Studio. Remote Linux (via SSH), MinGW. Cygwin, embedded systems.
wave-vs.net – Plugin to enable Remote Pair Programming in Visual Studio, supports Visual Studio 2008 and Visual Studio 2010
TestDriven.NET
GhostDoc
Smart Paster
CodeKeep
PInvoke.NET
VSWindowManager PowerToy
WSContractFirst
VSMouseBindings
CopySourceAsHTML
Cache Visualizer
Wrapping It Up
more fererence:http://msdn.microsoft.com/en-us/magazine/cc300778.aspx
CodeRush - Of course. It's the bomb, enough said.
Peter Blum's ADME - ASP.NET Design Mode Extender (“ADME”) helps custom controls to provide a better design mode interface. This supports his Validation Controls, which rock, but also controls that you might write that need richer Design Mode Support.
CodeSmith Explorer - Generate CodeSmith code and templates directly from VS.NET
CopySourceAsHtml - Better than a Macro, this Add-In puts syntax-highlighed HTML on your clipboard. Now it supports "Embedded Styles" for use in BlogJet and other tools.
GhostDoc - Here's an Add-In I'd overlooked previously, now in it's 1.2 version. GhostDoc attempts to generate C# documentation that can be gleaned from the name and type of methods and properties. Roland Weigelt has big plans for version 1.30 that will include customizable text and rules. One to watch, and while it sometimes guesses wrong, it's a completely unique Add-In worth your download.
devMetrics - devMetrics is a free tool for measuring various attributes of your C# code so that you can accurately assess your product for quality and maintainability. I use it to measure cyclomatic complexity and abuse people during code reviews.
QuickCode.NET - This has been largely supplanted by CodeRush, but if you don't want to pay as much, this cool tool gives you phrase expansion and a surprising number of code expansions available on their user forum.
Mindreef SOAPscope - The original. The glory forever, this is more than an Add-In, it's a complete XML Web Services design studio. It's a bargain and works even better when setup in a workgroup. It keeps a database of all Web Services traffic, but it's more than a sniffer. It also analyzes data for WS-I compliance and allows for record and replay of messages. "It's Tivo for Web Services!"
NUnit Addin, now TestDriven.NET - If you're serious about TDD, stop fooling with NUnitGui and Attach Process and start using TestDriven.NET. It's a simple as Right-Click -> Test With -> Debugger.
pinvoke.net - Adam Nathan continues to innovate with an add-in that lets you "Insert PInvoke Signature" from the VS.NET Editor by communiating with a server-side repository with best-practice signatures to make calling unmanaged code a breeze. Also, be sure to visit the PInvoke.NET Wiki.
Reflector as an AddIn - A joint effort, run Lutz's unbelievable decompiler/explorer with Jamie's Add-In support. (There's a number of other slick, but alpha-quality addins at that link as well, including FxCop as an AddIn.)
Regions AddIn - Finally, something useful from CodeProject, this add-in helps organize your code with a simple Right-Click -> Add To New Region and Right-Click -> Add To Existing Region. You'll wonder how you lived without it!
Unleash it! - The great ASP.NET deployment tool with the unfortunate name. Formerly known as WebDeploy, this Add-In lets you deploy your ASP.NET application using whatever it takes. Now with plugin support!
WS Contract-First - Christian Weyer leads the pack with custom Web Service code generation, and coming soon, generation of WSDL itself from Message-based XSD. How's that for SOA and contract-first development?
VSCmdShell - Open a Command Prompt within a Visual Studio.NET 2003 Docked Toolbox Window!
CommentReflower - Really detail-oriented? This tool reformats your code comments to your specifications.
OnlineSearch - Search the Internet and Google directly from VS.NET!
ReSharper
MZ-Tools is also pretty feature rich...
http://www.mztools.com/v4/features.htm
CruiseControl.Net
Thursday, June 24, 2010
Read /write NULL Datetime in Sql Server by C#
Use Namespace:using System.Data.SqlTypes;
declare a variable SqlDateTime sqlNullDate;
for INSERT
if (txtSessionStartDate.Text == "")
sessionsOBJ.sDate = sqlNullDate;
else
sessionsOBJ.sDate = Convert.ToDateTime(txtSessionStartDate.Text);
and read would work normally.
Tuesday, June 22, 2010
To get the Latitude Longitude for any location
http://maps.google.com/maps/api/geocode/xml?address=1600+Pennsylvania+Ave,+Washington+D.C.&sensor=false
for JSON
http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false
or type
http://geocoder.us/demo.cgi?address=4950+stevenson+blvd+%2Cfremont+ca+94538
to get the lat and log
for details read below article
http://code.google.com/apis/maps/documentation/geocoding/index.html#Geocoding
http://www.4guysfromrolla.com/articles/060210-1.aspx
Image Generator control in ASP.Net 3.5
Download the control (Microsoft.Web.GeneratedImage.dll) from
http://aspnet.codeplex.com/releases/view/16449
This control can be used to display image faster, we can cache the generated image and we can do transformation on the generated image. To display the image, this control uses an Image HttpHandler which can accept parameters using NameValueCollection object. This Image HttpHandler is similar to normal HttpHandler which inherits an abstract class called ImageHandler. This ImageHandler abstract class internally inherits IHttpHandler.
public class ImageHandler1 : ImageHandler {
public ImageHandler1() {
// Set caching settings and add image transformations here
}
public override ImageInfo GenerateImage(NameValueCollection parameters) {
return new ImageInfo();
}
}
The implementation is really simple. Read the image from database as a byte array and convert the byte array to Microsoft.Web.ImageInfo object for the image to display. This object will come as a part of the control dll we are downloading. ImageInfo object has 2 overloaded constructors, one will take Image object and the other will take a byte array as an argument. We can pass the parameters to this handler by a collection called Parameters in GeneratedImage control. With this information, we will see how we can use this control to display images.
refere below article for more details...
http://www.codedigest.com/Articles/ASPNET/119_New_Image_Generator_control_in_ASPNet_35.aspx
Monday, June 21, 2010
Geocoding
http://www.4guysfromrolla.com/articles/051910-1.aspx
Geocoding is the process of finding associated geographic coordinates (often expressed as latitude and longitude) from other geographic data, such as street addresses, or zip codes (postal codes). With geographic coordinates the features can be mapped and entered into Geographic Information Systems, or the coordinates can be embedded into media such as digital photographs via geotagging.
Reverse geocoding is the opposite: finding an associated textual location such as a street address, from geographic coordinates.
A geocoder is a piece of software or a (web) service that helps in this process.
A simple method of geocoding is address interpolation. This method makes use of data from a street geographic information system where the street network is already mapped within the geographic coordinate space. Each street segment is attributed with address ranges (e.g. house numbers from one segment to the next). Geocoding takes an address, matches it to a street and specific segment (such as a block, in towns that use the "block" convention). Geocoding then interpolates the position of the address, within the range along the segment
Type
http://maps.google.com/maps/api/geocode/xml?address=1600+Pennsylvania+Ave,+Washington+D.C.&sensor=false
in the address bar and you would get the xml response
Thursday, June 17, 2010
Element of Web Config
timeout="number of minutes"
stateConnectionString="tcpip=server:port"
sqlConnectionString="sql connection string"
stateNetworkTimeout="number of seconds"/>
A very useful article at
http://msdn.microsoft.com/en-us/library/h6bb9cz9(VS.71).aspx
Wednesday, June 16, 2010
Favorites Icon
Tuesday, June 15, 2010
Create a Service Account for an ASP.NET 2.0 Application
Find Framework installed
OK, general end users can use either one of these ways to check the .Net framework version:
Query the User Agent String of Internet Explorer web browser. This is the easier way, I think, as every Windows bundled with IE! Although you need to remember this simple, one line JavaScript:
javascript:alert(navigator.userAgent)
Other way is to get into Registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
3 Way is to check through Windows Application:
Environment.Version property of .Net framework. For example, this simple C# source code can be compiled to a .Net console program that shows .Net framework version installed: using System;
class Version
{
public static void Main()
{
Console.WriteLine();
Console.WriteLine(".Net Framework Version {0}",
Environment.Version.ToString());
}
}
Monday, June 14, 2010
Databound Password TextBox field is blank on page load
Does anyone know a possible work around to make a databound TextBox inside a FormView work as desired?
Saturday, June 12, 2010
ENCTYPE
ENCTYPE determines how the form data is encoded. Whenever data is transmitted from one place to another, there needs to be an agreed upon means of representing that data. Music is translated into written music notation, English is written using letters and punctuation. Similarly, there needs to be an agreed on way of presenting the form data so it's clear that, for example, there is a field called "email" and its value is "raha@idocs.com".
Attribute for FORM ...
ENCTYPE = "multipart/form-data" | "application/x-www-form-urlencoded" | "text/plain"
Friday, June 11, 2010
Extension Methods
Will explain with example
public static class DateTimeHelper
{
public static DateTime ToIST(this DateTime dt)
{
DateTime utc = dt.ToUniversalTime();
return utc.AddMinutes(330);
}
public static bool IsDate(this string s)
{
DateTime dt;
return DateTime.TryParse(s, out dt);
}
}
there is static class named DateTimeHelper
All the extension methods must reside inside a static class
The extension methods themselves must be static
The ToIST() static method is an extension method that returns a DateTime instance. Observe how the parameter of the method is specified. An extension method can have any number of parameters but the first parameter indicates the data type to which that extension is applicable. In case of ToIST() method we specify that this method is an extension method of DateTime structure. The ToIST() method simply adjusts the date and time with required offset.
The IsDate() method is another extension method that will be applicable to string data type. Inside it checks if the supplied string is a valid date and returns a Boolean value.
Now, if you use DateTime structure then the Visual Studio will show you ToIST() method in the IntelliSense. Similarly, IsDate() method will be shown for string class.
More about extension methods
Though extension methods allow you to quickly extend an existing type this feature should not be used extensively as a replacement to other elegant approaches. Additionally, the following points about extension methods are worth noting.
Extension methods can chain themselves. For example you may write something like this:
dt.ToIST().ToDDMMYYYY()
The ToIST() and ToDDMMYYYY() are assumed to be extension methods.
Extension methods can be accessed only when its namespace is in scope
If an extension method has the same signature as any of the instance method of the class it extends then the instance methods take precedence
If two extension methods of a type have same signature them they must be called like normal static methods. For example, if you define two extension methods with same name and signature in two classes say DateTimeHelper1 and dateTimeHelper2, then they can be called like this - DateTimeHelper1.ToIST(dt)
Wednesday, June 9, 2010
XML
XML is a markup language much like HTML
XML was designed to carry data, not to display data
XML tags are not predefined. You must define your own tags
XML is designed to be self-descriptive
XML is a W3C Recommendation
Reading/Writing XML
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("XML\\XMLFile.xml")); //Path of XML file
GridView1.DataSource = ds;
GridView1.DataBind();
And to Write back the XML Date
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("XML\\XMLFile.xml"));
ds.WriteXml("XMLFile1.xml");
I am just creating the dataset from the existing file
Improving the Performance of Ajax enabled web page
Details can be found on this link:
http://weblogs.asp.net/bleroy/archive/2008/06/12/script-reference-profiler.aspx
Watct viedo for using it:
http://www.asp.net/aspnet-in-net-35-sp1/videos/using-script-combining-to-improve-ajax-performance
Add below to page to find the running scripts
run the page again and it will show all the scripts that take time collect them and paste then in
Tuesday, June 8, 2010
Yelp Features
* display trusted review and rating information for a particular business.
* determine accurate neighborhood name information for a particular location.
* display pictures of highly rated local businesses and of the top reviewers for that business.
* determine a particular business' review and rating information based on the phone number for that business.
Monday, June 7, 2010
Generic
A perfect example of where we would need Generics is in dealing with collections of items (integers, strings, Orders etc.).
We can create a generic collection than can handle any Type in a generic and Type-Safe manner.
For example, we can have a single array class that we can use to store a list of Users or even a list of Products, and when we actually use it, we will be able to access the items in the collection directly as a list of Users or Products, and not as objects (with boxing/unboxing, casting).
Previous problems
1)It requires that you store everything in it as an object
2)You need to cast up in order to get your object back to its actual Type
3)Performance is really lacking, especially when iterating with foreach()
4)It performs no type safety for you (no exceptions are thrown even if you add objects of different types to a single list)
System.Collections.ArrayList list = new System.Collections.ArrayList();
list.Add("a string");
list.Add(45); //no exception thrown
list.Add(new System.Collections.ArrayList()); //no exception
foreach(string s in list) { //exception will be thrown!
System.Console.WriteLine(s);
The ideal situation is for us to be able to create this generic collection functionality once and never have to do it again
-----------------
Generic Class
public class Col
{
T t;
public T Val{get{return t;}set{t=value;}}
}
"Col
This Type placeholder "T" is used to show that if we need to refer to the actual Type that is going to be used when we write this class, we will represent it as "T"
Notice on the next line the variable declaration "T t;" creates a member variable with the type of T, or the generic Type which we will specify later during construction of the class
final item in the class is the public property. Again, notice that we are using the Type placeholder "T" to represent that generic type for the type of that property. Also notice that we can freely use the private variable "t" within the class.
In order to use this class to hold any Type, we simply need to create a new instance of our new Type, providing the name of the Type within the "<>" brackets and then use that class in a Type-safe manner. For example:
public class ColMain {
public static void Main() {
//create a string version of our generic class
Col
//set the value
mystring.Val = "hello";
//output that value
System.Console.WriteLine(mystring.Val);
//output the value's type
System.Console.WriteLine(mystring.Val.GetType());
//create another instance of our generic class, using a different type
Col
//load the value
myint.Val = 5;
//output the value
System.Console.WriteLine(myint.Val);
//output the value's type
System.Console.WriteLine(myint.Val.GetType());
}
}
Thursday, June 3, 2010
IDisposable Interface
The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams
Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.
Tuesday, June 1, 2010
Differences Between Web.Config and Machine.Config
Web.config files specify configuration settings for a particular web application, and are located in the application's root directory; the machine.config file specifies configuration settings for all of the websites on the web server, and is located in $WINDOWSDIR$\Microsoft.Net\Framework\Version\CONFIG.
Web.Config Encryption
1) programatically
2) aspnet_regiis.exe, a command-line program
and the following sections can be encrypted.
Each of these sections can optionally be encrypted, either programmatically or through aspnet_regiis.exe, a command-line tool. When encrypted, the scrambled text is stored directly in the configuration file. For example, if we were to encrypt the
e.g
There are some configuration sections that you cannot encrypt using this technique:
In order to encrypt these configuration sections you must encrypt the value and store it in the registry. There's an aspnet_setreg.exe command-line tool to help along with this process
Programmatically Encrypting Configuration Sections
The System.Configuration.SectionInformation class abstractly represents a configuration section. To encrypt a configuration section simply use the SectionInformation class's ProtectSection(provider) method, passing in the name of the provider you want to use to perform the encryption. To access a particular configuration section in your application's Web.config file, use the WebConfigurationManager class (in the System.Web.Configuration namespace) to reference your Web.config file, and then use its GetSection(sectionName) method to return a ConfigurationSection instance. Finally, you can get to a SectionInformation object via the ConfigurationSection instance's SectionInformation property.
protected void UnProtect_Click(object sender, EventArgs e)
{
UnProtectSection("appSettings");
}
protected void Protect_Click(object sender, EventArgs e)
{
ProtectSection("appSettings",
"DataProtectionConfigurationProvider");
}
private void ProtectSection(string sectionName, string provider)
{
Configuration config =
WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);
if (section != null && !section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(provider);
config.Save();
}
}
private void UnProtectSection(string sectionName)
{
Configuration config =
WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);
if (section != null && section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}
Friday, May 21, 2010
shortcuts for C# coders
Copy a single line - CTRL+C [Move the insertion point at the begin or end and press space bar, then press the shortcut key combination]
Cut a single line - CTRL+X [Move the insertion point at the begin or end and press space bar, then press the shortcut key combination]
Comment a line - CTRL+K, CTRL+C [Keep the insertion point any where on line and press ]
UnComment a line - CTRL+K, CTRL+U [Keep the insertion point any where on line and press ]
Put/Remove a break point - F9
Remove all break points as once - CTRL+SHFT+F9
Expand/Collapse a region- CTRL+M, CTRL+M
Intellisense - Ctrl+Space [Press CTRL again make the drop down transparent]
Build Solution - Ctrl+Shft+B
Expand All regions - Ctrl+M+P
Collapse All regions - Ctrl+M+O
New Break Point - Ctrl+B
Switch to Code view - F7
Switch to Html view - SHIFT + F7
Html ParameterInfo - CTRL + SHIFT + SPACEBAR
GoTo window - CTRL + G
CompleteWord - ALT + RIGHT ARROW
CTRL + SPACEBAR
Comment Selection - CTRL + K, CTRL + C
Uncomment Selection - CTRL + K, CTRL + U
Line Cut - CTRL + L
Line Delete - CTRL + SHIFT + L
Make Lowercase - CTRL + U
Make Uppercase - CTRL + SHIFT + U
Tuesday, May 18, 2010
Creating aspnetdb database
C:\Windows\Microsoft.NET\Framework\v2.0.50727
find aspnet_regsql.exe and follow the wizard to creat a new database
Saturday, May 15, 2010
Application Hit Counter
Global.aspx file
Application["AppHitCount"] = 0;
lblConfCode.Text = Session["confCode"].ToString();
Application["AppHitCount"] = int.Parse(Application["AppHitCount"].ToString()) + 1;
lblAppHitCounter.Text = Application["AppHitCount"].ToString();
//lable to display the hits
Wednesday, May 12, 2010
Publish a Web site
2.In the Publish Web Site dialog box, click the ellipsis button (…) to browse to the location to which you want to publish the Web site.
You can write the Web site output to a local or shared folder, to an FTP site, or to a Web site that you access with a URL. You must have Create and Write permissions in the target location.
3.To be able to change the layout (but not the code) of .aspx files after publishing the Web site, select the Allow this precompiled site to be updateable check box.
4.To name strongly named assemblies using a key file or a key container, select the Enable strong naming on precompiled assemblies check box, and then click OK.
Publishing status is displayed in the taskbar. Depending on the connection speed, the size of the site and the types of content files, publishing time can vary. When publishing is completed, the status of Publish succeeded is displayed.
5.Make any configuration changes that are necessary for your site. For more information, see How to: Configure Published Web Site Projects. You might also want to encrypt specific configuration settings. For more information, see Encrypting Configuration Information Using Protected Configuration.
Tuesday, May 11, 2010
Accessing Config File Mail Settings Programmatically
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("PathToConfigFile");
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
int port = mailSettings.Smtp.Network.Port;
string host = mailSettings.Smtp.Network.Host;
string password = mailSettings.Smtp.Network.Password;
string username = mailSettings.Smtp.Network.UserName;
}
===============================================================
object path = "~/WebRegAdmin";
Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
ConfigurationSection appSettings = config.GetSection("connectionStrings");
if (bEncrypt)
{
appSettings.SectionInformation.ProtectSection "DataProtectionConfigurationProvider");
}
else
{
appSettings.SectionInformation.UnprotectSection();
}
config.Save();
Monday, May 10, 2010
log4net DLL
At the same time, log output can be so voluminous that it quickly becomes overwhelming. One of the distinctive features of log4net is the notion of hierarchical loggers. Using these loggers it is possible to selectively control which log statements are output at arbitrary granularity.
log4net is designed with two distinct goals in mind: speed and flexibility
•Support for multiple frameworks
•Output to multiple logging targets
•Hierarchical logging architecture
•XML Configuration
•Dynamic Configuration
•Logging Context
•Proven architecture
•Modular and extensible design
•High performance with flexibility
Friday, May 7, 2010
What is the difference between JavaScript and jQuery?
What is jQuery anyways?
Thursday, May 6, 2010
some Important tools
Rhino mocks (http://ayende.com/projects/rhino-mocks.aspx) - I can't imagine unit testing without rhino.
Snoop (http://www.blois.us/Snoop/) - Do you develop WPF apps. This visual tree tool will help you figure out how to restyle almost anything.
Wireshark (http://www.wireshark.org/) - Nothing beats this network sniffer
TFS Sidekick (http://attrice.info/cm/tfs/) - All those things you wish TFS did, sidekick does.
Stylus Studio (http://www.stylusstudio.com/) - hands down the best XML tool on the planet.
The Regulator (http://tools.osherove.com/CoolTools/Regulator/tabid/185/Default.aspx) I love regular expressions, but they can a nightmare to debug. This tool makes it regex trial and error fast and easy.
Ghost Doc (http://www.roland-weigelt.de/ghostdoc/) - I like writing code, I don't like writing comments. I like ghost doc.
Sandcastle (http://blogs.msdn.com/sandcastle/) - Again, I like writing code, I don't like writing docs. Make professional looking documentation from your code.
Process Monitor (http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) What the heck is locking that file? ProcMon knows.
Binding to Data Using a Data Source Control
Data source controls greatly expand the capabilities of data-bound controls introduced in version 2.0, such as the GridView, FormView, and DetailsView controls. When used with data source controls, these controls enable users to easily perform database operations from different data sources, with little or no code.
1) add a data source control, such as a SqlDataSource control
2) add a data-bound control, such as a GridView control and bind it to the data source control
The data source control connects to a data source such as a database or middle-tier object and then retrieves or updates data. The data-bound control can then use this data.
GridView Control
The GridView control displays one row for each record in the data source, and by default, generates a column for each field. You can, however, choose which fields in the data source will render in the grid.
The GridView control can automatically page over the data, if the underlying data source supports paging.
The GridView control must be bound to a data source; otherwise, the control will not render on the page.
Data binding
Data binding using the DataSourceID property, which allows binding the GridView control to a data source control.
Data binding using the DataSource property, which allows binding to any data source that implements the ICollection or IEnumerable interface, including ADO.NET datasets and datareaders
Saturday, May 1, 2010
IDisposable Interface
The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.
Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.
e.g
[ComVisibleAttribute(true)]
public interface IDisposable
Wednesday, April 28, 2010
Fetching Random Rows From SQL Server
Recently I needed to fetch random rows from a SQL server table. If you have an integer column then using RAND() function goes well. However in my case there was no number column. In such cases you can use the following query:
SELECT TOP
FROM