Wednesday, March 21, 2012

How to disable previous dates in Calendar control in ASP.NET

 

This is a simple code but many people got confused about this inbuilt feature in .NET Calendar control.

We will be using Calendar DayRender control to disable all the previous dates.

First we will add the Calendar control,

<asp:Calendar ID="Calendar1" runat="server" ondayrender="Calendar1_DayRender">
       </asp:Calendar>

No we will see what you have to write under DayRender event,

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date < DateTime.Now.Date)
            {
                e.Day.IsSelectable = false;
                e.Cell.ForeColor = System.Drawing.Color.Gray;
            }
        }

 

See the Calendar control after disabling the previous dates,

Calendar

Tuesday, March 20, 2012

Best of Microsoft Management Summit (UK) 2012‏

 

82141_d6 MMS Email

Learn about 2012's exciting wave of Microsoft Private Cloud product launches and announcements – starting with the release of System Center 2012.
Get the latest insights into the Microsoft Private Cloud and learn what's new in System Center 2012. The Best of MMS 2012 brings you the highlights from MMS 2012 conference in a choice of UK-wide one-day or virtual events.

Register for the event using the link Launching System Center 2012

Wednesday, March 14, 2012

How to read web.config file using JavaScript

 

I have seen many people asking this question in .NET forums. So I thought I will share this small piece of code.

First we will see web.config entry which we are going to read,

<configuration>
      <appSettings>
            <addkey="WordTemplate"value="template.doc"/>
      </appSettings>
      <connectionStrings>
                 <add name="MysqlCon"
         connectionString="server=1xx.1xx.x.x;User Id=username;password=password;database=dbName;Persist Security Info=True"
         providerName="MySql.Data.MySqlClient" />
   </connectionStrings>
      </connectionStrings>
...
<configuration>

Now we will see the JavaScript function which reads above connection string and the AppSettings key,

<script language="javascript" type ="text/javascript"> 
function ReadWebConfig()
{
    var strCon = '<%=ConfigurationManager.ConnectionStrings["MysqlCon"].ConnectionString %>'
    alert(strCon);
    var strTemp = '<%=ConfigurationManager.AppSettings["WordTemplate"].ToString() %>'
    alert(strTemp);
}
</script>

Tuesday, March 13, 2012

Visual Studio 11 Beta in LIVE now

 

Happy news for all .NET developers who was waiting to have glance on Visual Studio 11 Beta.

You can download Visual Studio 11 Beta from Microsoft download centre now.

Please check this link to download the Visual Studio 11 Beta

Monday, March 12, 2012

List all Stored Procedure Names and Scripts in the database.

 

Below SQL query can be used to display all Stored Procedures and SQL Scripts used to create those Stored Procedure in your database.

SELECT  sysObj.Name as [Stored Procedure Name], sysM.Definition as [Stored Procedure Script]
FROM sys.sql_modules as sysM INNER JOIN sys.objects as sysObj 
ON sysM.object_id = sysObj.object_id 
WHERE sysObj.type = 'P'

If you need more sample please refer my articles: Stored Procedures

Tuesday, March 6, 2012

Download for Internet Information Services (IIS) 8.0 Express Beta is now live

 

Happy news for the developers. Microsoft announce that download for IIS 8.0 Express Beta is now live.  You can download the same using the following URL:

http://www.microsoft.com/download/en/details.aspx?id=29055

The IIS 8.0 version of IIS Express shares more of its foundation with the full version of IIS, so you may not face much issues when you switch between your development environment and your production environment.

More details are available in the ReadMe file for IIS Express, which is can be seen at the following URL:

http://learn.iis.net/page.aspx/1266/iis-80-express-beta-readme/

Thursday, March 1, 2012

How to display alert in outlook express if subject field is empty while sending mail

 

This is a common mistake every one does while sending mail using outlook. You may feel bad if you send an important mail to the client or to your manager without a subject.

Since Microsoft didn't provide any option to make the subject mandatory or any warning for the empty subject I thought I will do a little research and find out the workaround.

This is a VB code which will display an alert when you click on Send Mail button in Outlook if subject field is empty.


Just follow below steps,
1. Of course first we will open outlook
2. Then we will Open Visual basic editor by pressing ALT+F11
3. Then from left pane expand the Project1 until you see "ThisOutlookSession"
4. Double Click on "ThisOutlookSession"
5. Now it's the time to copy and paste the below code in the new window opened when you double click on "ThisOutlookSession".
6. Save and Close the window. You are done!

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean) 
Dim strOutlookSubject As String 
strOutlookSubject = Item.Subject 
If Len(strOutlookSubject) = 0 Then 
Prompt$ = "Are you sure you want to send the Mail without Subject?" 
If MsgBox(Prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Subject is empty") = vbNo Then 
Cancel = True 
End If 
End If 
End Sub

Note: Change the alert as per your interest from above code.

Below is the screen print of the alert which you may be getting,

image

Now try to send mail without subject from your outlook!!!

My Weblog post

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.