Thursday, December 30, 2010

Format width of AutocompleteExtender AjaxControlToolkit

By default, the width of the autocomplete list of autocomplete extender is inherited from the target control which is the textbox. However, you can customize the width and appearance of the ajax control:
1. Create an asp.net website
2. Add a webservice to your site
3. In your webservice, add a code to retrieve customer or any info.
4. In your asp.net website, add an aspx markup similar below:
 Note that CompletionListElementID target control is the div called autocomplete declared below the textbox.
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  
 <Services>  
 <asp:ServiceReference Path="~/YourSampleService.asmx"/>  
 </Services>  
 </asp:ToolkitScriptManager>  
 <div>  
 <table>  
 <tr>  
 <td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>  
 <td><div id="AutoComplete" runat="server"> </div></td>  
 </tr>  
 <tr>  
 <td>  
 <asp:AutoCompleteExtender ID="AtNames" runat="server"  
 ServicePath="~/YourSampleService.asmx"  
 ServiceMethod="Your_method" CompletionListElementID="AutoComplete"  
 CompletionSetCount="25" TargetControlID="txtName" >  
 </asp:AutoCompleteExtender>  
 </td>  
 </tr>  
 </table>  
 </div>  
5. Add a custom css for your div

#AutoComplete  
 {  
   width: 250px !important;  
   overflow: visible !important;  
 }  
6. Compile and run your website
Reference: Increase Width of Autcomplete Extender

Wednesday, December 29, 2010

Remove autorun.inf virus in USB 2.0 Flashdisk

I was bothered by this weird pop-up generated by avira antivirus regarding autorun.inf..
After googling, the solution was to use cmd(previously DOS) command.

del /a:rhs [driveletter]:autorun.inf

Example: del /a:rhs F:autorun.inf (where F is my USB drive)

Reference: http://inforids.com/remove-autoruninf-virus-completly-from-system-flash-drives/

Monday, December 27, 2010

SQL Server Formatting Dates Tip/Article

Here is a handy site when im currently working with dates in sql server 2005/2008..

http://www.sql-server-helper.com/tips/date-formats.aspx

Sunday, December 26, 2010

WPF Datagrid Demo

I have developed a project on WPF before. WPF has been utilized in Vista OS and other software. But this cannot replace the stability of Windows Forms.
Still, I don't have ample time to dive deeply in WPF, hopefully soon! LOL.. :D
So, to begin with:
1. Download and install WPF Toolkit (Visual Studio 2008)
2. Open Visual Studio 2008
3. Add a WPF Project (Just call it GridDemo)
4. Add a DataGrid in your Window.xaml
5. Make sure to have referenced wpf toolkit: http://schemas.microsoft.com/wpf/2008/toolkit/
6. Customize Your Grid
1:  <grid:DataGrid AutoGenerateColumns="False" Margin="8,11,10,78"  
2:  ItemsSource="{Binding}" Name="CusGrid">  
3:  <grid:DataGrid.Columns>  
4:  <grid:DataGridTextColumn Binding="{Binding Path=CustomerID}"  
5:  Header="Customer ID" />  
6:  </grid:DataGrid.Columns>  
7:  ....other columns goes here  
8:  </grid:DataGrid>  
7. In your Window1.cs file, populate your grid with resulset
Code:
 protected void GridLoad()  
 {  
  SqlConnection conn = new SqlConnection(your_connection_string);  
  SqlCommand cmd = new SqlCommand("select * from customers",conn);  
  DataSet ds = new DataSet();  
  SqlDataAdapter da = new SqlDataAdapter(cmd);  
  da.Fill(ds);  
  CusGrid.DataContext = ds.Tables[0];  
 }
8. Run your application.
That's It!

Using jQuery Intellisense in an external javascript file.

Create an aspx page and an external javascript file. Call the javascript external file in your aspx page.

1:  <script src="js/jquery-1.4.1.js" type="text/javascript">  
2:  </script>  
3:  <script src="js/Sample.js" type="text/javascript">  
4:  </script>  

In your external .js file, add the following code on top of the js file page.
 ///<reference path="jquery-1.4.1.js"/>  
 function dothis()  
 {  
     //your code here  
 }  

