JG Vimalan's Blog

It is all about coding!

DbTransaction and EnterpriseLibrary Data Application Block 5.0

Using DbTransaction with EnterpriseLibrary Data Application Block 5.0 is very easy. In this post, i am inserting multiple rows in 5 tables in sql server database. If insert fails in one table, then all transaction will be rollback.

The complete code is given below,

using System;
using System.Collections.Generic;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Db2_EntLib5._0_Transaction
{
class Program
{
static void Main(string[] args)
{
List<string> sqlCollection = new List<string>();

sqlCollection.Add(“INSERT INTO TABLE_A (Name) VALUES (‘A0’)”);
sqlCollection.Add(“INSERT INTO TABLE_A (Name) VALUES (‘A1’)”);
sqlCollection.Add(“INSERT INTO TABLE_A (Name) VALUES (‘A2’)”);
sqlCollection.Add(“INSERT INTO TABLE_A (Name) VALUES (‘A3’)”);
sqlCollection.Add(“INSERT INTO TABLE_B (Name) VALUES (‘B’)”);
sqlCollection.Add(“INSERT INTO TABLE_C (Name) VALUES (‘C’)”);
sqlCollection.Add(“INSERT INTO TABLE_D (Name) VALUES (‘D0’)”);
sqlCollection.Add(“INSERT INTO TABLE_D (Name) VALUES (‘D1’)”);
sqlCollection.Add(“INSERT INTO TABLE_E (Name) VALUES (‘12345678901234567890123456789012345678901234567890’)”);
sqlCollection.Add(“INSERT INTO TABLE_F (Name) VALUES (null)”); //null value is not allowed. So, exception will occur here.

Database database = DatabaseFactory.CreateDatabase(“DBConn”);

using (DbConnection connection = database.CreateConnection())
{
DbTransaction transaction = null;

try
{
if (connection.State != System.Data.ConnectionState.Open)
connection.Open();

transaction = connection.BeginTransaction();

foreach (string sql in sqlCollection)
{
database.ExecuteNonQuery(transaction, System.Data.CommandType.Text, sql);
}

transaction.Commit();
}
catch (Exception error)
{
Console.WriteLine(error);
transaction.Rollback();
}
finally
{
transaction.Dispose();
connection.Close();
}
}

Console.Read();
}
}
}

Advertisements

September 29, 2012 Posted by | C#.NET, Enterprise Library 5.0 | , | Leave a comment

Save xml file in client machine without user interaction using asp.net

I got a task where I need to save an xml file in client machine whenever user vists a specific asp.net webpage. As my web application is IE compatible only, I have not verified this solution in other browsers.

In the following code I am going to read an xml file (data source) from the server and paste it in the client machine. The data source can be a session object, a variable in the code behind or a value in hidden field in asp.net page. My sample project structure is given below,

As a first step, add reference to jquery in your aspx page. Using jquery ajax, read the xml file. Then, using FileSystemObject ActiveX create the file in the target location. Then populate the file with the xml object.

Complete code is given below,

<head runat=”server”>
<title>Process XML using jQuery</title>
<script src=”Scripts/jquery-1.7.2.min.js” type=”text/javascript”></script>

<script type=”text/javascript” language=”javascript”>
$(document).ready(function () {;
$.ajax({
type: “GET”,
url: “UserInfo.xml”,
dataType: “xml”,
success: function (xmlObj) {
var fileSystemObject = new ActiveXObject(“Scripting.FileSystemObject”);
varFileObject = fileSystemObject.OpenTextFile(“C:\\Data\\UserInfo.xml”, 2, true, 0);
varFileObject.write(xmlObj.xml);
varFileObject.close();
alert(“Download complete”);
close();
},
error: function () {
alert(“Download failed. Please contact the administrator.”);
}
});
});

</script>

This does not require any user interaction. I am displaying javascript alert messages just for testing purpose.

