NEWS

Wednesday, June 29, 2011

Load Text from File to String [C#]

To load text from file to string you can use StreamReader.Re­adToEnd method. First create new instance of StreamReader. As a parameter in constructor you can pass string with file path or Stream instance. Default encoding is UTF-8.


using System.IO;




StreamReader streamReader = new StreamReader(filePath);

string text = streamReader.ReadToEnd();

streamReader.Close();





Tuesday, June 21, 2011

SSRS 2008 tutorial

To create subreport as drilldown

To create a subreport as drilldown type to a particular cell data.

1. After creating the main report.
2. Right click on any datacell and choose "Insert Row/Below".
3. Select all the data cells of the newly created row, right click and click "Merge cells"
4. In the sub report tablix properties :
    provide "Name", select "Report Name",  "Hidden : True", "Toggle item : "

Now check the preview. The below image is an example.

To add embedded code to a report


1. In Design view, right-click the design surface outside the border of the report and click Report Properties.

2. Click Code.


3. In Custom code, type the code. Errors in the code produce warnings when the report runs. The following example creates a custom function named ChangeWord that replaces the word "Bike" with "Bicycle".
 
Public Function ChangeWord(ByVal s As String) As String



Dim strBuilder As New System.Text.StringBuilder(s)


If s.Contains("Bike") Then


strBuilder.Replace("Bike", "Bicycle")


Return strBuilder.ToString()


Else : Return s


End If


End Function
 
The following example shows how to pass a dataset field named Category to this function in an expression:
=Code.ChangeWord(Fields!Category.Value)
If you add this expression to a table cell that displays category values, whenever the word "Bike" is in the dataset field for that row, the table cell value displays the word "Bicycle" instead.

Sql Server Reporting services 2008 Tablix control

When working with Sql server 2008 reporting services I found a new control named Tablix. [Of course there are plenty of new features] This is a mix of both Table and a Matrix. The main and great advantage of it is when we drag a table or matrix to the report body you can't find table or matrix any more. The report control automatically convert it to Tablix. Now, it's very easy to show the complex and grouping of data with this control.


The interest thing in 2008 reporting services is, When I open report builder 2008, BIDS 2008 I didn't find the Tablix control at all and started researching for the control. Stupidly searched in google like download tablix control ssrs 2008 etc… But, once I drap and drop the table or matrix and right clicked for properties found "tablix properties" in list of properties there. Then understood the whole concept and implemented the reports very fast.

Data Formatting in sql server reporting services

In Sql server reporting services the formatting the data is pretty much simple as we have plenty of built in options available for percentage, numbers, decimal, currency etc. So, just them to data format and display the data as you want. Below are most commonly use format for the usual reports.




c – Currency
d – Decimal
n – Number
p – Percentage.

If you want two decimal places in decimal number then in the format option [Text box properties -> format] then the format should be d2. In percentage if you want two decimal places in percentage then the format is p2 etc.. But, I have tried it some reports, and found not working. Then used the default C# string formats for the data formatting in reports. That is, for two decimal places the format is like 0.00. Then the result data will be two decimal places. Example, 5.67. So, you can try both and use which one is best fit for you.

There are other plenty of formats available and they are completely described here.
http://msdn.microsoft.com/en-us/library/ms252080%28VS.80%29.aspx

Expand Collapse columns in a table SSRS

1. Select all the columns that you want to make expandable, collapsible.


2. Hit F4 [Properties window] –> Select Visibility, and in that, set these values, Hidden = true and ToggleItem = ID of the textbox [Where you want to show the Expand[+], Collpse[-] symbols that text box id. in other words parent text box id.]

Thursday, June 16, 2011

How to set report path and server url

reportViewer1.ServerReport.ReportServerUrl = new Uri("http://localhost/reportserver");


reportViewer1.ServerReport.ReportPath = "/WH/WHRep";

ReportParameter rp = new ReportParameter("SchYears", "93");

reportViewer1.ServerReport.SetParameters(new ReportParameter[] { rp });

reportViewer1.DocumentMapCollapsed = true;

reportViewer1.PromptAreaCollapsed = true;

Thursday, June 9, 2011

To pass parameters to report from reportviewer in asp.net

if(!Page.IsPostBack)


ReportViewer1.ServerReport.SetParameters(new Microsoft.Reporting.WebForms.ReportParameter("ParamName","ParamValue"));

Wednesday, June 8, 2011

How To Determine if Reporting Services was Installed

If reporting services was installed, then there are two databases installed along with it. Just look for those databases:


select * from sys.databases where name like 'ReportServer%'


Indian Rupee symbol in typing

The Foradian have came up with new way to implement the font. Since, UTC accepted code position U+20B9 for the character of Indian Rupee Sign. This means that we could use the rupee symbol around the world without deviating from Unicode standards. However, It would take time to implement rupee symbol to ISO Standard and to all fonts. You can download the New font from Foradian but using font with the default keyboard will not be that ease. Foradian have came up with solution for this problem, Download the font from Foradian website, Download the Font. Follow the instruction given on their site to install the font and keyboard layout. If you need to type single quote instead of symbol just change keyboard layout from below language bar on the taskbar.




SSRS Version

To determine the version of Reporting Services, go to your report server (http://server_name/reportserver). At the bottom of the page, you should see "Microsoft SQL Server Reporting Services Version" with the version number following it.



You can match your version number to which service pack here: http://support.microsoft.com/default.aspx/kb/321185
I you want to do this programmatically, take a look at the ServerInfoHeader class. When you make a request to the report server SOAP API you'll be able to get detailed information. The link below is for the 2005 Execution endpoint, there's a similar structure for the Management endpoint.


http://msdn2.microsoft.com/en-us/library/microsoft.wssux.reportingserviceswebservice.rsexecutionservice2005.serverinfoheader(sql.90).aspx



Tuesday, June 7, 2011

SQL SERVER – Delete Duplicate Records – Rows

Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.




DELETE

FROM MyTable

WHERE ID NOT IN

(

SELECT MAX(ID)

FROM MyTable

GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)



SQL Server Reporting services tutorial

Monday, June 6, 2011

What is the difference between Session.Abandon() and Session.Clear()?


Session.Abandon() will end current session by firing Session_End and in the next
request, Session_Start will be fire.

Session.Clear( ) just clears the session data without killing it. With session.clear
variable is not removed from memory it just like giving value null to this session.

Session ID will remain same in both cases, as long as the browser is not closed.

Sunday, June 5, 2011

What is SAX?

SAX is a simple API for XML Processing.
It is generally an alternative to DOM and it also can be used to parse the XML documents.
This simple API is based on Streaming model

Main Advantage of using SAX over DOM :

SAX does not build an in memory representation of the source XML document so when parsing large amount of XML documents it does not require a large amount of memory or Resources.

Friday, June 3, 2011

II7 issues and work-arounds

ASP.NET 2.0 applications on IIS 7.0 are hosted using the ASP.NET Integrated mode by default. This new mode enables a myriad of exciting scenarios including using super-valuable ASP.NET features like Forms Authentication for your entire Web site, and developing new ASP.NET modules to do things like URL rewriting, authorization, logging, and more at the IIS level. For more information about the ASP.NET Integration in IIS 7.0, see: ASP.NET Integration with IIS7.


As you know, with great power comes great responsibility. Similarly, with making ASP.NET applications more powerful in IIS 7.0 comes the responsibility of making sure that existing ASP.NET applications continue to work. This has been a major challenge for us as we re-architected the entire core engine of ASP.NET, and in the end we were highly successful in meeting it. As a result, most ASP.NET applications should work without change.

This post lists the changes in behavior that you may encounter when deploying your ASP.NET applications on IIS 7.0 on Windows Vista SP1 and Windows Server 2008. Unless noted, these breaking changes occur only when using the default ASP.NET Integrated mode.

Using Classic ASP.NET mode

IIS 7.0 also offers the ability to run ASP.NET applications using the legacy Classic ASP.NET Integration mode, which works the same way as ASP.NET has worked on previous versions of IIS. However, we strongly recommend that you use a workaround where available to change your application to work in Integrated mode instead. Moving to Classic mode will make your application unable to take advantage of ASP.NET improvements made possible in Integrated mode, leveraging future features from both Microsoft and third parties that may require the Integrated mode. Use Classic mode as a last resort if you cannot apply the specified workaround. For more information about moving to Classic mode, see: Changing the ASP.NET integration mode.

Migration errors


These errors occur due to changes in how some ASP.NET configuration is applied in Integrated mode. IIS will automatically detect this configuration and issue an error asking you to migrate your application, or move it to classic mode if migration is not acceptable (See breaking change #3 below).

1) ASP.NET applications require migration when specifying configuration in or .


You will receive a 500 - Internal Server Error. This can include HTTP Error 500.22, and HTTP Error 500.23: An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

It occurs because ASP.NET modules and handlers should be specified in the IIS and configuration sections in Integrated mode.

Workaround:

1) You must migrate the application configuration to work properly in Integrated mode. You can migrate the application configuration with AppCmd:
> %windir%\system32\inetsrv\Appcmd migrate config ""

2) You can migrate manually by moving the custom entries in in the / and / configuration manually to the / and / configuration sections, and either removing the and configuration OR adding the following to your application’s web.config:





2) ASP.NET applications produce a warning when the application enables request impersonation by specifying in configuration


You will receive a 500 - Internal Server Error. This is HTTP Error 500.24: An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

It occurs because ASP.NET Integrated mode is unable to impersonate the request identity in the BeginRequest and AuthenticateRequest pipeline stages.

Workaround:

1) If your application does not rely on impersonating the requesting user in the BeginRequest and AuthenticateRequest stages (the only stages where impersonation is not possible in Integrated mode), ignore this error by adding the following to your application’s web.config:





2) If your application does rely on impersonation in BeginRequest and AuthenticateRequest, or you are not sure, move to classic mode.


3) You receive a configuration error when your application configuration includes an encrypted section.

You will receive a 500 – Internal Server Error. This is HTTP Error 500.19: The requested page cannot be accessed because the related configuration data for the page is invalid.

The detailed error information indicates that “Configuration section encryption is not supported”.

It occurs because IIS attempts to validate the section and fails to read section-level encryption.

Workaround:

1) If your application does not have the problem with request impersonation per breaking change #2, migrate your application configuration by using AppCmd as described in breaking change #1:
> %windir%\system32\inetsrv\Appcmd migrate config ""

This will insure that the rest of application configuration is migrated, and automatically add the following to your application’s web.config to ignore the section:





2) If your application does have the problem with request impersonation, move to classic mode.

Authentication, Authorization, and Impersonation


In Integrated mode, both IIS and ASP.NET authentication stages have been unified. Because of this, the results of IIS authentication are not available until the PostAuthenticateRequest stage, when both ASP.NET and IIS authentication methods have completed. This causes the following changes:

4) Applications cannot simultaneously use FormsAuthentication and WindowsAuthentication

Unlike Classic mode, it is not possible to use Forms Authentication in ASP.NET and still require users to authenticate with an IIS authentication method including Windows Authentication, Basic Authentication, etc. If Forms Authentication is enabled, all other IIS authentication methods except for Anonymous Authentication should be disabled.

In addition, when using Forms Authentication, the following changes are in effect:

- The LOGON_USER server variable will be set to the name of the Forms Authentication user.

- It will not be possible to impersonate the authenticated client. To impersonate the authenticated client, you must use an authentication method that produces a Windows user instead of Forms Authentication.

Workaround:

1) Change your application to use the pattern explained in Implementing a two level authentication scheme using Forms Authentication and another IIS authentication method in IIS 7.0.

5) Windows Authentication is performed in the kernel by default. This may cause HTTP clients that send credentials on the initial request to fail.

IIS 7.0 Kernel-mode authentication is enabled by default in IIS 7.0. This improves the performance of Windows Authentication, and simplifies the deployment of Kerberos authentication protocol. However, it may cause some clients that send the windows credentials on the initial request to fail due to a design limitation in kernel-mode authentication. Normal browser clients are not affected because they always send the initial request anonymously.

NOTE: This breaking change applies to both Classic and Integrated modes.

Workaround:

1) Disable kernel-mode authentication by setting the userKernelMode to “false” in the system.webServer/security/authentication/windowsAuthentication section. You can also do it by AppCmd as follows:

> %windir%\system32\inetsrv\appcmd set config /section:windowsAuthentication /useKernelMode:false

6) Passport authentication is not supported.

You will receive an ASP.NET 500 – Server Error: The PassportManager object could not be initialized. Please ensure that Microsoft Passport is correctly installed on the server.

