Wednesday, May 25, 2011

Selecting checkboxlist type on checkbox checked on OnAutoPostback=true

On pageload
-------------------
$(document).ready(




}

{
function () {var "input[id*='chkSelectAll']");if ("checked")) {"input[id*='chlTypeList']")."checked", "checked");"input[id*='chlTypeList']")."disabled", true);else //$("input[id*='chlTypeList']").removeAttr("checked");
}
});

SelectAll Checkbox
---------------------------




}



}
}
"input[id*='chlTypeList']")."disabled", false);function if ("checked")) {"input[id*='chlTypeList']")."checked", "checked");"input[id*='chlTypeList']")."disabled", true);else {"input[id*='chlTypeList']")."checked");"input[id*='chlTypeList']")."disabled", false);attr($(removeAttr($(attr($(attr($($(Check).attr(ChangeCheckboxlist(Check) {attr(
$(
attr(
$(
attr(
$(
$(Check).attr(
Check = $(

Friday, May 20, 2011

Limiting the No. of Characters in TextBox using JQuery

1. In aspx page:
<div>
<div>
<asp:ImageButton ID="imgAddCommentUser" CommandName="AddReply" runat="server" />
<asp:TextBox ID="txtReplies" runat="server" TextMode="MultiLine" onKeyUp="textCounter(this.id);"Text="Write a replies..."></asp:TextBox>
</div>
<div class="clear">
</div>
<div style="float: right; padding: 0 0 0 50px; *margin-top: -15px;"><span id="spanLeftChar" runat="server">
<small>4000 characters left</small>
</span>

In Jquery.js
---------------
eg: 4000 characters


 
        var spanObj = $(txtId).parent().next().next().children("span:first");       

        len = $(txtId).val().length;
        
        if (len > limit)
            $(txtId).val($(txtId).val().substring(0, limit));


      if((limit - len)>=0)
          $(spanObj).html("<small>" + (limit - len) + " characters left </small>")
        else
            $(spanObj).html("<small>0 characters left </small>")
    }

    function textCounter(txtId)
     {            
        var limit = 4000;
        var txtId = "#" + txtId;

The Other Side of FileUpload Control.

1. The maximum size of the fileupload control 2GB for .net 2.0 and 1GB for .net 1.0.

2  The default maximum size of the fileupload control is 4MB.

3. How to do error handling if the file size exceeds 10 MB or N MB. The steps are as follows

3.1 Create the Global.asax file which should be in the root directory of your application.

3.2 Place the below code in the Application_AuthenticateRequest event
 
(HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");//Approx 100 Kb(for page content) size has been deducted because the maxRequestLength proprty is the page size, not only the file upload size
int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;//This code is used to check the request length of the page and if the request length is greater than //MaxRequestLength then retrun to the same page with extra query string value action=exception

{


(HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));// Check if body contains data
{
if (workerRequest.HasEntityBody())// get the total body length
int requestLength = workerRequest.GetTotalEntityBodyLength();// Get the initial bytes loaded

initialBytes

{
int initialBytes = 0;if (workerRequest.GetPreloadedEntityBody() != null)= workerRequest.GetPreloadedEntityBody().Length;if (!workerRequest.IsEntireEntityBodyIsPreloaded())byte[] buffer = new byte[512000];// Set the received bytes to initial bytes before start reading

{
int receivedBytes = initialBytes;while (requestLength - receivedBytes >= initialBytes)// Read another set of bytesinitialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);// Update the received bytesreceivedBytes
}

}
}
}

3.3  In the Application_Error add the following code

HttpContext context = HttpContext.Current;
Exception ex = Context.Server.GetLastError();
if(ex != null)
if (ex.InnerException.Message.ToString().ToLower().IndexOf("request length exceed") >= 0)
{
context.Server.ClearError();
context.Response.Redirect(Resources.Redirection.FileMaximumUploadError);
}

3.4. In the web.config add the following

<httpRuntime requestValidationMode="2.0" maxRequestLength="10240" executionTimeout="600" />

maxRequestLength in kilobytes =eg. 10 Mb

3.5. In the FileMaximumUploadError.aspx add the error Message.

Thursday, May 12, 2011

Input $1500.00 Output 1500.00

object objData = dr["POExtendedCost"];
string strData = decimal.Parse(objData.ToString(), NumberStyles.Currency).ToString();

Format a double string datetime

String.Format( "{0:#.##}",dt.Rows(0).Item("CostPerUnit"))
DateTime.Parse(.Item("ExpiryDt").ToString).ToString("dd/MM/yyyy")
Convert.ToDateTime(cpRow["AvailabilityDate"]).ToString("MM-dd-yyyy")

txtQuantity.Text = value.ToString("f2") eg: 10.32

Retrieving a value from readonly textbox

Server.HtmlEncode(Request.Form[txtExtendedCost.UniqueID])

Enabling caching for a table in asp.net for sql dependency

http://blogs.msdn.com/b/tolong/archive/2007/02/16/sql-cache-dependency.aspx

Unable to start debugging on the web server. Debugging failed

"Unable to start debugging on the web server. Debugging failed because
integrated Windows authentication is not enabled.

Please see Help for assistance" - What could be the problem?

in case the project is on local IIS server, you need to enable Integrated
Windows Authentication on the local IIS.

1. Open IIS Manager (Internbet Information Services)
2. Right-click the web site (in case you run it locally you only have
Default web site) and pick Properties
3. Choose "Directory Security" tab and click Edit on "Anonymous access and
authentication control"
4. In the opening window, uncheck "Allow Anonymous access" and check
"Integrated Windows Authentication" (allowing anonymous can make that you
don't have enough permissions to debug)

It is an error to use a section registered as allowdefinition='MachineOnly'

It is an error to use a section registered as allowdefinition='MachineOnly'  beyond machine.config

When I try to run my application I get the following parser error :
Parser Error Message: It is an error to use a section registered as allowdefinition='MachineOnly' beyond machine.config.

The Pure ASP.NET Upload extension adds an entry to the web.config file. Unfortunately, this entry can only be used when you remove an attribute in the machine.config file, that is located in your windows dir\Microsoft.NET\Framework\version\CONFIG directory. Locate the following line :
<section name="processModel" type="System.Web.Configuration.ProcessModelConfigurationHandler, System.Web, version="1".0.3300.0, Culture=neutral, publickeytoken="b03f5f7f11d50a3a"" allowdefinition="MachineOnly"/>

and delete the allowDefinition attribute.

Formatting Date in GridView

<asp:BoundField DataField="ContractRecvd" DataFormatString="{0:dd/MM/yyyy}" HeaderText="Date of Contract Received"
                                    SortExpression="ContractRecvd" HtmlEncode="False" ItemStyle-Wrap="false" />

Enabling the Read-only property of HTML textbox

txtDrugName.Attributes.Remove("readonly")

Storing the hidden value available in the parent form from the child window

Response.Write("<script>window.opener.document.getElementById('hdnsno').value ='" + sno + "';window.opener.document.form1.submit();window.close();</script>")

Redirecting to the Root Path

Simply prefix the path with the ~ (tilda) character.  During the compilation process of the server-side control, ASP.NET will translate that ~ into Request.ApplicationPath.

Windows Authentication Connection String

Windows Authentication Connection String
---------------------------------------------
<add key="connstring" value="Data Source=TAKE7;Initial Catalog=SPPFU2;Integrated Security=True"/>

SQL Authentication Connection String
---------------------------------------
<add key="connstring" value="Data Source=takedev10;Initial Catalog=SPFU2;Persist Security Info=True;User ID=sa;Password=sa123"/>

how to enable the break point

<compilation debug="true" strict="false" explicit="true">

Printing the web page to the printer

 <style type="text/css" media="print">
    .PrintButton
    {
     display:none;   
    }
</style>

<asp:Button ID="butPrintTop" runat="server" Text="Print" CssClass="buttonStyle PrintButton" OnClientClick="window.print();" />

Removing the header from the Web Page
 To disable this, you can simply change the Header & Footer options in Internet Explorer. While in IE, click on File > Page Setup, and locate the Header & Footer fields. You may see text such as:
"&w&bPage &p of &P" or "&u&b&d"


Removing the header from the web page using code - Think twice before you implement this code

http://geekswithblogs.net/narent/archive/2007/05/14/112479.aspx

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim pageKey As RegistryKey = Registry.CurrentUser.OpenSubKey("software\microsoft\internet explorer\pagesetup", True)

Dim newFooter As String = "&b&D&b&T"

Dim curFooter As Object = pageKey.GetValue("footer")

pageKey.SetValue("footerTemp", curFooter)

pageKey.SetValue("footer", newFooter)

pageKey.Close()

End Sub


Dim pageKey As RegistryKey = Registry.CurrentUser.OpenSubKey("software\microsoft\internet explorer\pagesetup", True)

Dim oriFooter As Object = pageKey.GetValue("footerTemp")

pageKey.SetValue("footer", oriFooter)

pageKey.DeleteValue("footerTemp")

pageKey.Close()


ClientScript.RegisterStartupScript(Me.GetType, "error", "<script language='Javascript'>window.close();</script>")


You can use any of IE's header and footer codes in your custom code as well:


&w Window title

&u Page address (URL)

&d Date in short format specified by Regional Settings in Control Panel

&D Date in long format specified by Regional Settings in Control Panel

&t Time in the format specified by Regional Settings in Control Panel

&T Time in 24-hour format

&p Current page number

&P Total number of pages

&& A single ampersand (&)

&b The text immediately following these characters as centered

&b&b The text immediately following the first "&b" as centered, and the text following the second "&b" as right-justified

Setting the Border Style for textbox in code behind

txtStrength.Style.Add(HtmlTextWriterStyle.BorderStyle, value)

where value = "None", "Solid"

Refreshing the parent page from the child pop up window

Dim script As String = "<script language='JavaScript'>"
 script = script + "window.opener.document.forms(0).submit(); </script>"

 If Not Page.ClientScript.IsClientScriptBlockRegistered("popup") Then
      Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "popup", script)
   End If

Displaying the PDF file in Asp.net

 <iframe runat="server" id="PDFViwer" width="95%" height="500px" scrolling="auto"></iframe>
PDFViwer.Attributes.Add("src", rptPath + "/" + pono + ".pdf")

Displaying pop-up box

System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=""JavaScript"">" & vbCrLf)
 System.Web.HttpContext.Current.Response.Write("alert(""" & msg & """)" & vbCrLf)
 System.Web.HttpContext.Current.Response.Write("</SCRIPT>")

Fixed Header for GridView


.gvFixedHeader
{       
    position:relative;
    top:expression(this.offsetParent.scrollTop);       

}

Header Style - CSSClass="gvFixedHeader"

Displaying the text instead of the empty string in the gridview

NullDisplayText="NA" ConvertEmptyStringToNull="true"

SelectedChangeEvent for dropdownlist

   <asp:DropDownList ID="ddlValue" runat="server"  CssClass="ddl"
                                                                            Width="325px" TabIndex="1" onchange="ResetValue();">
                                                                        </asp:DropDownList>


 function ResetValue()
    {   
    var txtValue = document.getElementById('<%=txtValue.ClientID%>');
    txtValue.value = '';  
    }

   

Formatting to two decimal places / trailing spaces in EVAL using gridview

<%# Eval("InvoiceValue","{0:0.00}") %>'>
<%# Eval("InvoiceValue","{0:N2}") %>'>

<asp:TemplateField HeaderText="Total Value of Invoice">
                                <ItemTemplate>
                                    <%#CType(DataBinder.Eval(Container, "DataItem.TotalValue"), Decimal).ToString("0.00")%>
                                </ItemTemplate>
                            </asp:TemplateField>

Iframe with dynamic load of pages

[aspx]
<iframe id="iframeResult" runat="Server" scrolling="auto" width="1003" height="425px"
                                                frameborder="0" TabIndex="5"></iframe>


[vb]
iframeResult.Attributes("src") = url

Finding the hostname using asp.net 2.0

Request.UrlReferrer.Host
Request.UserHostName

Creating a footer template and displaying the total in the gridview

Creating a footer template and displaying the total in the gridview
----------------------------------------------------------------------

in the gridview column tag adding the following

  <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Invoice Date" FooterStyle-HorizontalAlign="right">
                                <ItemTemplate>
                                    <asp:Label ID="lblInvoiceDate" runat="server" Text='<%# Eval("InvoiceDate") %>'></asp:Label>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:Label ID="lblTotalText" Font-Bold="true" runat="Server" Text="Total :"></asp:Label>
                                </FooterTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField ItemStyle-HorizontalAlign="Right" HeaderText="Invoice Value" FooterStyle-HorizontalAlign="right">
                                <ItemTemplate>
                                    <asp:Label ID="lblInvoiceDate" Font-Bold="true" runat="server" Text='<%# Eval("InvoiceValue","{0:0.00}") %>'></asp:Label>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:Label ID="lblTotal" runat="Server" Text="Total :" Font-Bold="true"></asp:Label>
                                </FooterTemplate>
                            </asp:TemplateField>



If (e.Row.RowType = DataControlRowType.Footer) Then

                'display the total in the footer
                Dim lblTotal As Label = CType(e.Row.FindControl("lblTotal"), Label)

                Dim dbObj As New dbutil()
                Dim qryFmt As String = "SELECT SUM(FFGrandTotal) AS InvoiceValue FROM TTINVVIEW WHERE  FFJONO='{0}'"
                Dim qry As String = String.Format(qryFmt, Request.QueryString("Value"))

                lblTotal.Text = Decimal.Parse(dbObj.ExecuteScalar(qry), Globalization.NumberStyles.AllowDecimalPoint).ToString("0.00")

 End If

Adding multiple rows Rows in the Grid View

Adding multiple rows Rows in the Grid View
 
Row 1

 If (e.Row.RowType = DataControlRowType.Header) Then

                Dim oGridView As GridView = DirectCast(sender, GridView)

                'Add Query
                Dim oGridViewRow As New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)
                Dim oTableCell As New TableCell()

                oTableCell.ColumnSpan = 3
                oTableCell.Text = "Query : " & Request.QueryString("Query")

                oGridViewRow.BorderColor = Drawing.Color.Black
                oGridViewRow.BackColor = Drawing.Color.Gray
                oGridViewRow.ForeColor = Drawing.Color.Black
                oGridViewRow.HorizontalAlign = HorizontalAlign.Left

                oGridViewRow.Cells.Add(oTableCell)
                oGridView.Controls(0).Controls.AddAt(0, oGridViewRow)

Row 2

                'Add Value
                oGridViewRow = New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)
                oTableCell = New TableCell()

                oTableCell.Text = "Value : " & Request.QueryString("Value")
                oTableCell.ColumnSpan = 3

                oGridViewRow.BorderColor = Drawing.Color.Black
                oGridViewRow.BackColor = Drawing.Color.Gray
                oGridViewRow.ForeColor = Drawing.Color.Black
                oGridViewRow.HorizontalAlign = HorizontalAlign.Left

                oGridViewRow.Cells.Add(oTableCell)
                oGridView.Controls(0).Controls.AddAt(1, oGridViewRow)

Row 3

                'Add Track List
                oGridViewRow = New GridViewRow(0, 1, DataControlRowType.Header, DataControlRowState.Insert)
                oTableCell = New TableCell()

                oTableCell.Text = "Track List : " & Request.QueryString("TrackList")
                oTableCell.ColumnSpan = 3

                oGridViewRow.BorderColor = Drawing.Color.Black
                oGridViewRow.BackColor = Drawing.Color.Gray
                oGridViewRow.ForeColor = Drawing.Color.Black
                oGridViewRow.BorderColor = Drawing.Color.Black
                oGridViewRow.HorizontalAlign = HorizontalAlign.Left

                oGridViewRow.Cells.Add(oTableCell)
                oGridView.Controls(0).Controls.AddAt(2, oGridViewRow)

            End If

Creating Global file in asp.net 2.0

Creating Global file in asp.net 2.0
-------------------------------------
Public Class _Global [User Defined name]
    Inherits HttpApplication

In Global.asax file
-------------------
Inherits="_Global"

Creating the connection string in web.config and accessing in asp.net 2.0

<add connectionString ="server=TAKEPOC;user id=sa;password=sa;database=TRTE" name ="CTL" providerName ="System.Data.SqlClient"/>

ConfigurationManager.ConnectionStrings("CTL").ToString()

Embedding the CSS style sheet in asp.net 2.0

<link rel="stylesheet" href="../StyleSheets/StyleSheet.css" type="text/css" /></head>

Adding a column to the datatable

dt.Columns.Add(New DataColumn("IsEdit", System.Type.GetType("System.Int16")))

disabling copy/cut/paste in textbox

Properties: oncopy, onpaste, oncut.


  <asp:TextBox ID="txtSearchTitle" runat="server"  oncopy="return false" onpaste="return false" oncut="return false"></asp:TextBox>

Tuesday, May 10, 2011

Selenium??

What is Selenium ??
Selenium is a robust set of tools that supports rapid development of test automation for web-based applications. 

Can simulate a user navigating through pages and then assert for specific marks on the pages.

Selenium IDE is a plug-in to Firefox to record and playback tests (like WinRunner, QTP).

You can then export the recorded test in most language e.g. HTML, Java , .NET , Perl , Ruby etc.

The exported test can be run in any browser and any platform using "selenium remote control or Selenium RC".

1) Begin: write and run tests in Firefox.
Selenium IDE is a Firefox add-on that records clicks, typing, and other actions to make a test, which you can play back in the browser.

2) Customize: your language, your browser.
Selenium Remote Control (RC) runs your tests in multiple browsers and platforms. Tweak your tests in your preferred language.

3) Deploy: scale out, speed up
Selenium Grid extends Selenium RC to distribute your tests across multiple servers, saving you time by running tests in parallel.

Selenium-Grid allows the Selenium-RC solution to scale for test suites or test suites to be run in multiple environments.

  With Selenium-Grid multiple instances of Selenium-RC are running on various operating system and browser configurations, each of these when launching register with a hub. When tests are sent to the hub they are then redirected to an available Selenium-RC, which will launch the browser and run the test.

  This allows for running tests in parallel, with the entire test suite theoretically taking only as long to run as the longest individual test.

Command Overview in Selenium IDE:
1. ClickAndWait - Redirection URL.
2. Click followed by pause - Redirection within the page. (visible true or false with the help of the controls, pause is in the form of milliseconds, usually 5000 millseconds is used to represent 5 minutes)

Capcha In ASP.NET??

What is capcha??

A CAPTCHA  is a type of challenge-response test used in computing as an attempt to ensure that the response is not generated by a computer. The process usually involves one computer (a server) asking a user to complete a simple test which the computer is able to generate and grade. Because other computers are supposedly unable to solve the CAPTCHA, any user entering a correct solution is presumed to be human.

How to implement in ASP.NET?

Step 1: In the page add the following:
<%@ Register Assembly="WebControlCaptcha" Namespace="WebControlCaptcha" TagPrefix="Capcha" %>

<div style="width: 230px;" class="greenContainer">
                            
<Capcha:CaptchaControl id="capcha" enableviewstate="false" enabletheming="false"
 captchamaxtimeout="300" runat="server" layoutstyle="Vertical" cssclass="fL" />
 
</div>


Step 2: Add the following css

.greenContainer
{border:1px solid #6a377d;background-color:#f7f2f9;overflow:auto;padding:10px;}


Step 3: In the Save button
The save operation should be done only within

if (Page.IsValid)
{}

 Step 4: Add the following in the web.config file.

<system.web>
<httpHandlers>
<add verb="GET" path="CaptchaImage.aspx" type="WebControlCaptcha.CaptchaImageHandler, WebControlCaptcha"/>
</httpHandlers>
</system.web>

This should be included after </system.web> and before <system.webServer> if exists

Also include the pages where the capcha is implemented (eg. Registration Page, Subscription)

 <location path="Subscription.aspx">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>

 <location path="Registration.aspx">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>

<location path="CaptchaImage.aspx">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>

Add the dll  WebControlCapcha.dll

Fixes:
If you are using IIS 7.0 then your capcha image wont display in that case do the following

Go Handler Mapping in IIS 7.0 for your application configured in IIS 7.0

Opening the Handler Mappings, the listing for all file extensions registered with various handlers was displayed, so this was the right place. However as I looked for an "Add new file mapping" option, I instead found three options
1. Add Managed Handler...
2. Add Script Map...
3. Add Module Mapping...
The Add Managed Handler is the thing that we need to work with.Back to adding managed handlers for Capcha give the parameters as below and save the parameters.
 Thatz it we have the capcha in place.

Manage Handler


 

Monday, May 9, 2011

How to restore a database when the database is in use??

Usually when we are restoring the database in the server.. when the database is in use it will throw the pop up error the database is in use. So inorder to fix that pop up error, do the following..

ALTER DATABASE <DBNAME> 
SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE

Wednesday, May 4, 2011

Transliteration for Facebook

http://www.google.co.in/transliterate/indic/Tamil