Tuesday, April 30, 2013

Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. ---> System.Data.SqlClient.SqlException: Incorrect syntax near ''

I have received this ‘Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. ---> System.Data.SqlClient.SqlException: Incorrect syntax near '<some Keyword>' error when I migrated my application from SQL server 2005 to SQL server 2008.

What happened is after migration, database compatibility was still set to previous version. So when we ran any SQL script which doesn’t support previous version will throw error.

To resolve this, you just need to login to the SQL server and change the compatibility level.

If you are getting this error while migrating the database from SQL 2000 to SQL 2005 then you may select the option “SQL Server 2005 (90)”

If you are getting this error while migrating the database from SQL 2005 to SQL 2008 then you may select the option “SQL Server 2008 (100)”

If you are a database admin then you can directly open the SQL query analyzer and execute below SQL query,

EXEC sp_dbcmptlevel 'DatabaseName', 90 ---This is for SQL 2005 Migration
EXEC sp_dbcmptlevel 'DatabaseName', 100 --–This is for SQL 2008 Migration

Steps to follow if you are doing it directly on server,

  • Login to the database server.
  • Locate the database you are getting this error
  • Right click on the database and select Properties
  • Go to “Options” Page
  • Here you will find the option to change the “Compatibility Level”

Below screen print will give you the clear idea of all the options and what you need to change.

Change Compatibility Level

You are always welcome to post your comments below.

Sunday, April 21, 2013

How to read PDF content using iTextSharp in .NET

How to read PDF content using .NET?” is one of the very common questions you normally found in almost all Microsoft forum. Since I have been answering this question with sample code most of the time in I thought I will write a short article with detailed explanation.

Here I am going to use iTextSharp.dll to read the PDF file. iTextSharp is a C# port of iText, and open source Java library for PDF generation and manipulation. You can download the DLL from sourceforge.net using this download iTextSharp link.

Now we will start the .NET coding part to use the iTextSharp.

As this is a sample programe I am going to add only 3 controls. One FileUpload Control to locate/browse the PDF file, one button to show the content in a label and finally a label display the PDF content.

First we will see the PDF file and it’s content we are going to read.

PDF Content To read using .NET

No we will design our .ASPX page, as I mentioned above we have only three controls.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Sample_2012_Web_App.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
        <asp:Label ID="Label1" runat="server" Text="Please select the PDF File"></asp:Label>
&nbsp;<asp:FileUpload ID="PDFFileUpload" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnShowContent" runat="server" OnClick="btnShowContent_Click" Text="Show PDF Content" />
        <br />
        <br />
        <asp:Label ID="lblPdfContent" runat="server"></asp:Label>
    </form>
</body>
</html>

Below image shows you the interface we have created,

.NET Interface to read PDF Content

Now we will see the C# code to read the PDF content. Before start writing the code we need to add reference to the iTextSharp.dll. So from your solution explorer right click on the Reference and click on Browse button to locate the DLL file you have stored from the downloaded source code.

Once you add the reference we have to add the namespaces like below,

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;

Now we will see the complete source code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.Text;
namespace Sample_2012_Web_App
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnShowContent_Click(object sender, EventArgs e)
        {
            if (PDFFileUpload.HasFile)
            {
                string strPDFFile = PDFFileUpload.FileName;
                PDFFileUpload.SaveAs(Server.MapPath(strPDFFile));
                StringBuilder strPdfContent = new StringBuilder();
                PdfReader reader = new PdfReader(Server.MapPath(strPDFFile));
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    ITextExtractionStrategy objExtractStrategy = new SimpleTextExtractionStrategy();
                    string strLineText = PdfTextExtractor.GetTextFromPage(reader, i, objExtractStrategy);
                    strLineText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(strLineText)));
                    strPdfContent.Append(strLineText);
                    reader.Close();
                    strPdfContent.Append("<br/>");
                }
                lblPdfContent.Text = strPdfContent.ToString();
            }
        }
    }
}

Finally we will see the output.

How to read PDF Content using .NET output

As usual you are always welcome to post your comment below.

Monday, March 25, 2013

How to do animation in .NET using jQuery

In general everybody likes animation. Earlier animation in a page was a difficult tasks. Now after jQuery library animation can be done using two lines of code.