Passport authentication is no longer supported on Windows Vista and Windows Server 2008. NOTE: This breaking change applies to both Classic and Integrated modes.

7) HttpRequest.LogonUserIdentity throws an InvalidOperationException when accessed in a module before PostAuthenticateRequest

You will receive an ASP.NET 500 – Server Error: This method can only be called after the authentication event.

HttpRequest.LogonUserIdentity throws an InvalidOperationException when accessed before PostAuthenticateRequest, because the value of this property is unknown until after the client has been authenticated.

Workaround:

1) Change the code to not access HttpRequest.LogonUserIdentity until at least PostAuthenticateRequest

8) Client impersonation is not applied in a module in the BeginRequest and AuthenticateRequest stages.

The authenticated user is not known until the PostAuthenticateRequest stage. Therefore, ASP.NET does not impersonate the authenticated user for ASP.NET modules that run in BeginRequest and AuthenticateRequest stages. This can affect your application if you have custom modules that rely on the impersonating the client for validating access to or accessing resources in these stages.

Workaround:

1) Change your application to not require client impersonation in BeginRequest and AuthenticateRequest stages.

9) Defining an DefaultAuthentication_OnAuthenticate method in global.asax throws PlatformNotSupportedException

You will receive an ASP.NET 500 – Server Error: The DefaultAuthentication.Authenticate method is not supported by IIS integrated pipeline mode.

In Integrated mode, the DefaultAuthenticationModule.Authenticate event in not implemented and hence no longer raises. In Classic mode, this event is raised when no authentication has occurred.

Workaround:

1) Change application to not rely on the DefaultAuthentication_OnAuthenticate event. Instead, write an IHttpModule that inspects whether HttpContext.User is null to determine whether an authenticated user is present.

10) Applications that implement WindowsAuthentication_OnAuthenticate in global.asax will not be notified when the request is anonymous[M2]

If you define the WindowsAuthentication_OnAuthenticate method in global.asax, it will not be invoked for anonymous requests. This is because anonymous authentication occurs after the WindowsAuthentication module can raise the OnAuthenticate event.

Workaround:

1) Change your application to not use the WindowsAuthentication_OnAuthenticate method. Instead, implement an IHttpModule that runs in PostAuthenticateRequest, and inspects HttpContext.User.

Request limits and URL processing


The following changes result due to additional restrictions on how IIS processes incoming requests and their URLs.

11) Request URLs containing unencoded “+” characters in the path (not querystring) is rejected by default

You will receive HTTP Error 404.11 – Not Found: The request filtering module is configured to deny a request that contains a double escape sequence.

This error occurs because IIS is by default configured to reject attempts to doubly-encode a URL, which commonly represent an attempt to execute a canonicalization attack.

Workaround:

1) Applications that require the use of the “+” character in the URL path can disable this validation by setting the allowDoubleEscaping attribute in the system.webServer/security/requestFiltering configuration section in the application’s web.config. However, this may make your application more vulnerable to malicious URLs:







12) Requests with querystrings larger then 2048 bytes will be rejected by default

You will receive an HTTP Error 404.15 – Not Found: The request filtering module is configured to deny a request where the query string is too long.

IIS by default is configured to reject querystrings longer than 2048 bytes. This may affect your application if it uses large querystrings or uses cookieless ASP.NET features like Forms Authentication and others that cumulatively exceed the configured limit on the querystring size.

NOTE: This breaking change applies to both Classic and Integrated modes.

Workaround:

1) Increase the maximum querystring size by setting the maxQueryString attribute on the requestLimits element in the system.webServer/security/requestFiltering configuration section in your application’s web.config:








Changes in response header processing

These changes affect how response headers are generated by the application.

13) IIS always rejects new lines in response headers (even if ASP.NET enableHeaderChecking is set to false)

If your application writes headers with line breaks (any combination of \r, or \n), you will receive an ASP.NET 500 – Server Error: Value does not fall within the expected range.

IIS will always reject any attempt to produce response headers with line breaks, even if ASP.NET’s enableHeaderChecking behavior is disabled. This is done to prevent header splitting attacks.

NOTE: This breaking change applies to both Classic and Integrated modes.

14) When the response is empty, the Content-Type header is not suppressed

