Friday, May 10, 2013

Asp.net - The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Introduction: 

Here I will explain how to solve the problem “The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).” when running web application using asp.net. 

Description: 

I created one web application and added some of script files in header section of page like this

<head id="head2" runat="server">
<title>Lightbox Page</title>
<link href="aspdotnetsuresh.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%= ResolveUrl("~/js/LightBox.js") %>"></script>
</head>
After add script file to header section i tried to run the application during that time I got error like The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Server Error in 'ASP.Net' Application.


The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

To solve this problem we have different methods
First Method
Remove JavaScript from the header section of page and add it to body of the page and run your application it will work for you.
Second Method
Replace the code block with <%# instead of <%=
<head id="head2" runat="server">
<title>Lightbox Page</title>
<link href="aspdotnetsuresh.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%# ResolveUrl("~/js/LightBox.js") %>"></script>
</head>
After replace code block with <%# instead of <%= add following code in page load

protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();    
}
After add code run your application it will work for you.

Happy Coding………

Monday, May 6, 2013

Automatically Map Network Drives on Domain Login for All Users, Certain Users, or Certain Groups


As always, use the following instructions at your own risk (and joy). Please submit any corrections or comments if you feel so moved.
Auto map network drives on login for all users
  1. Save the following batch file to the domain controller's NETLOGON share as logon.bat:
    @echo off
    net use * /delete /yes
    net use x: \\server_name\shared_directory_name
  2. Active Directory Users and Computers
  3. Right click domain name at top left and click Properties > Group Policy > Edit > User Configuration > Windows Settings > Scripts (Logon/Logoff) > Logon > Add...
  4. Enter path to logon.bat (e.g., \\ACME.local\sysvol\ACME.local\scripts\logon.bat) and click OK three times
  5. Login from workstation. Drive x: should appear in My Computer.
Auto map network drives on login for certain users:
  1. Save the following batch file to the domain controller's NETLOGON share as logon.bat:
    @echo off
    net use * /delete /yes
    net use x: \\file_server_name\shared_directory_name
  2. Active Directory Users and Computers > Users > Double click user > Profile
  3. Enter "logon.bat" (no quotes) in the "Logon script" box and click OK
  4. Login from workstation as user modified in step 2. Drive x: should appear in My Computer.
