Wednesday, October 22, 2008

Remove a HTML Element using Javascript

3 comments
Suppose the ID of the element is "objID"

The JavaScript method.(We are writing a custom function)



function removeElement(objID) {
var node = document.getElementById(objID);
node.parentNode.removeChild(node);
}



The JQuery method.



$("#objID").remove();



Its all about Keeping it Simple.
What do you say? :)
Read more...

Thursday, October 16, 2008

Copy DataRows from one DataTable to Another

0 comments
"This row already belongs to another table" - Annoying, to say the least!

The workaround, simple but elusive.



public DataTable CopyDataTable(DataTable dtSource, int iRowsNeeded)
{

if (dtSource.Rows.Count > iRowsNeeded)
{
// cloned to get the structure of source
DataTable dtDestination = dtSource.Clone();
for (int i = 0; i < iRowsNeeded; i++)
{
dtDestination.ImportRow(dtSource.Rows[i]);
}
return dtDestination;
}
else
return dtSource;
}



Happy Coding!
Read more...

Monday, September 29, 2008

JQuery Time

0 comments
jQuery is a lightweight open source JavaScript library developed
under the management of John Resig .
For those ASP.NET Developers who dont know jQuery, its seriously DO or DIE
For those who think jQuery is totally needless, its time to rethink.

Because
Scott Guthrie
(You ought to know the him!) yesterday announced that


Microsoft Microsoft will be shipping jQuery with Visual Studio going forward....
.................................................................................
Going forward we'll use jQuery as one of the libraries used to implement higher-level
controls in the ASP.NET AJAX Control Toolkit, as well as to implement new
Ajax server-side helper methods for ASP.NET MVC.
New features we add to ASP.NET AJAX (like the new client template support)
will be designed to integrate nicely with jQuery as well.


Heres the corresponding entry in the jQuery Team Blog

So its time to start taking jQuery a lot more seriously. [:)]

For starters:

1. The book "jQuery in Action".
Order from IndiaPlaza (Click Here)
2. A superb introductory article by Rick Strahl. (Click Here)
3. Another good article by Scott HanselMan.(Click Here)
4. Last but by no means the least Tutorials from the jQuery Team. (Click Here)

Read more...

DateTime Format Strings

0 comments
Been googling about common DateTime format strings.
Surprisingly, very few relevant ones came up.
So decided to make a post of the formats I got for future reference



DateTime.Now; //5/16/2006 1:05:13 AM
DateTime.Now.ToString(); //5/16/2006 1:05:13 AM
DateTime.Now.ToShortTimeString() //11:40 AM
DateTime.Now.ToShortDateString() //5/16/2006
DateTime.Now.ToLongTimeString() //11:40:13 AM
DateTime.Now.ToLongDateString() //Tuesday, May 16, 2006



Examples of DateTime for Given Formats