In this article I am going to explain you how to do animation in a webpage using jQuery.

First you have to download the jQuery library. Use the jQuery download page to download the library. If you don’t wanted to download you can add the reference directly as well. Here in this article I am directly referring the jQuery library.

Now we will see the complete code used for animation. I have tried to explain most of the details in the code itself and rest of the codes are self explanatory.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Animations.aspx.cs" Inherits="Sample_2012_Web_App.CustomerDetails" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Animation Sample</title>
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    </head>
<body>
    <button id="GoLeft">&laquo;Move Left</button>
    <button id="GoRight">&raquo;Move Right</button>
    <div class="block" style="position:absolute;background-color:#f00;left:100px;width:200px;height:100px;margin:20px;">This box is going to Animate</div>
    <script>
        $("#GoRight").click(function () {
            $(".block")
            .animate({ "left": "+=100px" }, "slow")//This code will move the box Right.
            .animate({ "height": "250px" }, 500)//This code will increase the height.
            .animate({ "width": "250px" }, 500)//This code will increase the width.
            .animate({ "opacity": "0.15" }, "slow")//This code will reduce the Opacity.
            .animate({ "opacity": "1" }, "slow")//This code will increase the Opacity.
            .animate({ "height": "100px" }, 500)//This code will reduce the increased height.
            .animate({ "width": "100px" }, 500);//This cide will reduce the increased width.
        });
        $("#GoLeft").click(function () {
            $(".block")
            .animate({ "left": "-=100px" }, "slow")
            .animate({ "height": "250px" }, 500)//This code will increase the height.
            .animate({ "width": "250px" }, 500)//This code will increase the width.
            .animate({ "opacity": "0.15" }, "slow")//This code will reduce the Opacity.
            .animate({ "opacity": "1" }, "slow")//This code will increase the Opacity.
            .animate({ "height": "100px" }, 500)//This code will reduce the increased height.
            .animate({ "width": "100px" }, 500);//This cide will reduce the increased width.
        });
</script>
</body>
</html>

When you look at the code you can see that I have written many animate code on click of the button. Actually that is the beauty of jQuery. Add as many animation code and make it interesting.

There are many more animation options available but I have limited here with 6 or 7 options.

Below is the interface I have created for animation.

Animation using jQuery

Let me know your feed back after trying this feature in jQuery

Wednesday, February 20, 2013

Techweets–MVPs from South Asia region will be on Twitter on Friday

 

I am very excited to blog this event. All south Asia MVP’s are on twitter on all Fridays from 9 AM to 9PM.

IF you are looking for tips and techniques from Microsoft Most Valuable Professionals then be on twitter.

Here is the official announcement: Techweets

Monday, August 20, 2012

Debugging is not supported under current trust level settings?

Today When I was debugging a test website I created for learning I got the error “Debugging is not supported under current trust level settings?

This error normally occurs when you keep the website directly under C:\inetpub\wwwroot folder. Anyway that is not a subject here. We will directly go to the simple solution to resolve the issue.

Open your Web.config and add below line in

<system.web>
    <trust level="Full"/> 
    .....
    .....
</system.web>

Tuesday, August 7, 2012

Window.Confirm in JavaScript.

 

Most of the time during web application development you may get a requirement to redirect the page based on user choice.

Here I am going to show you how to redirect to an another web page or site on click of a JavaScript Ok button.

If you use Window.Confirm in JavaScript you will get OK and Cancel button. So we will redirect to another page only if user click on OK button. If user Click on Cancel button then we will stay on the same page.

So test the code first we will create a simple button

Below is the .ASPX code for creating a button.

<body>
<form id="form1" runat="server">
<div>

</div>
<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
Text="Submit" />
</form>
</body>

Now in Code behind we will write the JavaScript code to redirect to another website.

protected void btnSubmit_Click(object sender, EventArgs e)
{

ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:if (window.confirm('You will be redirected to Dotnet Galaxy. Click OK to confirm')) { location.href = 'http://asheej.blogspot.in/'; }", true);

}

Now we will see how the alert will be
Cinfrim box in JavaScript

Monday, July 30, 2012

How to replace carriage return and line feed in a SQL server varchar field

 