If the application sets a Content-Type header, it will remain present even if the response is cleared. Requests to ASP.NET content types will typically have the “Content-Type: text/html” present on responses unless overridden by the application.

Workaround:

1) While this should not typically have a breaking effect, you can remove the Content-Type header by explicitly setting the HttpResponse.ContentType property to null when clearing the response.

15) When the response headers are cleared with HttpResponse.ClearHeaders, default ASP.NET headers are not generated. This may result in the lack of Cache-Control: private header that prevents the caching of the response on the client

HttpResponse.ClearHeaders does not re-generate default ASP.NET response headers, including “Content-Type: text/html” and “Cache-Control: private”, as it does in Classic mode. This is because ASP.NET modules may call this API for requests to any resource type, and therefore generating ASP.NET-specific headers is not appropriate. The lack of the “Cache-Control” header may cause some downstream network devices to cache the response.

Workaround:

1) Change application to manually generate the Cache-Control: private header when clearing the response, if it is desired to prevent caching in downstream network devices.

Changes in application and module event processingThese changes affect how the application and module event processing takes place.

16) It is not possible to access the request through the HttpContext.Current property in Application_Start in global.asax

If your application accesses the current request context in the Application_Start method in global.asax as part of application initialization, you will receive an ASP.NET 500 – Server Error: Request is not available in this context.

This error occurs because ASP.NET application initialization has been decoupled from the request that triggers it. In Classic mode, it was possible to indirectly access the request context by accessing the HttpContext.Current property. In Integrated mode, this context no longer represents the actual request and therefore attempts to access the Request and Response objects will generate an exception.

Workaround:

1) See Request is not available in this context exception in Application_Start for a detailed description of this problem and available workarounds.

17) The order in which module event handlers execute may be different then in Classic mode

The following differences exist:

- For each event, event handlers for each module are executed in the order in which modules are configured in the configuration section. Global.asax event handlers are executed last.

- Modules that register for the PreSendRequestHeaders and PreSendRequestContent events are notified in the reverse of the order in which they appear in the configuration section

- For each event, synchronous event handlers for each module are executed before asynchronous handlers. Otherwise, event handlers are executed in the order in which they are registered.

Applications that have multiple modules configured to run in either of these events may be affected by these change if they share a dependency on event ordering. This is not likely for most applications. The order in which modules execute can be obtained from a Failed Request Tracing log.

Workaround:

1) Change the order of the modules experiencing an ordering problem in the system.webServer/modules configuration section.

18) ASP.NET modules in early request processing stages will see requests that previously may have been rejected by IIS prior to entering ASP.NET. This includes modules running in BeginRequest seeing anonymous requests for resources that require authentication.

ASP.NET modules can run in any pipeline stages that are available to native IIS modules. Because of this, requests that previously may have been rejected in the authentication stage (such as anonymous requests for resources that require authentication) or other stages prior to entering ASP.NET may run ASP.NET modules.

This behavior is by design in order to enable ASP.NET modules to extend IIS in all request processing stages.

Workaround:

1) Change application code to avoid any application-specific problems that arise from seeing requests that may be rejected later on during request processing. This may involve changing modules to subscribe to pipeline events that are raised later during request processing.

Other application changes

Other changes in the behavior of ASP.NET applications and APIs.

19) DefaultHttpHandler is not supported. Applications relying on sub-classes of DefaultHttpHandler will not be able to serve requests.[M3]

If your application uses DefaultHttpHandler or handlers that derive from DefaultHttpHandler, it will not function correctly. In Integrated mode, handlers derived from DefaultHttpHandler will not be able to pass the request back to IIS for processing, and instead serve the requested resource as a static file. Integrated mode allows ASP.NET modules to run for all requests without requiring the use of DefaultHttpHandler.

Workaround:

1) Change your application to use modules to perform request processing for all requests, instead of using wildcard mapping to map ASP.NET to all requests and then using DefaultHttpHandler derived handlers to pass the request back to IIS.

20) It is possible to write to the response after an exception has occurred.