DateTime.Now.ToString("dddd, MMMM dd yyyy") // Tuesday, May 16 2006
DateTime.Now.ToString("ddd, MMM d "'"yy") // Tue, May 16 '06
DateTime.Now.ToString("dddd, MMMM dd") // Tuesday, May 16
DateTime.Now.ToString("M/yy") // 5/06
DateTime.Now.ToString("dd-MM-yy") // 16-05-06



Courtesy : An article from DOTNET Spider
Read more...

Thursday, August 28, 2008

Check if a URL actually exists

0 comments
We have seen many validations for URLs.
But what to do if the requirement is like to check whether a URL is in the NET.
In other words, how can one knows the URL given has not returned a 404 error?

Here's the code



/// <summary>
/// Checks the status of the specified URL.
/// </summary>
/// <param name="strURL">The URL that needs to be checked</param>
/// <returns>True if the URL exists</returns>

public bool IsURLValid(string strURL)
{
string strResponse = "";
try
{
string pattern = @"((http|ftp|https):\/\/w{3}[\d]*.|(http|ftp|https):\/\/|w{3}[\d]*.)([\w\d\._\-#\(\)\[\]\\,;:]+@[\w\d\._\-#\(\)\[\]\\,;:])?([a-z0-9]+.)*[a-z\-0-9]+.([a-z]{2,3})?[a-z]{2,6}(:[0-9]+)?(\/[\/a-z0-9\._\-,]+)*[a-z0-9\-_\.\s\%]+(\?[a-z0-9=%&\.\-,#]+)?";
//validatng url in case if it hasn't been validated earlier
if(Regex.IsMatch(strURL,pattern))
{
WebRequest request = HttpWebRequest.Create(strURL);
request.Timeout = 5000;
strResponse = ((HttpWebResponse)request.GetResponse()).StatusCode.ToString();
}
}
catch(Exception exp)
{
strResponse = "";
}
return (strResponse=="OK")? true: false;
}



Does the work, but not very classy.
Any better ideas?
Read more...

Saturday, August 16, 2008

The Coalesce Operator (The ?? Operator in C#)e

3 comments
The Conventional Way
if (obj1 != null)
{
objOut = obj1;
}
else
{
objOut = obj2;
}

The Ternary Operator
objOut = (obj1 != null) ? obj1 : obj2;


The Coalesce Operator Way
objOut = obj1 ?? obj2;


The Extended Coalesce Operator

The Conventional Way
if (obj1 != null)
{
return obj1;
}
else if (obj2 != null)
{
return obj2;
}
else if (obj3 != null)
{
return obj3;
}
else
{
return null;
}

The Coalesce Operator Way
return obj1 ?? obj2 ?? obj3;


As a useful replacement to the Ternary Operator

The Ternary Operator Way
obj = (obj != null)? obj : objNew;

The Coalesce Operator Way
obj = obj ?? objNew;


Then why is not used more? I think cos its got a tough name.[:)]
How do you pronounce it?

I LOVE C#
Read more...

Resolving W3C Validation Issues

1 comments
For those who are wondering why should one bother with W3C Validations,
please read Why should we Validate our WebSites?

When validating your website using W3C some weird errors might occur

An Example is


there is no attribute "border"



even if you haven't given the border attribute

The Reason


The ASP.NET engines sees the W3C validator as down-level browser and renders
non-XHTML compliant code. Your code is most likely fine. The problem is with
ASP.NET.




The Solution(Step Wise)


1.Right Click on your Solution Explorer
2.Click on Add ASP.NET Folder ---> App_Browsers
3.Now Click on App_Browsers ---> Add New Item
4.A dialog Box now pops up with some Visual Studio Installed Templates.
Select the Browser File Template from there, change the name as W3CValidations.browser(any other convenient name also) and Click on the Add Button
5.Delete the whole XML MarkUp code inside the W3CValidations.browser
6.Place the following code instead



<browsers>
<!--
Browser capability file for the w3c validator

sample UA: "W3C_Validator/1.305.2.148 libwww-perl/5.803"
-->
<browser id="w3cValidator" parentID="default">
<identification>
<userAgent match="^W3C_Validator" />
</identification>

<capture>
<userAgent match="^W3C_Validator/(?'version'(?'major'\d+)(?'minor'\.\d+)\w*).*" />
</capture>

<capabilities>
<capability name="browser" value="w3cValidator" />
<capability name="majorversion" value="${major}" />
<capability name="minorversion" value="${minor}" />
<capability name="version" value="${version}" />
<capability name="w3cdomversion" value="1.0" />
<capability name="xml" value="true" />
<capability name="tagWriter" value="System.Web.UI.HtmlTextWriter" />
</capabilities>
</browser>
</browsers>



7.Now upload this Folder and File to your Hosting Service
8.Re Validate using W3C Validator
9.Bingo! You got a Clean Validation Certificate.
10. Show off the Validation Certificate to all those who cares [:)]

Courtesy

Link at DigitalColony.com

Link at idunno.org


Happy Coding!
Read more...

Friday, August 8, 2008

Nested GridView with Paging for Child Grid

1 comments
I have a post called Nested GridView using JavaScript in this same blog.

