Sunday, February 26, 2012

How to add URL in favourites using ASP.NET and JavaScript

One another regular question in forum. This is a simple code which helps you to add URL in favourites. Here I have used both JavaScript and ASP.NET code.

I am giving two sample code here.

Method 1:

First we will add the current URL by opening Add URL pop up and allow the user to enter the favourites URL title.

//btnAddFavourites is the button name 
btnAddFavourites.Attributes.Add("OnClick", "window.external.AddFavorite(location.href, document.title); return true;");

Below is the pop up window sample,

image

Method 2:

In this method we will not take any input from user. We will add a simple JavaScript function and hard code both the URL and Title.

Add below JavaScrit just below your <head> opening tag,

<script language="javascript">
        function AddToFav()
        {
        bookmarkurl= "http://asheej.blogspot.com/";
        bookmarktitle="Good .NET Articles"
        if (document.all)
        window.external.AddFavorite(bookmarkurl,bookmarktitle)
        else if (window.sidebar) // firefox
        window.sidebar.addPanel(bookmarktitle, bookmarkurl, "");
        }
    </script>

Now we will call this function on button click,

//btnAddFavourites is the button name
btnAddFavourites.Attributes.Add("OnClick", "AddToFav(); return true;");

Just try this in your website.

Cheers Asheej!

Saturday, February 25, 2012

How to get max value from a varchar field in MS SQL

Here I am going to explain you how to get max value from a varchar field in MS SQL.

Below is the table we are going to use here,

CREATE TABLE [Customer]
(
    [CustomerID] [nvarchar](50) NOT NULL,
    [CustomerName] [nchar](10) NULL,
    [Address] [nvarchar](50) NULL,
  CONSTRAINT [pk_Cust_ID] PRIMARY KEY CLUSTERED 
  (
    [CustomerID] 
  )
)
GO

If you look at the table I have declared CustomerID as nvarchar data type which means we will have both numeric and alphanumeric values.

Now we will insert some sample data,

INSERT INTO [Customer] ([CustomerID] ,[CustomerName],[Address]) VALUES ('1','Name1','Address1')
INSERT INTO [Customer] ([CustomerID] ,[CustomerName],[Address]) VALUES ('2','Name2','Address2')
INSERT INTO [Customer] ([CustomerID] ,[CustomerName],[Address]) VALUES ('11','Name11','Address11')
INSERT INTO [Customer] ([CustomerID] ,[CustomerName],[Address]) VALUES ('2a','Name2a','Address2a')
INSERT INTO [Customer] ([CustomerID] ,[CustomerName],[Address]) VALUES ('1a','Name1a','Address1a')
INSERT INTO [Customer] ([CustomerID] ,[CustomerName],[Address]) VALUES ('21','Name21','Address21')
GO

In the above statement 21 is the highest value.

SELECT MAX(CAST(CustomerID AS Int)) as [Customer ID] FROM Customers
 
WHERE ISNUMERIC(CustomerID)=1  AND CustomerID LIKE '%[0-9]%'

When we execute above query all alphanumeric values in the field  will be ignored and the output will be 21.

Friday, February 24, 2012

Transaction in ASP.NET

I have seen many people asking questions in forum that how to use transaction in ASP.NET. Normally we do transaction from SQL. Here I am going to explain how to do the transaction from ASP.NET code behind.

Normally transaction will be used in the code where you do all your database operation.

Below is the sample code to show you how the code looks like when we use the transaction in ASP.NET code behind.

string strCon = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection SQLCon = new SqlConnection(strCon);
SQLCon.Open();
    SqlTransaction SQLTran = SQLCon.BeginTransaction("MyTrans");
    SqlCommand Cmd = new SqlCommand();
    Cmd.Transaction = SQLTran;
    Cmd.Connection = SQLCon;
    try
{
        Cmd.CommandText ="First SQL query to update/delete record";
        Cmd.ExecuteNonQuery();
        Cmd.CommandText ="Second SQL query to update/delete record";
        Cmd.ExecuteNonQuery();        
        SQLTran.Commit();
    }
    catch (Exception ex)
    {
    lblError.Text = "Error!! <br>+" + ex.Message.ToString();
        SQLTran.Rollback();
    }

In the code you would have noticed that roll back code is kept inside the catch block which means whole execution will be rolled back if there is an exception.

I hope now you are clear with the Transaction concept in ASP.NET

Thursday, February 23, 2012

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

" Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack" - This is one of the common error we see in forum where people request solution for it.

Below is a small explanation and resolution to resolve this issue,

This error normally occurs when we use Response.Redirect or Server.Transfer or Response.End in your code before completing the actual process the page was doing.

In this case what you have to do is

In place of Response.End you have to use HttpContext.Current.ApplicationInstance.CompleteRequest

and in place of Response.Redirect, use the Response.Redirect ("Paganame.aspx", false);