Auto map network drives on login based on Group membership
  1. Get KiXtart
  2. Put WKIX32.EXE in both the domain controller's NETLOGON share and %SystemRoot% (normally C:\WINNT\).
  3. Save the following script as map_drive.kx to the NETLOGON share (be sure to change the group as needed - here we've used Domain Users):
    use "*" /DELETE
    if ingroup("Domain Users")
    use x: "\\server_name\share_name"
    endif
  4. Save the following batch file (which calls your KiXtart script) as login.bat to the domain controller's NETLOGON share:
    @echo off
    \\server_name\NETLOGON\WKIX32.EXE \\server_name\NETLOGON\map_drive.kx
  5. Active Directory Users and Computers
  6. Right click domain name at top left and click Properties > Group Policy > Edit > User Configuration > Windows Settings > Scripts (Logon/Logoff) > Logon > Add...
  7. Enter path to login.bat (e.g., \\ACME.local\sysvol\ACME.local\scripts\login.bat) and click OK three times
  8. Login from workstation as a user belonging to group designated in map_drive.kx. Drive x: should appear in My Computer.
  9. If x: does not appear, check the permissions of NETLOGON, WKIX32.EXE, your script files, etc. Also, make sure that the user or group has the necessary permissions on the shared folder you are mapping.
More KiXtart Examples
  1. Map drive if user is *not* a member of a certain group (in this case, "Students"):
    If InGroup("Students") = 0
       Use R: "\\server\records"
    EndIf
    
  2. Using Boolean operators:
    If InGroup("Teachers") Or InGroup("Office") Or InGroup("PTA")
       Use G: "\\server\Grownup_Files"
    EndIf
    
    If InGroup("2008 Class") And InGroup("Honors")
       Use S: "\\server\smart_kids"
    EndIf
    
  3. Using Select...EndSelect (stops processing on the first true Case)
    Select
       Case InGroup("Students")
          Use S: "\\server\student_storage"
       Case InGroup("Office")
          Use O: "\\server\office_docs"
          Use R: "\\server\records"
       Case InGroup("Teachers")
          Use O: "\\server\office_docs"
          Use S: "\\server\student_storage"
          Use T: "\\server\teaching_materials"
    EndSelect
    
    
    reference : http://tinyapps.org/docs/auto_map_network_drives.html

Monday, April 29, 2013

Client Side Validation using ASP.NET Validator Controls from Javascript

       ASP.NET validation controls provide functionality to perform validation using client script. By default, when client-side validation is being performed, the user cannot post the page to the server if there are errors on the page thus the user experience with the page is enhanced.

Client-side objects:

Page_IsValid
Boolean variable
Indicates whether the page is currently valid. The validation scripts keep this up to date at all times.
Page_Validators
Array of elements
This is an array containing all of the validators on the page.
Page_ValidationActive
Boolean variable
Indicates whether validation should take place. Set this variable to False to turn off validation programmatically.
isvalid
Boolean property
This is a property on each client validator indicating whether it is currently valid.
Page_ValidationSummaries
Array of elements
This is an array containing all of the validation summaries on the page.

Client-Side APIs:

ValidatorValidate(val)
Takes a client-validator as input. Makes the validator check its input and update its display.
ValidatorEnable(val, enable)
Takes a client-validator and a Boolean value. Enables or disables a client validator. Being disabled will stop it from evaluating and it will always appear valid.
ValidatorHookupControl(control, val)
Takes an input HTML element and a client-validator. Modifies or creates the element’s change event so that it updates the validator when changed. This can be useful for custom validators that depend on multiple input values.
Page_ClientValidate(val)
Takes validation group as input and validate all validators of the group and returns bool.

Sample Code:

Let us take an example to understand, consider following asp.net code:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<div>
       <fieldset class="login">
           <legend>Account Information</legend>
           <p>
               <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label>
               <asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox>
               <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
                   CssClass="failureNotification" ErrorMessage="User Name is required." ToolTip="User Name is required."
                   ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
           </p>
           <p>
               <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
               <asp:TextBox ID="Password" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
               <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
                   CssClass="failureNotification" ErrorMessage="Password is required." ToolTip="Password is required."
                   ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
           </p>
           <p>
               <asp:CheckBox ID="AllowMe" runat="server" />
               <asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="AllowMe" CssClass="inline">Allow me without password</asp:Label>
           </p>
       </fieldset>
       <p class="submitButton">
           <asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="LoginUserValidationGroup"
               OnClientClick="performCheck();" />
       </p>
   </div>
 Client Side Validation using ASP.NET Validator Controls from Javascript

Case I: Validate the Group:

In our example, See following code to validate LoginUserValidationGroup:
?
01
02
03
04
05
06
07
08
09
10
11
function performCheck() {
            Page_ClientValidate("LoginUserValidationGroup");
            if (Page_IsValid) {
                alert('it is valid');
                return true;
            }
            else {
                alert('No valid');
                return false;
            }
        }
In other way, you can directly use Page_ClientValidate method:
?
01
02
03
04
05
06
07
08
09
10
function performCheck() {        
           if (Page_ClientValidate("LoginUserValidationGroup")) {
                alert('it is valid');
                return true;
            }
            else {
                alert('No valid');
                return false;
            }
        }

Case II:

To understand other client side objects and APIs, let us validate LoginUserValidationGroup without using Page_ClientValidate.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function performCheck() {
            if (checkValidationGroup("LoginUserValidationGroup")) {
                alert('it is valid');
                return true;
            }
            else {
                alert('No valid');
                return false;
            }
        }
    
        function checkValidationGroup(valGrp) {
            var rtnVal = true;
            for (i = 0; i < Page_Validators.length; i++) {
                if (Page_Validators[i].validationGroup == valGrp) {
                    ValidatorValidate(Page_Validators[i]);
                    if (!Page_Validators[i].isvalid) { //at least one is not valid.
                        rtnVal = false;
                        break; //exit for-loop, we are done.
                    }
                }
            }
            return rtnVal;
        }
In checkValidationGroup method, first validation group of all validators on page is checked. If it belongs to given group, it is validated. If it is not valid, the method will return false.

Case III: Enable/Disable Validator:

Suppose you have to disable password requiredfield validator If ‘Allow me’ checkbox is true. See following code:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
function performCheck() {
          if (document.getElementById('<%=AllowMe.ClientID%>').checked) {
              ValidatorEnable(document.getElementById('<%=PasswordRequired.ClientID%>'), false);
          }
          if (Page_ClientValidate("LoginUserValidationGroup")) {
              alert('it is valid');
              return true;
          }
          else {
              alert('No valid');
              return false;
          }
      }
Hope It helps!!!