A guy at ASP.NET Forums asked how to implement paging for the child grid and this is what made me make a post on this.

Just change the ASPX.CS like this.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            BindGridToDS(GridView1.DataKeys[e.Row.RowIndex].Value.ToString(), (GridView)e.Row.FindControl("GridView2"));
        }
    }


    protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView gvwChild = ((GridView)sender);
        GridViewRow gvRowParent = ((GridView)sender).Parent.Parent as GridViewRow;

        gvwChild.PageIndex = e.NewPageIndex;
        BindGridToDS(GridView1.DataKeys[gvRowParent.RowIndex].Value.ToString(), gvwChild);

        //show the div again after postback
        string strDIVID = "div" + GridView1.DataKeys[gvRowParent.RowIndex].Value.ToString();
        string cScript = "";
        ClientScript.RegisterStartupScript(typeof(Page), "clientscript", cScript);
    }

    private void BindGridToDS(string strCustomerID, GridView gv)
    {
        SqlDataSource dbSrc = new SqlDataSource();
        dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings["NorthWind"].ConnectionString;
        dbSrc.SelectCommand = "SELECT * FROM Orders WHERE CustomerID = '" + strCustomerID + "' ORDER BY OrderDate";
        gv.DataSource = dbSrc;
        gv.DataBind();
    }



Happy Coding!
Read more...

Tuesday, August 5, 2008

Display Images stored as Image in GridView

0 comments
Suppose we have a table in DB named "Images"
The data inside it are



img_id(int) ---> the id of the image
img_name(varchar(50)) ---> the name given to image
img_data(image) ---> the image stored as bit array
img_contenttype(varchar(20)) ---> like image/png, image/jpeg and all





Our requirement is to show the images in a GridView

Here's the ASPX

<asp:GridView ID="gvwImages" runat="server" 
AutoGenerateColumns="false" 
DataSourceID="dsImages">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%--field img_name is the name given to image--%>
<asp:Label ID="lblName" runat="server" 
Text='<%#Eval("img_name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<%--here field img_id is the id of the image--%>
<asp:Image ID="Image1" runat="server" 
ImageUrl='<%# "Handler.ashx?id=" + Eval("img_id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="dsImages" runat="server" 
ConnectionString='<%$ConnectionStrings: your conn string %>'
SelectCommand="Select img_id,img_name from Images">
</asp:SqlDataSource>




Here inside ImageUrl we have given Handler.ashx.
Since we dont have one, create one.
Go to Add New Item. select Generic Handler and click OK.

Inside the Handler.ashx, paste this code

using System;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public class Handler : IHttpHandler
{

public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginCon"].ConnectionString);
myConnection.Open();
//here field img_data is the content of the image (type image in DB)
//field img_contenttype is the type of the image (optional)
string sql = "Select img_data,img_contenttype from Images where img_id=@ImageId";
SqlCommand cmd = new SqlCommand(sql, myConnection);
cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = context.Request.QueryString["id"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.ContentType = dr["img_contenttype"].ToString();
context.Response.BinaryWrite((byte[])dr["img_data"]);
}

}



Simple enough right?

Now if you wanna test it do it using Northwind DB.
Take the "Employees" table inside it and try to diplay the field "Photo"
10 out of 10, it wont work in your Page. [:)]
Suprised?
The reason is that the images stored in Northwind DB has OLE Header.
The header length is invariably 78 bytes.
So if we remove the first 78 bytes we can view images from Northwind too.

Here goes the special Handler.ashx for Northwind DB.(Table used ---> Employees)

using System;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public class Handler : IHttpHandler
{

public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString);
sqlConnection.Open();
string sql = " Select Photo from Employees where EmployeeID=@EmpId";
SqlCommand cmd = new SqlCommand(sql, sqlConnection);
cmd.Parameters.Add("@EmpId", SqlDbType.Int).Value = context.Request.QueryString["id"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
// Output the binary data
// But first we need to strip out the OLE header
byte[] thePicture = (byte[])dr["Photo"];
const int OleHeaderLength = 78;
int strippedImageLength = thePicture.Length - OleHeaderLength;
byte[] strippedImageData = new byte[strippedImageLength];
Array.Copy(thePicture, OleHeaderLength, strippedImageData, 0, strippedImageLength);
context.Response.BinaryWrite(strippedImageData);
// context.Response.BinaryWrite((byte[])dr["Photo"]);
}

}