I have been facing an issue while importing some data from SQL to CSV file. In one of my SQL fields user entered Enter Key or Line feed, because of that my exported CSV file was not in good format. Rows were broken in between. So I started searching for a solution to replace carriage return and line feed and finally accomplished by writing below query.

SELECT replace ( replace(Col1, char(10),''), char(13), '') as [Column 1] FROM  Test

In the above code "col1" is the column name where you have enter key or line feed and "Test" is the table name.

After using this query I was able to export the data to CSV with proper formatting as I required.

I hope this query may help you also.

Sunday, July 15, 2012

How to validate RadioButton using C#

 

Validating radio button in ASP.NET is not very tough but new programmers always get confused about this and ask the questions in forum for the help. So I thought I will write a simple article related to this topic.

Here I am going to use JavaScript to validate the RadioButton.

First we will create the RadioButton.

<asp:Label ID="Label1" text ="Please select one of your favorite fruits" runat="server"></asp:Label>

<asp:RadioButtonList ID="radiobutton1" runat="server">

<asp:ListItem Text="A.Apples">Apple</asp:ListItem>

<asp:ListItem Text="B.Banana">Banana</asp:ListItem>

<asp:ListItem Text="c.cherry">Orange</asp:ListItem>

<asp:ListItem Text="D.Dates">Grapes</asp:ListItem> </asp:RadioButtonList>

<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"

Text="Submit" />

If you look at the above code I have created a RadioButtonList with 4 RadioButtons and a Button.

Now we will write the JavaScript to validate the RadioButtonList

<script type="text/javascript">

function rdValidate()

{

var rd = document.getElementsByName('radiobutton1')



for (var i = 0; i < rd.length; i++)

{

if (rd[i].checked)

{

return true;

}

};

alert("Please select an option");

return false;

}

</script>


Next we will call the JavaScript function to validate the RadioButtonList on Button Click Event.

protected void btnSubmit_Click(object sender, EventArgs e)

{

ClientScript.RegisterStartupScript(GetType(), "Alert", "<script>rdValidate();</script>");

}

That’s it. Now you can run your application and click on the button click event without selecting the RadioButton. You will get the alert message like in below screen print.

Validate Radio Button using JavaScript

Please post your query if you have any in below comment section.

Thanks for reading this article.

Monday, July 2, 2012

Renewed Microsoft MVP Third time a row…

 

I am very happy to inform you all that my MVP status has been renewed third time in row. It’s a very proud moment for me. Thank you all my readers and www.dotnetspider.com members for the support and guidance.

Thursday, May 31, 2012

How to Encrypt and Decrypt web.config using aspnet_regiis

 

Encrypting and decrypting connection string and the web.config is one of the very important task we have to do when we deploy the application in the server. The main reason and the importance of this task is because once you deploy the application with clear text anyone who has permission to access the server can open your web.config and will be able to see the user id and password used to connect to your database.

There are many ways you can encrypt your web.config. Also there are many algorithms available to encrypt your connection string or web.config elements.

Here we will see a very simple method using aspnet_regiis to encrypt and decrypt connectionString element.

First we will have a look at the connectionStrings in web.config

Encrypt Connection String

Below is the command you will be executing to encrypt the connectionStrings.

C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -pef connectionStrings "C:\Encrypt"

Encrypt Connection String 1

In the above command,  connectionStrings is the element we are encrypting, you may change this if you have appSettings or any other section you wanted to encrypt. Also the path C:\Encrypt is the path where I kept the web.config file. It should be your application path where your web.config exists.

Now we will see after encryption how our connectionStrings looks like by opening our web.config.

Decrypt ConnectionString

You can see that our encrypt command added many keys and the connectionString is completely encrypted which you can not read at all.

Decrypt web.config

Ok, now we will move on to decrypting part of the same connectionStrings. Advantage of this approach is, you don’t need to write any specific code to decrypt the connection string. When you access the connection string form your code behind you will get the connection string in encrypted format.

Below is the command you will be executing to decrypt the ConnectionSteings in case you wanted to read the data in clear text format.

C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -pdf connectionStrings "C:\Encrypt"

Decrypt ConnectionString 1

Explanation of the above command is same as the one I have given it for encrypting. Now after executing above command you will see the clear text conectionStrings in your web.config.

I hope you are very clear about the idea and concept regarding encrypt and decrypt connectionString. If you still need some more explanation you can read it form MSDN