Saturday, December 25, 2010

Code in gridview rowdatabound not working if rowstate is (Alternate|Edit)

In a gridview rowdatabound event I have this condition to check if rowstate is in edit mode:
Code:
if (e.Row.RowState == DataControlRowState.Edit) //row is in edit mode  
  {  
      TextBox actdaterec = (TextBox)e.Row.Cells[1].FindControl("txtDateRec");  
      actdaterec.Text = string.Empty;  
      TextBox cashRec = (TextBox)e.Row.Cells[2].FindControl("txtCashReceived");  
      cashRec.Text = string.Empty;  
  }  
The code above usually works if the rowstate is in edit mode, however on the succeeding rows the rowstate becomes Alternate|Edit. The code above does not work. So the solution would involve C# bitwise operator (&).
See the revised code below:
Code:
if ((e.Row.RowState & DataControlRowState.Edit) > 0) //row is in edit mode  
 {  
    TextBox actdaterec = (TextBox)e.Row.Cells[1].FindControl("txtDateRec");  
    actdaterec.Text = string.Empty;  
    TextBox cashRec = (TextBox)e.Row.Cells[2].FindControl("txtCashReceived");  
    cashRec.Text = string.Empty;  
 }  
The code will execute even if rowstate is Alternate|Edit. It will ignore the alternate value.
Reference: ASP.NET Forum

Friday, December 24, 2010

Formatting date values shown in label control inside a Gridview

Reference: Set Date Format in Gridview
To format date as short date format of a label control inside a template field use Bind() as shown below:
1:  <ItemTemplate>  
2:    <asp:Label id="lblDateRec" runat="server" Text='<%#   
3:    Bind("GeneratedDateRec", "{0:MM/dd/yyyy}") %>'></asp:Label>  
4:  </ItemTemplate>  

Reset autonumber in sql server (TSQL)

Here is the script to reset autonumbers in sql server. Usually, i have to delete the table contents and then reseed the tables.

TSQL Script:
1:  use Transmittal  
2:  go  
3:  delete from dbo.TransDetails;  
4:  delete from dbo.TransMaster;  
5:  DBCC CHECKIDENT (TransMaster, reseed, 0)  
6:  DBCC CHECKIDENT (TransDetails, reseed, 0)  

Validation not working if i added client script in a save button attribute property