Happy Coding!
Read more...

Saturday, July 26, 2008

Paging in ListView

5 comments
Paging in ListView is pretty different from Paging in GridView.
We page data on a ListView using DataPager.
Its a joyful ride that has so many features we have dreamed of
ListView with Top and Bottom Pagers attached to it
Paging in GridView is with a twist and not an extension of gridview paging.
It uses the ListView event for Paging called
"OnPagePropertiesChanging"

Here is an example of doing it using two datapagers so that paging gets displayed
both on top and bottom of the page (google serach page style)
As used at almost all my examples, the database Northwind is used.

In ASPX

The Top Pager

<asp:UpdatePanel ID="updPanel" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <div class="pager">
            <asp:DataPager ID="pgrTopDetails" runat="server"
                    PageSize="10"
                    PagedControlID="ListView1">
                <Fields>
                    <asp:NextPreviousPagerField ButtonCssClass="command"
                                        PreviousPageText="Previous"
                                        RenderDisabledButtonsAsLabels="true"
                                        RenderNonBreakingSpacesBetweenControls="true"
                                        ShowFirstPageButton="false"
                                        ShowNextPageButton="false"
                                        ShowLastPageButton="false"
                                        ShowPreviousPageButton="true"/>
                    <asp:NumericPagerField ButtonCount="10"
                                        NumericButtonCssClass="command" 
                                        CurrentPageLabelCssClass="current" 
                                        NextPreviousButtonCssClass="command"
                                        RenderNonBreakingSpacesBetweenControls="true"/> 
                    <asp:NextPreviousPagerField ButtonCssClass="command"
                                        NextPageText="Next"
                                        RenderDisabledButtonsAsLabels="true"
                                        ShowFirstPageButton="false"
                                        ShowPreviousPageButton="false"
                                        ShowNextPageButton="true"
                                        ShowLastPageButton="false" />
                </Fields>
            </asp:DataPager>
        </div>
        <asp:ListView ID="ListView1" runat="server"
                    DataKeyNames="ProductID"
                    OnPagePropertiesChanging="ListView1_PagePropertiesChanging">
            <LayoutTemplate>
                <table class="datatable">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Quantity</th>
                        <th>Unit Price</th>
                        <th>In Stock</th>
                        <th>On Order</th>
                    </tr>
                    <tr id="itemPlaceholder" runat="server"></tr>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr class="row">
                    <td><%# Eval("ProductID") %></td>
                    <td><%# Eval("ProductName") %></td>
                    <td><%# Eval("QuantityPerUnit") %></td>
                    <td><%# Eval("UnitPrice") %></td>
                    <td><%# Eval("UnitsInStock") %></td>
                    <td><%# Eval("UnitsOnOrder") %></td>
                </tr>
            </ItemTemplate>
        </asp:ListView>
        <div class="pager">
            <asp:DataPager ID="pgrBottomDetails" runat="server"
                        PageSize="10"
                        PagedControlID="ListView1">
                <Fields>
                    <asp:NextPreviousPagerField ButtonCssClass="command"
                                        PreviousPageText="Previous"
                                        RenderDisabledButtonsAsLabels="true"
                                        RenderNonBreakingSpacesBetweenControls="true"
                                        ShowFirstPageButton="false"
                                        ShowNextPageButton="false"
                                        ShowLastPageButton="false"
                                        ShowPreviousPageButton="true"/>
                    <asp:NumericPagerField ButtonCount="10"
                                        NumericButtonCssClass="command" 
                                        CurrentPageLabelCssClass="current" 
                                        NextPreviousButtonCssClass="command"
                                        RenderNonBreakingSpacesBetweenControls="true"/> 
                    <asp:NextPreviousPagerField ButtonCssClass="command"
                                        NextPageText="Next"
                                        RenderDisabledButtonsAsLabels="true"
                                        ShowFirstPageButton="false"
                                        ShowPreviousPageButton="false"
                                        ShowNextPageButton="true"
                                        ShowLastPageButton="false" />
                    <asp:TemplatePagerField>
                        <PagerTemplate>
                            <br />
                            Displaying&nbsp;<%# Container.StartRowIndex + 1 %>&nbsp;to&nbsp;
                            <%# Container.StartRowIndex + Container.PageSize %>&nbsp;of&nbsp;
                            (<strong><%# Container.TotalRowCount%></strong>) Profiles Found.
                        </PagerTemplate>
                    </asp:TemplatePagerField>
                </Fields>
            </asp:DataPager>
        </div>                             
    </ContentTemplate>
</asp:UpdatePanel>



In ASPX.CS

private static NorthwindClassesDataContext database;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        database = new NorthwindClassesDataContext(ConfigurationManager
                        .ConnectionStrings["NorthwindConnectionString"]
                        .ConnectionString);
        BindListView();
    }
}
protected void ListView1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
    this.pgrTopDetails.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
    this.pgrBottomDetails.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
    //custom function to bind your listview
    BindListView();
}