and in place of Server.Transfer, use the Server.Execute method

There is also a KB article related to this issue,
http://support.microsoft.com/kb/312629/EN-US/




Wednesday, February 1, 2012

Received winners of Star of the Year - 2011 Award from dotnetspider.com

Happy to inform you all the I have been selected as "Star of the Year for the year 2011" and given iPad2 as gift by www.dotnetspider.com.

Thank you all for the support and guidance especially to Tony John who is the founder and webmaster of dotnetspider.com

You may read the announcement here Star of the Year

Sunday, January 22, 2012

Can we have primary key and clustered index on same table with different field?

In this article I am going to explain what will happen if we try to create primary key on a table which is already having clustered index in it.

Also this article is the answer to the question "Can we have primary key and clustered index on same table with different field?"

Read my article from dotnetspider

Sliding Image using JQuery

Here I am going to explain you how you can make a sliding image in your web application using jQuery. There are many ways to implement this feature in your web application but Using jQuery it will be very easy and you don't need to use any timer control for sliding it automatically.

Sliding Image using JQuery.

Let's start with step by step.
First we will download the required jQuery Library for this purpose.
Below are the library names to be downloaded for this purpose and the respective URL for that,

1. jquery-1.6.4.min.js
2. jquery.easing.1.3.js
3. jquery.cycle.all.js

Now we will start the coding

First Open a simple web application using your visual studio.

Go to the webapplication root folder and create two folder named "Scripts" and "images" to save jQyery Library which we downloaded and to save the image we will be using in the application.

Copy all the 3 jQuery library in your "Scripts" folder and all the images in your "images" Folder.

Once this is done we will open our web application and copy below lines in your head section of the .aspx page.
<head runat="server">
<%--needs to download "jquery-1.6.4.min.js","jquery.easing.1.3.js" and jquery.cycle.all.js files from the net. Just search in google for this file directly --%>
    <script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.easing.1.3.js" type="text/javascript"></script>
    <script src="Scripts/jquery.cycle.all.js" type="text/javascript"></script>
    <title>Sample jQuery Sliding Image Application</title>
    <script type="text/javascript">
        jQuery(document).ready(function () 
        {
            if (jQuery('#SlideImages').length > 0) 
            {
                jQuery('#SlideImages').cycle(
                {
                    fx: 'curtainX', speed: 500, timeout: 5000, randomizeEffects: true, easing: 'easeInOutBounce',
                    next: '.NextSlide',prev: '.PrevSlide',pager: '#SlideStyleNav',cleartypeNoBg: true
                });
            }
        });
   </script>
   <%--Prev.png and Next.png are the two small buttons to navigate next and prev on click ImageCount.png is the image count we display at the bottom of the page.--%>
   <style type="text/css">
#SlideStyle{position:relative;width:400px;}
#SlideStyle .PrevSlide, #SlideStyle .NextSlide{display:block;position:absolute;width:40px;height:40px;top:150px;z-index:9999;text-decoration:none;}
#SlideStyle .PrevSlide{left:0;background:transparent url(images/Prev.png) no-repeat top left;}
#SlideStyle .NextSlide{right:0;background:transparent url(images/Next.png) no-repeat top left;}
#SlideStyleNav {position:absolute; bottom:0; z-index:9999;}
#SlideStyleNav a{background:transparent url(images/ImageCount.png) no-repeat 0 0 ; float:left; height:15px; overflow:hidden; text-decoration:none; text-indent:-1234px; width:16px;}
#SlideStyleNav a.activeSlide {background-position:-32px 0;}
#SlideImages{overflow: hidden; position: relative;}
</style>
</head>

Now in your body tag add below code.
<body>
    <form id="form1" runat="server">
<div id="SlideStyle">
    <div id="SlideImages">
    <%--Needs to add images in IMAGE folder, in this examle I have added 6 Images--%>
    <%--Image size can be changed depends on the size of image you are using, my code shrinks the image according to the size you are mentioning --%>
        <img src="images/1.jpg" alt="Image 1" width="400" height="300" />
        <img src="images/2.jpg" alt="Image 2" width="400" height="300" />
        <img src="images/3.jpg" alt="Image 3" width="400" height="300" />
        <img src="images/4.jpg" alt="Image 4" width="400" height="300" />
        <img src="images/5.jpg" alt="Image 5" width="400" height="300" />
        <img src="images/6.jpg" alt="Image 6" width="400" height="300" />
    </div>
    <a class="PrevSlide" href="#"> </a>
    <a class="NextSlide" href="#"> </a>
    <div id="SlideStyleNav"> </div>
</div>
    </form>
</body>
Below is the sample image you will get after creating this application.


In this code you may change the image name based on the images you are using. You don't need to worry about the size of the images as I am adjusting the size of the images to fit it into the space.

Below are the some of the fx: options you can try:

1. shuffle
2. Zoom
3. fade
4. turnDown
5. curtainX