In this scenario, I have a series of textbox controls that has required field validations and a save button with the following attribute property set in pageload event:
1:  btnSave.Attributes.Add("onclick", "return confirm  
2:  ('Proceed saving or updating this record?')");  

In most cases, this works fine, but the problem is if i clicked ok in the confirm dialog of javascript, the validation of required fields will be bypassed.

So the solution would be to modify the script to return false if cancel is pressed in the confirm dialog of javascript so that validation will work..

Here is the modified script:
 btnSave.Attributes.Add("onclick", "if(!confirm  
 ('Proceed saving or updating this record?'))  
 return false;");  

If the user will click ok, in the javascript confirm dialog, validations will be executed.

Thursday, December 23, 2010

Check if Leap Year

Below is a custom code i have been working to check if a year is considered as leap year.
Code:
  protected bool CheckLeap(int year)  
  {  
     if((year%4==0&&year%100!=0)||year%400==0)  
     {  
       return true;  
     }  
     return false;  
  }  

However, as i checked the DateTime class methods in MSDN, i found a handy tool to do the same functionality.
Code:
DateTime.IsLeapYear(int year);  

Cheers!

Tuesday, December 21, 2010

Re-order DataColumns in a DataTable

Here's how to re-order DataColumns in a DataTable. This solves a particular problem in a project I'm currently working with.
Code:
1
datatable.Columns["Col1"].SetOrdinal(1);

ADO.NET Entity Framework Tutorial

Here's an example from MSDN. There are some minor bugs that I encountered, but this is a good start.
ADO.NET Entity Framework in Winforms

Tuesday, December 14, 2010

Access DOM elements in ASP.NET Master/Content Pages using ClientID and jQuery

The example below will display Bill Murstein in asp.net textbox

Example:
1
2
3
4
5
6
var name = 'Bill Murstein';  
//javascript DOM  
document.getElementById('<%=txtCustomerName.ClientID%>').value = name;  

//jQuery Counterpart  
$('[id$=txtCustomerName]').val(name);  

Monday, December 13, 2010

jQuery in ASP.NET Ajax does not work after partial postback

I encountered a problem with jquery in asp.net ajax with master page content. During first pageload, the jquery script works fine, but after partial postback, the jquery script does not work.

After a few googling activity, I came upon this site:
http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/


This explains how to use document.ready, pageload, and Application.init. In my previous code, i've used document.ready since my aspx page was not ajax enabled. But since, Im switching my application to ajax ready, the solution I came upon was using function pageLoad() instead of document.ready().
Example:
1
2
3
4
5
6
7
function Pageload() {
    $("#txtsomething").blur(function() {
        //your js code here  
        var x = 25 + 25;
        alert(x);
    });
}

Hope this insight will help other developers out there...

Here is the summary from the direct link:

$(document).ready()
  • Ideal for onetime initialization.
  • Optimization black magic; may run slightly earlier than pageLoad().
  • Does not re-attach functionality to elements affected by partial postbacks.

pageLoad()

  • Unsuitable for onetime initialization if used with UpdatePanels.
  • Slightly less optimized in some browsers, but consistent.
  • Perfect for re-attaching functionality to elements within UpdatePanels.

Application.Init

  • Useful for onetime initialization if only ASP.NET AJAX is available.
  • More work required to wire the event up.
  • Exposes you to the “sys is undefined” error if you aren’t careful.

Formatting numbers with comma in JavaScript

In asp.net c#, this can be achieved by String.Format(), however in javascript/jquery, this can be achieved using a simple JavaScript function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  function addCommas(nStr) {
      nStr += '';
      x = nStr.split('.');
      x1 = x[0];
      x2 = x.length > 1 ? '.' + x[1] : '';
      var rgx = /(\d+)(\d{3})/;
      while (rgx.test(x1)) {
          x1 = x1.replace(rgx, '$1' + ',' + '$2');
      }
      return x1 + x2;
  }

In your script, you can call it using:
1
2
3
var number = 123456.99;  
var result = addCommas(number);  
alert(result);  

Source: JavaScript Number Format

Tuesday, December 7, 2010

Manipulating DataTable Columns and Rows

Hi!
I found this link to be of help. DataTable Manipulation

Saturday, December 4, 2010

CSS color for asp.net textbox in disabled state

i was wondering what's the hex equivalent of asp.net textbox color rendered in firefox/IE.
The default color is:
#7F9DB9 (Firefox/chrome/IE)
#DADADA (Safari)

CSS Code:
1
2
3
4
.Disabled  
{  
   border-color: #7F9DB9;  
}  

Or you may use the border attribute and define other properties such as border-style, border-width and border-color.

Wednesday, November 24, 2010

ScriptManager.RegisterStartupScript() vs. ClientScript.RegisterStartupScript()

Hi!

I have been struggling in manipulating scripts to focus to a particular control when a user executes a button or events triggered by postbacks.

The scenario was in every button clicked, the focus will be transferred to another control. These butttons are inside an update panel and ajax tab container.

The solution presented in an article i've previously posted was using ClientScript.RegisterStartupScript() to register a script. However, this script is registered in the Page object. But since my controls are inside an update panel which is partial postback rendering, the solution I've come up was using ScriptManager.RegisterStartupScript().

So, to register client scripts on an aspx page w/o ajax functionalities, use ClientScript:
1
ClientScript.RegisterStartupScript(this.GetType(), "MyScript", script.ToString(), false);  

And to register client scripts on an aspx page w/ ajax functionalities such as inside an update panel, use ScriptManager:
1
ScriptManager.RegisterStartupScript(this, this.GetType(), "MyScript", script.ToString(), false);  

Thursday, November 18, 2010

Assign Hexa Color to .NET control background color property

To convert hexa decimal color to Color in .NET and assign it to a control's background property, do the following:
1:  this.lblMachinery.BackColor = ColorTranslator.FromHtml("#CCCOOO");  