private void BindListView()
{
    ListView1.DataSource = database.Products.OrderBy(p => p.ProductID);
    ListView1.DataBind();
}


Download Source Code(16kb)

Simple enough, right?
Happy Coding!

P.S: The above shown style is a shameless port of gridview style by Matt Berseth.

He is a wonderful coder with so many superb wonders done on DataPresentation Controls at .NET
Read more...

Thursday, July 17, 2008

Nested GridView

6 comments
Sometimes there will be tables in databases corresponding to another ones
Suppose we have a table named Customer and another named Orders(made by each customer)
In that case it will be better to use Nested GridView.
Here we are making it a little fancier using Javascript.

Here is a ScreenShot of the Nested GridView



Prequisites

1.Create a folder in your project called "Images" and put two images
arrowright.jpg and arrowdown.jpg which are arrows pointing to the defined directions.

2.Create a ConnectionString named "NorthWindConnectionString" in the web.config pointing to the Northwind DB in your system

In ASPX Page
<asp:GridView ID="GridView1" runat="server"
AllowPaging="True"
AutoGenerateColumns="False"
DataKeyNames="CustomerID"
DataSourceID="SqlDataSource1"
PageSize="20"
OnRowDataBound="GridView1_RowDataBound" 
CellPadding="4" 
ForeColor="#333333" 
GridLines="None">

<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />


<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="javascript:ShowChildGrid('div<%# Eval("CustomerID") %>');">
<img id="imgdiv<%# Eval("CustomerID") %>" 
alt="Click to show/hide orders" 
border="0" 
src="Images/arrowright.jpg"/>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
<asp:TemplateField>
<ItemTemplate>
</td>
</tr>
<tr>
<td colspan="100%">
<div id="div<%# Eval("CustomerID") %>" style="display:none;position:relative;left:25px;" >
<asp:GridView ID="GridView2" runat="server"
AutoGenerateColumns="false"
DataKeyNames="OrderID"
EmptyDataText="No orders for this customer."
Width="80%" 
CellPadding="4" 
ForeColor="#333333" 
GridLines="None">
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="OrderDate" HeaderText="Order Date" DataFormatString="{0:MMM-dd-yyyy}" HtmlEncode="False" />
<asp:BoundField DataField="ShippedDate" HeaderText="Shipped Date" DataFormatString="{0:MMM-dd-yyyy}" HtmlEncode="False" />
<asp:BoundField DataField="ShipCity" HeaderText="Shipped To" />
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>        
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:NorthWindConnectionString %>"
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City], [PostalCode], [Phone] FROM [Customers]">
</asp:SqlDataSource>