In Integrated mode, it is possible to write to and display an additional response written after an exception has occurred, typically in modules that subscribe to the LogRequest and EndRequest events. This does not occur in Classic mode. If an error occurs during the request, and the application writes to the response in EndRequest after the exception has occurred, the response information written in EndRequest will be shown. This only affects requests that include unhandled exceptions. To avoid writing to the response after an exception, an application should check HttpContext.Error or HttpResponse.StatusCode before writing to the response.

21) It is not possible to use the ClearError API to prevent an exception from being written to the response if the exception has occurred in a prior pipeline stage

Calling Server.ClearError during the EndRequest event does not clear the exception if it occurred during an earlier event within the pipeline. This is because the exception is formatted to the response at the end of each event that raises an exception.

Workaround:

1) Change your application to call Server.ClearError from the Application_OnError event handler, which is raised whenever an exception is thrown.

22) HttpResponse.AppendToLog does not automatically prepend the querystring to the URL.[M4]

When using HttpResponse.AppendToLog to append a custom string to the URL logged in the request log file, you will manually need to prepend the querystring to the string you pass to this API. This may result in existing code losing the querystring from the logged URL when this API is used.

Workaround:

1) Change your application to manually prepend HttpResponse.QueryString.ToString() to the string passed to HttpResponse.AppendToLog.

Other changes.

23) ASP.NET threading settings are not used to control the request concurrency in Integrated mode

The minFreeThreads, minLocalRequestFreeThreads settings in the system.web/httpRuntime configuration section and the maxWorkerThreads setting in the processModel configuration section no longer control the threading mechanism used by ASP.NET. Instead, ASP.NET relies on the IIS thread pool and allows you to control the maximum number of concurrently executing requests by setting the MaxConcurrentRequestsPerCPU DWORD value (default is 12) located in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\2.0.50727.0 key. This setting is global and cannot be changed for individual application pools or applications.

Workaround:

1) To control the concurrency of your application, set the MaxConcurrentRequestsPerCPU setting.

24) ASP.NET application queues are not used in Integrated mode. Therefore, the “ASP.NET Applications\Requests in Application Queue” performance counter will always have a value of 0

ASP.NET does not use application queues in Integrated mode.

25) IIS 7.0 always restarts ASP.NET applications when changes are made to the application’s root web.config file. Because of this, waitChangeNotification and maxWaitChangeNotification attributes have no effect.

IIS 7.0 monitors changes to the web.config files as well, and cause the ASP.NET application corresponding to this file to be restarted without regard to the ASP.NET change notification settings including the waitChangeNotification and maxWaitChangeNotification attributes in the system.web/httpRuntime configuration sections.

26) ASP.NET deadlock detection is not supported in Integrated mode.

ASP.NET 2.0 Classic mode supports a deadlock detection mechanism which monitors ASP.NET responses and considers the process deadlocked if no responses have been received in more then the amount of time specified in the setting, and there are more than a certain number of requests outstanding. In this case, the process is marked unhealthy and a new process is eventually started. In Integrated mode, this feature is not supported. If your application is prone to deadlocks, it may lead to deadlock conditions being undetected, however it should have no effect on healthy applications that do not exhibit deadlocks.






Thursday, June 2, 2011

Client Ids generation with ASP.NET 4.0

Client Ids were always been problem for us.But as now a days, in new age application we are moving more towards the client side programming in new Rich Interent applications. Many new technologies and the way of programming has been evolved in last few years to make very rich UI like JQuery,JSon,Dojo.


In DOM, to access a a control client id play pivotal role.So Microsoft also trying to make our life easier by providing the capability to control over the client id generation which will ensure easy simple and less error prone RIA development.

So lets discus, how the ClientIds were generated earlier. First I’will start with normal control say textbox control or a label. So here the client Ids that are generated, was starting with prefix of all the naming containers from top to bottom with separated as underscore. And actually this was a good idea to generate the unique id at client side. But as I discussed ClientIds are key part of new age development. Lets look at the example for a simple textbox server control.My aspx looks like

So from the above picture we can see that my label and textbox are inside a contentplaceholder. Now lets look at the ClientId

Now here client Id is ctl00_ContentPlaceHolder1_myTextBox.If we go one by one the ctl00 is the counter ,next one is ID of contentplaceholder and next id of textbox.


So one thing as you move the control to some other part the Client Id will get changed as well.

So although we know the ID is going to be unique on the page but still you dont have any control over it . .Net engine will generate the ClientIds according to its algorithm for you ).