Below are the some of the easing: options you can try:

1. easeOutBounce
2. easeInBounce
3. easeInOutBack
4. easeOutBack
5. easeInOutQuint

you can find many more options if you search over the net I have given you just 5 options in each category there are lot many...

Wednesday, January 11, 2012

WCF error: metadata contains a reference that cannot be resolved

WCF error: metadata contains a reference that cannot be resolved

This is one of the very common error you get when you develop your first WCF and try to consume the same in your client application.

One of this silly error may take long time to resolve because the error description is totally meaning less and our mind will always force us to look through the code to find out the issue.

cause:
Cause of this error is simple when you try to refer the WCF service IIS tried to access C:\Windows\Temp folder. If ASP.NET or IIS_IUSER(based on the windows version) account doesn’t have access to this folder you will see this error.

Solution:
Add ASP.NET or IIS_USER account to this folder or give admin rights to the user account you are running your application.

Thursday, September 15, 2011

Loop through all folders and display files in a Gridview using ASP.NET

Loop through all folders and display files in a Gridview using ASP.NET This is one of the usefull code snippet everybody looking for.
When I search google I found lot of methods to accomplish this task but all seems to be very complex and lengthy code.
This is just a 4 line code to loop through all the folders, including subfolder to get the file detals and display it in Gridview.
You may alter this based on your need.
    
 protected void Page_Load(object sender, EventArgs e)
     {
       ArrayList arrFileList = new ArrayList();
       string[] strFiles = Directory.GetFiles("C:\\Test", "*", SearchOption.AllDirectories);
       foreach (string fileName in strFiles)
       {  
         arrFileList.Add(fileName); 
       }  
       GridView1.DataSource = arrFileList;  
       GridView1.DataBind();  
    }  

Thursday, July 14, 2011

How to check SQL table exists or not, if exists delete the same and create a new one

Nowadays it became my habit that I am posting the code or article only when people ask the questions in forums.

This is one another regular question I used to see in forums "How to check SQL table exists or not, if exists delete the same and create a new one".

What normally people suggests is query the table and if nothing returned then it doesn't exists, but if you do that execution will take some time.
But if you check directly the Object ID of the table it will be much quicker.

Below is a simple query which helps you to check whether table exists or not in the database and if table exists then this query drops the table and create a new one with the same name.
IF OBJECT_ID('dbo.Users') IS NOT NULL
DROP TABLE dbo.Users 
GO
 
CREATE TABLE dbo.Users 
(
  ID INT,
  UserID Varchar(50)
) 
GO
 
select * from Users  
GO
I believe above code is self explanatory and you don’t need much explanation about that. Happy to provide more details if you have any questions.

Thursday, May 19, 2011

Check and uncheck all checkbox in GridView using JavaScript.


This is one of the most common query I saw in Microsoft forums when a beginner start coding. So I thought I will take some time and post a simple and useful code here.
 
<html>
<head id="Head1" runat="server">
  <title>Untitled Page</title>
  <script type="text/javascript">
      function CheckAllRow(chkBox) {
          var gridViewCtlId = '<%=GridView1.ClientID%>';
          var grid = document.getElementById(gridViewCtlId);
          var gridLength = grid.rows.length;
          for (var i = 1; i < gridLength; i++) {
              cell = grid.rows[i].cells[1];
              for (var j = 0; j < cell.childNodes.length; j++) {
                  if (cell.childNodes[j].type == 'checkbox') {
                      cell.childNodes[j].checked = chkBox;
                  }
              }
          }
      }
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:LinkButton ID="chkAll" Text="Check all" OnClientClick=" CheckAllRow(true); return false;"
      runat="server"></asp:LinkButton><br />
    <asp:LinkButton ID="lnkUncheck" Text="Uncheck all" OnClientClick=" CheckAllRow(false); return false;"
      runat="server"></asp:LinkButton><br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AutoGenerateSelectButton="True"
       OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
      OnDataBound="GridView1_DataBound" OnRowDataBound="GridView1_RowDataBound">
      <Columns>
        <asp:TemplateField>
          <HeaderTemplate>
            Select All
            <asp:CheckBox ID="chkBoxAll" runat="server" onclick="CheckAllRow(this.checked);" />
          </HeaderTemplate>
          <ItemTemplate>
            <asp:CheckBox ID="chkBoxSel" runat="server" />
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Course ID">
          <ItemTemplate>
            <%# Eval("ID") %>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Course Name">
          <ItemTemplate>
            <%# Eval("Name")%>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Title">
          <ItemTemplate>
            <%# Eval("Address")%>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Description">
          <ItemTemplate>
            <%# Eval("Phone")%>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Course Type">
          <ItemTemplate>
            <%# Eval("Description") %>
          </ItemTemplate>
        </asp:TemplateField>
      </Columns>
    </asp:GridView>
  </div>
  </form>
</body>
</html>