In ASPX.CS Page

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
GridView gv = (GridView)e.Row.FindControl("GridView2");
SqlDataSource dbSrc = new SqlDataSource();
dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ConnectionString;
dbSrc.SelectCommand = "SELECT * FROM Orders WHERE CustomerID = '" + GridView1.DataKeys[e.Row.RowIndex].Value + "' ORDER BY OrderDate";
gv.DataSource = dbSrc;
gv.DataBind();
}
}


Put this JavaScript in the header of your ASPX Page


function ShowChildGrid(obj)
{
var div = document.getElementById(obj);
var img = document.getElementById('img' + obj);
var theFlag = div.style.display == "none";
div.style.display = (theFlag) ? "inline" : "none";
img.src = (theFlag) ? "Images/arrowdown.jpg" : "Images/arrowright.jpg";
}


Happy Coding!
Read more...

Trim(Remove Spaces) using JavaScript

0 comments
Here is a simple JS function to trim the outer spaces inside a string.
Mainly used while validating User Inputs.

These are the three methods that we normally use

Method 1

Write a TrimString function using regular expression and call it when needed.

function TrimString(stringToTrim){
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}

Now call it like

 var trimmedString = TrimString("    string to be trimmed         ");

If you alert trimmedString, you will get the value "string to be trimmed"

OR Method 2

If you want a more generic function for trimming, I would suggest taking a piece from Douglos Crockfords Remedial Javascript
Here we are extending the javascript String object with our own trim() function.
This is how we do that.
Declare the following prototype on the top of your page before any call to trim() occurs

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
    };
}

Now trim the string like

var str = "    string to be trimmed         ";
var trimmedString = str.trim();

OR Method 3

And if you are using jQuery, its much simpler.
jQuery natively has the trim() functionality and so just call it
No points for guessing that though! [:)]
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
var str = "    string to be trimmed         ";
var trimmedString = jQuery.trim(str);

Read more...

GridViewRow as Hyperlink

1 comments
This is a simple technique used in the RowDataBound event of a GridView so that its Entire Row acts as a HyperLink.
For Visual effects styles are applied at mouseover and mouseout.
The cursor is also given a hand like appearance to show the row is a hyperlink


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.color='DodgerBlue';this.style.cursor='hand';";
e.Row.Attributes["onmouseout"] = "this.style.color='Black';";
e.Row.Attributes["onclick"] = "window.navigate('NavigatedPage.aspx?id=" + e.Row.RowIndex + "')";
// can send anything as querystring
}
}

Read more...

Popup Style DIV using Javascript

8 comments
Update at November 10, 2010:

I am appalled by the numbers of visits this link is getting. Go through it just to understand how its basically done. But I suggest you dont use this code at all :)

Instead, use Malsup's Wonderful jQuery BlockUI Plugin : Demos are here


This sample is to create a pop-up using a DIV in the same page as passing values to and from the pop-up is easier

The Demo Pics are

Before Click



After Click



The CSS.

.opaqueLayer
{
display:none;
position:absolute;
top:0px;
left:0px;
opacity:0.6;
filter:alpha(opacity=60);
background-color: #000000;
z-Index:1000;
}

.questionLayer
{
position:absolute;
top:0px;
left:0px;
width:350px;
height:200px;
display:none;
z-Index:1001;
border:2px solid black;
background-color:#FFFFFF;
text-align:center;
vertical-align:middle;
padding:10px;
}

The Javascript.

function getBrowserHeight() {
var intH = 0;
var intW = 0;

if(typeof window.innerWidth == 'number' ) {
intH = window.innerHeight;
intW = window.innerWidth;
}
else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
intH = document.documentElement.clientHeight;
intW = document.documentElement.clientWidth;
}
else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
intH = document.body.clientHeight;
intW = document.body.clientWidth;
}
return { width: parseInt(intW), height: parseInt(intH) };
}

function setLayerPosition() {
var shadow = document.getElementById('shadow');
var question = document.getElementById('question');

var bws = getBrowserHeight();
shadow.style.width = bws.width + 'px';
shadow.style.height = bws.height + 'px';
question.style.left = parseInt((bws.width - 350) / 2)+ 'px';
question.style.top = parseInt((bws.height - 200) / 2)+ 'px';
shadow = null;
question = null;
}