In the line, varFileObject = fileSystemObject.OpenTextFile(“C:\\Data\\UserInfo.xml”, 2, true, 0); parameter true creates the file if it does not exist.

September 21, 2012 Posted by | ASP.NET, JavaScript, JQuery, VS 2010 | 6 Comments

Clickable GridView with Postback in ASP.NET 4.0

In this post, I will show you how to make a GridView row clickable and read the selected row values after postback.

Step 1:

Create an ASP.NET 4.0 web application. Add a gridview control in the application.

Step 2:

Create RowCreated and RowDataBound events and set their values as shown below,

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add(“onclick”, “CreatePostBack(this);”);
}
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add(“onmouseover”, “mouseIn(this);”);
e.Row.Attributes.Add(“onmouseout”, “mouseOut();”);
}
}

Here, the CreatePostBack(this); is a javascript function. In this function call the _doPostBack function and pass the necessary parameters as shown below,

<script type=”text/javascript”>
function mouseIn(row) {
document.body.style.cursor = ‘pointer’;
}
function mouseOut() {
document.body.style.cursor = ‘auto’;
}

function __doPostBack(eventTarget, eventArgument) {
var theForm = document.forms[‘ctl01’];
if (!theForm) {
theForm = document.ctl01;
}
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}

function CreatePostBack(row) {

__doPostBack(‘GridView1’, row.rowIndex);

//in this example, i am just passing the rowIndex. You can read the selected row values and pass them.
}
</script>

Step 3:

Add two hidden fields as shown below for capturing the  event target and event argument,

<input type=”hidden” name=”__EVENTTARGET” id=”__EVENTTARGET” value=”” />
<input type=”hidden” name=”__EVENTARGUMENT” id=”__EVENTARGUMENT” value=”” />

Step 4:

In the Page Load event, set the data source for the gridview control and the code for reading the values when there is a post back,

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetUsers(); //use your method for getting datasource value here
GridView1.DataBind();
}
else if (Request.Form[“__EVENTTARGET”] == “GridView1”)
{
var arg = Request.Form[“__EVENTARGUMENT”];
//now you got the selected row values
}
}

Step 5:

Thats all! The Gridview markup is given below for your reference,

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<input type=”hidden” name=”__EVENTTARGET” id=”__EVENTTARGET” value=”” />
<input type=”hidden” name=”__EVENTARGUMENT” id=”__EVENTARGUMENT” value=”” />
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”false”
onrowcreated=”GridView1_RowCreated” onrowdatabound=”GridView1_RowDataBound”>
<Columns>

….

</Columns>
</asp:GridView>
</asp:Content>

So, whenever a gridview row is clicked, the postback will happen and you can read the selected row values.

The working sample can be downloaded from here,

https://docs.google.com/file/d/0By3at1G2EGgOYTNYQ1ZuQi11aXc/edit

File->Download

September 15, 2012 Posted by | ASP.NET, C#.NET, VS 2010 | , | 9 Comments

Programmatically run PsExec.exe

The following code snippet will give you an idea on programmatically (c#) running PsExec.exe. I assume that you have already copied PsExec.exe in your executable path. In the following code snippet I am trying to launch an application in remote server programmatically.

ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = “PsExec.exe”;
processInfo.Arguments = “\\servername \”C:\\PROGRA~1\\myapp\\sample.EXE\””;

using (Process process = Process.Start(processInfo))
{
 process.WaitForExit();
}

To run the PsExec.exe from run command the syntax is given below,

C:\Project\psexec.exe \\servername “C:\PROGRA~1\myapp\sample.EXE”

 

September 11, 2012 Posted by | C#.NET, VS 2010 | Leave a comment

Write console output to text file using C#

The console output can be written to text file as shown below,

In the above example I am writing java version in the text file. So, the text file with java version is as shown below,

September 9, 2012 Posted by | C#.NET, VS 2010 | Leave a comment