Saturday, January 1, 2011

JQuery: Add, Deete Rows, Validate the controls of added rows of a Table

What if the new rows with controls has to be added dynamically and deleted on button clicks and those controls have to be validated before submitting to the server. JQuery is the easiest way to add/remove at the client side dynamically.

Have a sneak peek here.


Look at the code here





<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>JQuery Page</title>
<script src="js/jquery-1.4.4.min.js" type="text/javascript"></script>
<style type="text/css">
.mandatory
{
border: solid 1px red;
}
</style>
<script type="text/javascript">
function CallThis()
{
var requiredFields = $('#tableid').find('.requiredField');
var allFieldsComplete = true;
requiredFields.each(function(index) {
if (this.value.length == 0) {
$(this).addClass('mandatory');
allFieldsComplete = false;
} else {
//alert(this.value);
$(this).removeClass('mandatory');
}
});
if(!allFieldsComplete){
$('#dispMsg').html('Mandatory fields to be entered');
}
return allFieldsComplete;
}

</script>

</head>
<body>
<table id="tableid" border="1" class="tableid">
<thead>
<tr>
<td bgcolor="#f1f1f1">Header 1</td>
<td bgcolor="#f1f1f1">Header 2</td>
</tr>
<tr>
<td><input type="text" class="requiredField" /></td>
<td><input type="text" class="requiredField2" /></td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="requiredField" /></td>
<td><input type="text" class="requiredField2" /></td>
</tr>
<tr>
<td><input type="text" class="requiredField" /></td>
<td><input type="text" class="requiredField" /></td>
</tr>
</tbody>
</table>
<div id="dispMsg" style="color:Red;"></div>
<input type="button" class="txtbox" value="Validate" onclick="javascript:CallThis();" />
<input type="button" id="btnTest" value="Add"/>
<input type="button" id="btnTest2" value="Remove"/>
</body>
<script type="text/javascript">

$('#btnTest').click(function() {
$('#tableid > tbody:last').append('<tr><td><input type="text" id="txt1" class="requiredField"/> </td><td>yyy</td></tr>');
});
$('#btnTest2').click(function() {
$('#tableid > tbody:last tr:last').remove();
});
</script>
</html>

Friday, December 31, 2010

JQuery: Validate all the controls in the rows of a table

Validating all the controls of each row of a TABLE element can be done at clientside using jQuery.






<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>JQuery Page</title>
<script src="js/jquery-1.4.4.min.js" type="text/javascript"></script>
<style type="text/css">
.mandatory
{
border: solid 1px red;
}
</style>
<script type="text/javascript">
function CallThis()
{
var mandatorys = $('#tableid').find('.mandatory');
var allFieldsComplete = true;
mandatorys.each(function(index) {
if (this.value.length == 0) {
$(this).addClass('mandatory');
allFieldsComplete = false;
} else {
//alert(this.value);
$(this).removeClass('mandatory');
}
});
if(!allFieldsComplete){
$('#dispMsg').html('Mandatory fields to be entered');
}
return allFieldsComplete;
}
</script>

</head>
<body>
<table id="tableid" border="1" class="tableid">
<tr> <td>
<input type="text" class="mandatory" />
</td> <td>
<input type="text" class="mandatory" />
</td> </tr>
<tr> <td>
<input type="text" class="mandatory" />
</td>
<td><input type="text" class="mandatory" />
</td> </tr> </table>
<div id="dispMsg" style="color:Red;"></div>
<input type="button" class="txtbox" value="Validate" onclick="javascript:CallThis();" />
</body>
</html>

Wednesday, December 29, 2010

How to make ASP.Net Server side Calls from JQuery





Here Comes the WebService.
Dont forget to add the Namespace: System.Web.Script.Services. (Comes with AJAX Extensions).
(You may face problem while making the server call if the Website you built is not an Ajax Enabled Website.)