Sunday, May 27, 2012

How to find row size of the table in MS SQL

 

Some times you may required to know each row size in your table. Today I am going to present you a simple query which is helpful to find the row size of your table in MS SQL.

First we will see the design of the table,

CREATE TABLE [dbo].[Customer](
    [id] [int] NOT NULL,
    [name] [nchar](10) NULL,
    [Address] [nvarchar](50) NULL,
 ) ON [PRIMARY]
 
GO

Now we will insert some values to the table

INSERT INTO [Customer]([id] ,[name] ,[Address]) VALUES (1 ,'John','Spain')
INSERT INTO [Customer]([id] ,[name] ,[Address]) VALUES (1 ,'James','Wales')
INSERT INTO [Customer]([id] ,[name] ,[Address]) VALUES (1 ,'Michael','Scotland')
INSERT INTO [Customer]([id] ,[name] ,[Address]) VALUES (1 ,'Mark','United Kingdom')
GO

Now we will see the query to get the row size,

select
row_number() over (order by id desc) as [ROW],
ISNULL(datalength(id),0)+
ISNULL(datalength(name),0)+
ISNULL(datalength(Address),0) as RowSize
from Customer

Output of the above query will be

ROW    RowSize
1    52
2    40
3    34
4    34

Cheers!

Friday, May 4, 2012

How to find application path in Console/VB.NET windows application

In ASP.NET web application we normally use Server.MapPath to get the application root folder path. But what we will write in VB.NET windows and console application???

Here is the two lines of code which will help you to get the application path in VB.NET windows and console application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace ConsoleApplication2
{
    class TestConsole 
    {
        static void Main(string[] args)
        {
            string strLocation = System.AppDomain.CurrentDomain.BaseDirectory;
            Console.WriteLine(strLocation);
        }
    }
}

Below is the screen print of the above code with output,

Application path in Console application

Thursday, May 3, 2012

Open MS Word document in web browser

 

This is one of the common request you will get when you do any file operation in your project. This code can be used to open EXCEL, Power Point, PDF etc.

protected void btnWord_Click(object sender, EventArgs e)
{
    string strWordFile = @"c:/Test.docx";
    FileInfo objDoc = new FileInfo(strWordFile);
    Response.Clear();
    Response.ContentType = "Application/msword";
    Response.AddHeader("content-disposition", "attachment;filename=" + objDoc.Name);
    Response.AddHeader("Content-Length", objDoc.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.TransmitFile(objDoc.FullName); 
    Response.End(); 
}

Wednesday, May 2, 2012

How to add different column values as Tooltip for DropDownList in ASP.NET

 

Sometimes we may have to show different field from the database as tool tip for the DropDownList in ASP.NET.

Below is a sample code to display the tooltip for DropDownList. Here I have used different field from the database to show as tooltip.

protected void btnLoad_Click(object sender, EventArgs e)
        {
            string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["sqlConnection"].ToString();
 
            SqlConnection conn = new SqlConnection(strCon);
            conn.Open();
            SqlDataAdapter da = null;
            DataSet dsCountry = new DataSet();
            try
            {
                string strCountrySQL = "select id, name, Address from dbo.Customer";
                da = new SqlDataAdapter(strCountrySQL, conn);
                da.Fill(dsCountry);
                DropDownList1.DataSource = dsCountry;
                DropDownList1.DataTextField = "name";
                DropDownList1.DataValueField = "id";
                DropDownList1.DataBind();
 
                int ItemCount = DropDownList1.Items.Count;
                for (int i = 0; i < ItemCount; i++)
                {
                    DropDownList1.Items[i].Attributes.Add("Title", dsCountry.Tables[0].Rows[i]["Address"].ToString());
                }
                DropDownList1.Items.Insert(0, new ListItem("--Select--", "--Select--"));
                DropDownList1.SelectedItem.Selected = false;
                DropDownList1.Items.FindByText("--Select--").Selected = true;
            }
            catch (Exception ex)
            {
                lblMsg.Text = "Error!! <br>+" + ex.Message.ToString();
            }
            finally
            {
                dsCountry.Dispose();
                da.Dispose();
                conn.Close();
                conn.Dispose();
            }

Below is the screen print of the tooltip,

ToolTip