function showLayer() {
setLayerPosition();

var shadow = document.getElementById('shadow');
var question = document.getElementById('question');

shadow.style.display = 'block';
question.style.display = 'block';

shadow = null;
question = null;
}

function hideLayer() {
var shadow = document.getElementById('shadow');
var question = document.getElementById('question');

shadow.style.display = 'none';
question.style.display = 'none';

shadow = null;
question = null;
}

window.onresize = setLayerPosition;


And now, the HTML itself



<div id="shadow" class="opaqueLayer"> </div>
<div id="question" class="questionLayer">
<br />
<br />
<br />
This is the Popup DIV
<br />
Put anything here, Textbox or Buttons 
<br />
<br />
<br />
<input type="button" onclick="hideLayer();" value="Close" />
</div>
<table style="margin-left:auto;margin-right:auto;">
<tr>
<td style="height:120px;">

</td>
</tr>
<tr>
<td>
<button onclick="showLayer();">Click Me to see the Popup DIV</button>
</td>
</tr>
</table>




Explanation

Here two other DIVS are placed in the page which are hidden at first.
When clicking on the Button they are rendered visible.
These two DIVs are having different Z-Indexes that makes them look like a Popup Window.

Happy Coding!
Read more...

Friday, May 30, 2008

Cant Set "Show Hidden Files" aka Removing AMVO.EXE

0 comments
Beware when Plugging USBs to another System.
You will get a nasty amvo.exe!

First I got a memory reference error as alert.
I didn't mind it then, why bother with a silly alert?

After few days I noticed problems like
  • Cannot set "show hidden files and folders" inside the Tools-->Folder Options-->View

  • Contaminating every USBs plugged into it.
As most of us do, I googled it.
They asked me to check whether amvo.exe is the culprit.

To check that I Run msconfig. In the "Startup" Tab I found amvo.exe (Details)
Bingo! Got the virus/malware!

Now how to remove it?

Again I googled it. (What will be life without Google?) [:)]
Saw some options at the Digital me 's Blog.
Since it was based on manipulations on Windows Registry, I opted not to go for it.
Was totally at sea, on what to do next.
Then I started reading Comments for the topic at the Digital me 's blog.
I came across a splendid method by Olalekan
Based on that some steps were formulated.

Login inside Windows as Administrator or with Administrator previleges.

Run cmd (Opens DOS Window)
Now type C: to get to the C Prompt inside the DOS
Type: taskkill /im explorer.exe /f (Ends the Process "Explorer.exe". Important since virus spreads through Explorer)
Type: cd %systemroot%\system32 (Accessing System32)
Type: del amvo* /f /q /as (Deleting every file starting with amvo)
Type: cd \ (Going to Root Directory)
Type: dir /ah (List Hidden Files)

Now the Virus will be listed as"blahblah.com".We should delete it.
Note: The virus can never use NTDETECT.com ( Deleting it will cause big time troubles for you)
Now delete the virus using
del blahblah.com autorun.inf /f /q /as (My amvo used something like "iw1eg.com")

The virus is disposed from C:/ .

Now its the turn of other drives.

Suppose you have C:/, D:/, E:/ in your system. Repeat these processes for each drive.
ie. inside cmd type: D:
Now we have reached D: prompt, repeat the steps mentioned above for it too.
Do the same for E:/ and F:/ (if there is one)

After deleting from all these drives, restart the explorer by typing "explorer.exe"

Now the prevention from future attacks

Disabling AutoPlay for all drives

Start > Run > gpedit.msc
Inside it go to --> Computer Configuration > Administrative Templates > System > Turn Off Autoplay --> Enable


Now if you wanna View hidden Files a small Change in Registry is required.

Start > Run > regedit

Inside it Set
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\
Windows\CurrentVersion\Explorer\Advanced\Folder\Hidden\SHOWALL
CheckedValue as 1


Thats all to it Guys! [:)]
Read more...