JG Vimalan's Blog

It is all about coding!

Enable / Disable ASP.NET TextBox control using jquery

The following code snippet will give you an idea for enabling or disabling an asp.net control using jquery,

Here, based on the option (true or false), I am enabling / disabling a textbox, setting its background color to lightgrey and clearing the text.

<head runat=”server”>
<script src=”Scripts/jquery-1.8.2.min.js” type=”text/javascript”></script>
<script type=”text/javascript” language=”javascript”>
$(document).ready(function () {
var optionChkBox = $(“#chkOption”)
optionChkBox.change(function () {
var status = optionChkBox.is(‘:checked’)

var nameTxtBox = $(“#txtBoxName”)
if (status) {
nameTxtBox.attr(‘disabled’, false)
nameTxtBox.css(“background-color”, “white”)
}
else {
nameTxtBox.val(”)
nameTxtBox.attr(‘disabled’, true)
nameTxtBox.css(“background-color”, “lightgray”)
}
})
});
</script>

Advertisements

October 16, 2012 Posted by | ASP.NET, JQuery, VS 2010 | Leave a comment

Using files in C# unit testing

In order to use files during unit testing, the files must be added in the unit test project as shown below,

To demonstrate, I am using an xml file in my unit test.

The file should be available in the deployment folder for test methods to access. In order to achieve that, browse to Test -> Edit Test Settings -> Local.testsettings in Visual Studio menu. Test Settings window will be displayed as shown below,

Go to Deployment and Check ‘Enable Deployment’. Now add the file(s) (from test project folder) using the “Add File…” button.

In the unit test, specify the xml file name in the DeploymentItem attribute as shown below,

Now, when test is running, the file will be available in the deployment directory and it can be accessed using TestContext.DeploymentDirectory.

October 5, 2012 Posted by | C#.NET, VS 2010 | Leave a comment

This OdbcTransaction has completed; it is no longer usable.

I got this exception when I was trying to perform multiple row insert in a DB2 database using Enterprise Library 5.0 and DbTransaction.

Cause of this exception:

I was trying to invoke ExecuteNonQuery method from Database object instead of DbCommand object. And, when one of the SQL failed (due to syntax or data problem), the catch block caught the exception and tried to rollback but DbTransaction.Rollback failed and it was throwing the above exception.

Solution:

In order to solve this issue, set the transaction object in DBCommand.Transaction property and ExecuteNonQuery in DbCommand. Plus, the connection should be in open state when trying to rollback. The working code sample is given below,

internal static bool InsertRecords(List<string> sqlCollection)
{
Database database = DatabaseFactory.CreateDatabase(Utility.GetDB2ConnectionName);

using (DbConnection dbConnection = database.CreateConnection())
{
DbCommand dbCommand = dbConnection.CreateCommand();
DbTransaction dbTransaction = null;

try
{
dbConnection.Open();
dbTransaction = dbConnection.BeginTransaction();
dbCommand.Transaction = dbTransaction;

foreach (string sql in sqlCollection)
{
dbCommand.CommandText = sql;
dbCommand.CommandType = CommandType.Text;
dbCommand.ExecuteNonQuery();
}

dbTransaction.Commit();
return true;
}
catch (Exception error)
{
Log.Error(error);

if (dbTransaction != null)
dbTransaction.Rollback();
}
}

return false;
}

October 2, 2012 Posted by | ASP.NET, C#.NET, DB2, Enterprise Library 5.0, VS 2010 | | 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