using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class ThisService : System.Web.Services.WebService
{
    public ThisService()
    {
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld(string dlaID)
    {
        return "Hello World";
    }
}


Now the .aspx page with Markup.
Download the latest JQuery file and add to your project and refer.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JQServiceCall.aspx.cs" Inherits="JQServiceCall" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>JQuery ASP.Net Page</title>
    <script type="text/javascript" src="Scripts/jquery-1.4.2.min.js" language="javascript"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(
        function() {
        var ID = '49214';
        $.ajax({
        type:"POST",
        url:"ThisService.asmx/HelloWorld",
        dataType:"json",
        // data: "{}",
        data:'{"dlaID":' + ID + '}',
        contentType:"application/json; charset=utf-8",
        success:function(msg) {
        if (msg != null) {alert(msg);}
        else {alert('My Message!');
        }},
        error:
        function(xhr) {if (xhr != null) {alert("Error occured \n" + xhr.responseText);}}
        });});
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <font color="#000000">User Name :
            <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
            <span id="status"></span></font>
        <div>
        </div>
    </form>
</body>
</html>

Tuesday, November 23, 2010

Microsoft.Practices.Repository : Make sure "GenericResources.resources" was correctly embedded or linked into assembly

Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "GenericResources.resources" was correctly embedded or linked into assembly "Microsoft.Practices.Repository" at compile time, or that all the satellite assemblies required are loadable and fully signed.

This was the error which held my neck for more than two days. We follow Repository Factory for Visual Studio 2008 for Data Access Layer Creation (By Microsoft Patterns and Practices.)


I replaced the ExceptionHandling snippet [throw new RepositoryFailureException(ex);]
with [throw new RepositoryFailureException(ex.Message,ex.InnerException);] in each repository class generated by Repository Factory.

Did a Find and Replace for the whole DataAccess Project. Then went for a build of all the projects (DataAccess Layer, Business Logic Layer, and Presentation Layer. Then Ran the solution by Setting Startup Page as Finance User Dashboard.

Error got changed to the following.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

This is a very familiar one. Could be some thing wrong either with the Connection String in the Web.config or Failed network connection. :) the parameters mentioned in the Web.Config was pointing a wrong DB.

See, how vague the initial error was. It didnt have any relation with the actual problem. Be aware of these situations, these can mess up your day.

Wednesday, November 10, 2010

Resolved : Unable to connect to asp.net development server

Working on Visual Studio 2008 and not debugging the website and whenever you run the solution it gives error as "Unable to connect to asp.net development server" ?


WebDev.WebServer.EXE is the process associated with Visual Studio 2008 when you run a project(solution).
This is located EITHER at
C:\Program files\Common files\Microsoft Shared\DevServer\9.0  OR C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727


Problem is, your Visual Studio is unable to get attached to this exe, when you try to run the solution due to some reason. Problem with mine was, this executable (WebDev.WebServer.EXE) was corrupted. (There is no method known to identify this exe is corrupted or not). I just replaced this exe with the one i have copied from my colleagues PC where he had installed VS 2008, and was running fine. 


This has helped me in resolving the issue "Unable to connect to asp.net development server" with VS 2008. 
Have a try. 

Thursday, September 16, 2010

Ajax assembly version conflicts and resolution

The following could be faced during your Staging to Production movement or Implementation server.

System.Web.Script.Services.ScriptMethodAttribute exists in both 'C:\Windows\Microsoft.Net\Framework64\v2.050727\Temporary ASP.Net....' 
and C:\Windows\assembly\GAC_MSIL\System.Web.Extensions\3.5.0.0_...'

BindingRedirects


First step is to clear the Temporary ASP.Net folder and try, even then you face the same error message, spend some time in the below described.

When you build a .NET Framework application against a strong-named assembly, the application uses that version of the assembly at run time by default, even if a new version is available. However, you can configure the application to run against a newer version of the assembly.

You can redirect more than one assembly version by including multiple elements in a element.

The following example shows how to redirect one assembly version to another.



Visual Studio 2008 automatically adds binding redirects in the web.config file
This solves many of the interoperability issues and nothing wrong in creating applications with reference to System.Web.Extensions of older version (v1.0) with VS2008

Wednesday, September 1, 2010

Basics; Updating a row item in GridView

GridView Row Edit and Update would be one among the basics a .Net fresher programmer to start with.

   CODE BEHIND File

   protected void GrvCannibalize_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GrvCannibalize.EditIndex = e.NewEditIndex;
        BindCannibaliseGrid();
    }
    protected void GrvCannibalize_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GrvCannibalize.EditIndex = -1;
        BindCannibaliseGrid();
    }
   protected void GrvCannibalize_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        TrnFutureSales oEntity = new TrnFutureSales();  // Business Entity