Wednesday, November 17, 2010

Register Client Scripts in ASP.NET using ClientScriptManager class

Source: ClientScriptManager Class
C# Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public void Page_Load(Object sender, EventArgs e) {
  // Define the name and type of the client scripts on the page.  
  String csname1 = "PopupScript";
  String csname2 = "ButtonClickScript";
  // Get a ClientScriptManager reference from the Page class.  
  System.Web.UI.ClientScriptManager cs = Page.ClientScript;
  // Check to see if the startup script is already registered.  
  if (!cs.IsStartupScriptRegistered(csname1)) {
   String cstext1 = "alert('Testing');";
   cs.RegisterStartupScript(GetType(), csname1, cstext1, true);
  }
  // Check to see if the client script is already registered.  
  if (!cs.IsClientScriptBlockRegistered(csname2)) {
   StringBuilder cstext2 = new StringBuilder();
   cstext2.Append("");
   cs.RegisterClientScriptBlock(GetType(), csname2, cstext2.ToString(), false);
  }
 }

HTML Markup
1
2
3
4
5
6
<body>  
   <form id="Form1" runat="server">  
   <input type="text" id="Message"/>   
   <input type="button" value="ClickMe" onclick="DoClick()" />  
    </form>  
</body>  

Tuesday, November 16, 2010

(AJAX Tab Container Error)htmlfile: Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus.

In my aspx page, I have an ajax tab container control, and inside each tab strip,i have server controls.

During pageload,i want to set focus on a particular control but got this error during page load:
htmlfile: Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus.

the solution is in this page:
Setting focus to a textbox when in a tab panel errors

Saturday, November 13, 2010

JavaScript Format Decimal Precision

Here's a resource where i came to change decimal precision on of numbers using client script. It explained on how to use the toFixed() and toPrecision(). However, there are bugs on this. So it's much better to set precision of numbers using server side script.

http://www.mredkj.com/javascript/nfbasic2.html

Monday, November 8, 2010

Gridview samples from MSDN

Here's a link of samples from MSDN. I have'nt tested all of them, but this might help to other developers out there.
GridView Examples for ASP.NET 2.0

Thursday, November 4, 2010

Paste HTML codes in your post

You might be wondering how the heck could i paste html code in my post. Well, there's a handy tool for that in this site:

http://francois.schnell.free.fr/tools/BloggerPaste/BloggerPaste.html

Scalar and Inline Table Functions