Control Client Ids generation with ASP.NET 4.0:


ASP.NET 4.0 provides the power to control Client Ids generation. For that it provide the new property ClientIDMode property to handle this.This property enables us to to specify that, how the Client Ids will be generated for the controls . This provides four options:




•AutoID

•Static

•Predictable

•Inherit

We’ll discuss one by one.

AutoID: this property is same as earlier version of .NET.Specify this value if you dont want any changes in the Client Id genration from the earlier version.As I discussed in ClientIDs in earlier versions.

Static: Means the you want the static id of your control.You should use this property when you know the ID will be going to be unique on the page. Here .net engine will generate the Client Ids as it is, without adding any suffixes or prefixes in it. This mode is mainly used for normal single control. Lets look at the example.


Here as you seen in the picture,I set the ClientIDMode for Label AutoID and for TextBox I set it Static. Now lets see the generated Client Ids


Now if you see the client ID of Label it is same as earlier one because here I set it Auto.


But for the TextBox I set it static. So here the Client Id is same as the ID that we set it on aspx page.This is the beauty of ASP.NET 4.0 . So if we set it static the .net engine wont generate a new client id for the control it will use the ID of the control as Client ID.

Note: One thing need to make sure here, if we set the mode static then there should be no control on the page with the same id because it will have the same client id on the page and it may be disastrous when we access it from Clientside.

Predictable: This is one another mode that I liked for the ClienId generation. When you exactly dont know whether the Id is unique on the page or not, then you can use this property.This value enables us the predict the client ids on the rendered page.When you set mode to this, you need to set some more proprties according to your own choice.

Now I will take the example as above.Now here the aspx code would be like
Here One thing we are using datacontrol then we can not set it static because there going to be multiple controls generated based on the data.
So here we will be using mode as Predictable so that we can predict what will be the id of the contrl. One more property ClientIDRowSuffix we need to set it here. I set it ID meand the ID column.
Now lets look at the generated Client Ids
Now here if we look at the ClientID . So here it is MainContent_gridviewBooks_lblName_1. So if look it deeply the we find that here there is no conter like thing. Here we have first id of contentplaceholder the id of gridview the id of label the the suffix id that we set. So its really predictable and similarly for other rows.
Inherit: This is also value to set the to this property.As the name suggests,it means the Id genration of the control will be same as parent cpntrol. This is the default behavior of the control.

Setting the property at various levels:

There are various places where we can set the ClientIDMode property.This can be set at control level, page level as well as application. The behavior will be same. We can set it at page directive as below.


To set it at Application level, we need to set it in config file as
and that will be applied across all the pages in the application.

Some basics about C#

I have seen a lot of confusion amongst a lot developers about some basic things of C#. I am going to discuss some of them here.


The very first thing, In C# every thing is a struct or a Class. And every type(Class) is a derived from System.Object, whether is of reference type or Value type.

All Value type variables are derived from System.Value type and System.Value type itself is derived from System.Object. And every value type variables is declared sealed type so no one can derive from it.


Now Lets move some basic Questions.

- What is the difference string, String and System.String?
- What is the difference amongst int, System.Int32, System.Int64.

So these are few basic things, some always have confusion. So lets try to clear it out.

int c;


System.Int32 c;

int c=0;

System.Int32 c = 0;
int c= new int();
System.Int32 c = new System.Int32();

So what is the difference in all above. or Is there any differences?




In one word answer: NO



All of the above would be compiled and will produce the same and exact IL code.



It means all of these are same. Actually C# define primitive types and every primitive is directly mapped to some Class in FCL. So whenever you are going to write the primitive type, compiler while compiling finds the exact Class from the FCL and replaces with it.

Similarly, System.String or String or string all are same. Even I had confusion earlier between String and string. Even when you type both in Visual Studio IDE, both are in different color.

One more thing, I want to say every value type is initialized to its defined default value. Whether you give its default value or not Compiler does it for you, but this is not true for Reference Type.

One already know, writing int is mapped Int32 or is of 32 bit. But some people have different view, according to them int is of 32 bit in 32 bit machines and is of 64 bit on 64 bit machines. Which is absolutely wrong and int is always of 32 bit in C#, whether is of 32 bit or 64 bit machines.

Hope it clears…