FutureSalesLogic oLogic = new FutureSalesLogic();  // Business Logic Layer
      
TextBox oWRActual = GrvCannibalize.Rows[e.RowIndex].FindControl("TxtWRActual") as TextBox;
        TextBox oWIActual = GrvCannibalize.Rows[e.RowIndex].FindControl("TxtWIActual") as TextBox;
        TextBox oCNNActual = GrvCannibalize.Rows[e.RowIndex].FindControl("TxtCNNActual") as TextBox;

        HiddenField oFutureSalesId = GrvCannibalize.Rows[e.RowIndex].FindControl("HdnFutureSalesId") as HiddenField;

        oEntity.ActualCan = Convert.ToDecimal(oWRActual.Text);
        oEntity.ActualRR = Convert.ToDecimal(oCNNActual.Text);
        oEntity.ActualImpact = Convert.ToDecimal(oWIActual.Text);
        oEntity.FutureSalesId =  Convert.ToInt64(oFutureSalesId.Value);

oLogic.UpdateFutureSalesForId(oEntity);    // This method has to be added as yours to update the database. 

        GrvCannibalize.EditIndex = -1;
        BindCannibaliseGrid(); // Bind the grid again to load with the new values.
    }

ASPX (MARK UP) File

<asp:GridView ID="GrvCannibalize" DataKeyNames="FutureSalesID" runat="server" AutoGenerateColumns="false" EmptyDataText="No Record Found" EmptyDataRowStyle-CssClass="redstar" AllowPaging="true" Width="100%" PageSize="5" ShowFooter="true" OnRowEditing="GrvCannibalize_RowEditing" OnRowCancelingEdit="GrvCannibalize_RowCancelingEdit"
OnRowUpdating="GrvCannibalize_RowUpdating" AutoGenerateEditButton="false">

<Columns>
<asp:CommandField ButtonType="Image" ShowEditButton="True" EditImageUrl="~/App_Themes/images/Edit.gif" UpdateImageUrl="~/App_Themes/images/Update.gif" CancelImageUrl="~/App_Themes/images/Cancel.jpeg">
</<asp:CommandField>

<asp:TemplateField HeaderText="Actual WI">
  <ItemTemplate>
  <asp:Label ID="LblWIActual" runat="server" Text='<%# Bind("ActualImpact") %>'></<asp:Label>
 <asp:HiddenField ID="HdnFutureSalesId" runat="server" Value='<%# Eval("FutureSalesID") %>'></<asp:HiddenField>
  </ItemTemplate>
    <EditItemTemplate>
      <asp:TextBox ID="TxtWIActual" runat="server" CssClass="txtboxAmount" Text=''></<asp:TextBox>
      <asp:RequiredFieldValidator ID="RfvWIActual" runat="server" ErrorMessage="Required" CssClass="redstar" Text="Required" ControlToValidate="TxtWIActual">
</<asp:RequiredFieldValidator>
</EditItemTemplate>
</<asp:TemplateField>

<asp:TemplateField HeaderText="Actual WR">
<ItemTemplate>
<asp:Label ID="LblWRActual" runat="server" Text='<%# Bind("ActualRR") %>'></<asp:Label>
</ItemTemplate>
<EditItemTemplate>
  <asp:TextBox ID="TxtWRActual" runat="server" CssClass="txtboxAmount" Text=''></<asp:TextBox>
    <asp:RequiredFieldValidator ID="RfvWRActual" runat="server" ErrorMessage="Required" CssClass="redstar" Text="Required" ControlToValidate="TxtWRActual"></<asp:RequiredFieldValidator>
</EditItemTemplate>
</<asp:TemplateField>

</Columns>
</<asp:GridView>