After reading some articles on TSQL, I made some experiments on User defined functions. Actually, there are three types of UDF. First we have the Scalar functions that returns a single value of the data type referenced in the RETURNS clause of the CREATE FUNCTION statement. The returned data can be of any type except text, ntext, image, cursor, or timestamp. Next we have Inline table-valued function which returns a variable of data type table whose value is derived from a single SELECT statement. Lastly, we have multi-statement table-valued function which is slightly more complicated than the other two types of functions because it uses multiple statements to build the table that is returned to the calling statement.
(Source: http://www.sqlteam.com)
For the sake of simplicity, I'll tackle the first two types of functions.

1. Scalar function example:
1:  create function ComputeSum(@FirstNum int, @SecondNum int)  
2:  returns int  
3:  as  
4:  begin  
5:  Declare @sum int  
6:  set @sum = (@FirstNum + @SecondNum)  
7:  return @sum  
8:  end  

Note: As you can see, the function takes two arguments of type int. Then on the function body, the computation proceeds, then calls the return statement.

--to execute function
 declare @result int  
 set @result = dbo.ComputeSum(5,10)  
 print @result  

15 will be displayed as output

2. Inline Table Functions (make sure you have adventureworks db in your sql server)
create function maxorder()
returns table
as
return select max(SalesOrderID) as LastOrderID
from Sales.SalesOrderHeader

--execute the function
select * from maxorder()

The output returned is: 75123 which is the latest order generated.

Wednesday, November 3, 2010

Simple jquery manipulation (Asp.Net)

I started learning jquery recently. This is a simple tutorial using asp.net website to show alert message and to change background color of label control. Add a label control, an asp.net button control, and input html button. Make sure to reference the jQuery library in your asp.net website.

jQuery Script:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$(document).ready(function() {
    $('#btnAlert').click(function() {
        alert('my first jquery app!');
    });
    $('#btnChangeBackColorLabel').click(function() {
        $('span').css("background-color", "blue");
    });
    $("span").click(function() {
        $(this).css("background-color", "yellow");
    });
});

HTML CODE:
1
2
3
4
5
6
7
<div>  
     <asp:Button ID="btnAlert" runat="server" Text="Show Alert" /> <br />  
      Click Change Me label itself to change background color to yellow<br />  
     <input id="btnChangeBackColorLabel" type="button" value="ChangeColorToBlue" />   
      <asp:Label ID="lblHi" runat="server" Text="Change Me" BorderStyle="Solid">  
    </ asp:Label>  
 </div>  

During page render,labels are rendered as span elements.

Cheers

Getting jquery intellisense to work with VS 2008

I recently played with jquery to work with asp.net/asp.net ajax.
1. Perform these steps in this website:
jQuery Intellisense in Visual Studio 2008
2. Download jquery-1.4.1-vsdoc.js and jquery-1.4.1.min.js from jquery website.
3. Include them in your asp.net website.
4. remove the min in jquery-1.4.1.min.js. So the new jquery library would be like this: jquery-1.4.1.js
5. Add reference to the jquery library in your javascript file.

That's it...Cheers!!!

Monday, November 1, 2010

Calling a SQL Server Stored Procedure using LINQ

1. Make sure you have Northwind database in your Sql server.
2. Create a simple stored procedure to retrieve customers based on a specific country.
The parameter of the stored procedure is of type varchar.
3. Create a simple asp.net website or winforms or console project.
4. Add a Linq to SQL class to your project.
5. Make sure to add the stored procedure in your linq to sql class.
6. In your asp.net website, add a button,textbox and a gridview.
7. In your button event click, add the following snippet:

1
2
3
4
5
6
7
8
protected void Bind()  
{  
    string country = this.txtCity.Text.Trim();  
    var cr = new NorthWindDataContext();  
    var north = cr.CustomerByCountry(country);  
    this.gridCustomers.DataSource = north;  
    this.gridCustomers.DataBind();  
}  

That's it...

Saturday, October 30, 2010

Incorrect Syntax near % sql parameter (C#)

When writing sql statements in your business logic layer, you often want to append % which is a literal in your query. An example would be like this:
Code:
string query = "Select * from Patient where LastName like '" + "@family" + " %'";
However, this would give you an error, since the @family parameter is inside the tick marks that makes it a literal, but the % sign should be inside the tick marks. So, the correct sql syntax would be this way:
Code:
string query = "Select * from Patient where LastName like (@family + '%')";

Source: VBForums Link

Wednesday, October 27, 2010

Set top property of text object and field object of crystal reports during runtime (Crystal Reports.NET)

I have encountered a scenario when creating crystal reports for a specific customer. In my reports, I have four controls.
1. Comments (Text Object) and Comments (Field object )w/ top properties of 3465.
2. Recommendations (Text Object) and Recommendations (Field object ) w/ top properties of 4505.

Here's what i need to do.
1
2
3
if ((recommendations field object != null) && (comments field object == null)))  
2:     If true, set top properties of Recommendations Text   
3:     object and commendations Field object to 3465.  

Solution in VBForums.
Greg

Linux, Free BSD, Oracle articles

Here's a site from a friend of mine containing series of topics on Linux and open source softwares.

http://www.opensolutions101.com/

"No description found" error message pops-up when creating a SQL Server maintenance plan in SQL Server 2005

If there are instances that you failed to create maintenance plan (backup plan) in MS SQL due to the error specified above, the solution would be to reregister MSXML.
Solution:
http://support.microsoft.com/kb/922546

Unable to Print Reports using Samsung Printers (ASP.NET)

I encountered lately an error when printing a report from a deployed asp.net website. I installed correctly the printer software/drivers. The printer used was Samsung.

Solution:
In Control Panel (Printers and Faxes), add asp.net user account to the default printer.

The Official Microsoft ASP.NET Site

http://www.asp.net/ (Main ASP.NET Website)