Monday, February 21, 2011

USB devices attached to this computer has malfunctioned

This problem drove my IT support nuts, but there is a simple way 5 steps process to resolve the problem:

1. Disconnect all USB devices from the computer.
2. Go to BIOS and set USB as the 1st to load. This will make sure the device driver is loaded before Windows start.
3. Go to Windows in Safe mode - this will load all the device drivers again.
4. Switch off your computer for 30 mins so that the last faulty USB error memory that is stored in BIOS is cleared.
5. Restart your computer.


This works for all the cases of this problem I have found so far.

Thursday, August 26, 2010

Saving Changes is not Permitted. The changes you made requires the table to be dropped and recreated...

One of the new things that happens in SQL Server 2008 is that it prevents saving table structure changes that require the table to be dropped and re-created. While this is a great feature to prevent accidents from occurring, on a developer machine it can be quite frustrating. This is the dialog you get when trying to make changes in a table design.



Unfortunately, this dialog doesn’t tell you where to turn this feature off! Clicking on the small “?” on the title bar does get you to a help page that tells you how to do it.

Anyway, the place to do it is Tools > Options > Designers > Table and Database Designers > Prevent saving changes that require table re-creation. Turn this option off and you will be able to save the tables again.

Thursday, May 28, 2009

SQL Server 2005: Importing from Excel error 0xc020901c

Error 0xc020901c: Data Flow Task: There was an error with output column "Agenda 2" (63) on output "Excel Source Output" (9). The column status returned was: "Text was truncated or one or more characters had no match in the target code page.".


To fix the problem

  • To change the value of TypeGuessRows, use these steps:
  • On the Start menu, click Run. In the Run dialog box, type Regedt32, and then click OK.
  • Open the following key in the Registry editor:

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel
  • Double-click TypeGuessRows.
  • In the DWORD editor dialog box, click Decimal under Base. Type a value between 0 
  • Click OK, and then exit the Registry Editor.

http://support.microsoft.com/kb/281517/EN-US/

Wednesday, May 13, 2009

How to Close Web Browsers

btn.Attributes.Add("OnClick", "self.close()");
will do the trick.
Another alternative is
Response.Write (" < script > self.close() ; < /script >
");

Wednesday, April 22, 2009

DataBase could not be exclusively Locked when renaming a database

The problem is due to other users using the database. To resolve the problem, you set the database to be used only by yourself. After the rename operation, you need to reset it back to be usable by other users. It is a common courtesy to inform all users prior to doing this operation.

ALTER DATABASE DBNAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
SP_RENAMEDB @dbname = 'old_name' ,
@newname = 'new_name'
Go
ALTER DATABASE NEWDBNAME SET MULTI_USER -- set back to multi user
GO

Monday, March 16, 2009

How to Sort or handle Paging in GridView Manually without databinding

The GridView 'GridViewID' fired event PageIndexChanging which wasn't handled.
The GridView 'GridViewID' fired event Sorting which wasn't handled.

private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;

switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;

case SortDirection.Descending:
newSortDirection = "DESC";
break;
}

return newSortDirection;
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
int pageIndex = this.GridView1.PageIndex;
this.GridView1.DataSource = SortDataTable(GridView1.DataSource as DataTable, false);
this.GridView1.DataBind();
this.GridView1.PageIndex = pageIndex;

}

private string GridViewSortDirection
{
get
{
return ViewState["SortDirection"] as string ?? "ASC";
}

set
{
ViewState["SortDirection"] = value;
}
}



private string GridViewSortExpression
{
get
{
return ViewState["SortExpression"] as string ?? string.Empty;
}
set
{
ViewState["SortExpression"] = value;
}
}



private string GetSortDirection()
{
switch (GridViewSortDirection)
{
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}



protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.GridView1.DataSource = SortDataTable(this.GridView1.DataSource as DataTable, true);
this.GridView1.PageIndex = e.NewPageIndex;
this.GridView1.DataBind();
}

protected DataView SortDataTable(DataTable dataTable, bool isPageIndexChanging)
{
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
if (GridViewSortExpression != string.Empty)
{
if (isPageIndexChanging)
{
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection);
}
else
{
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GetSortDirection());
}
}
return dataView;
}

else
{
return new DataView();
}
}

How to have Display Number in GridView

< asp:TemplateField >
< ItemTemplate >
< %# Container.DataItemIndex + 1 % >
< /ItemTemplate >
< /asp:TemplateField >

Tuesday, March 10, 2009

Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started..

The error that you are getting is because your StateServer is not enabled. You have to go to AdministrativeTools > Computer Management > Services and Applications >Services and start the ASP.NET State Service

The SQL Server Service Broker for the current database is not enabled, and as a result query notifications are not supported...

This problem frequently occurs when you just restored a database, but service brokers are broken or lost.

To resolve this problem.

alter database xxxx set NEW_BROKER

Alternatively,

1. Go to Programs -> Microsoft Sql Server 2005 -> Configuration Tools -> Sql Server Surface Area Configuration -> Surface Area Configuration for Features.
2. Locate "Service Broker" under the database engine and enable it.

Sunday, March 08, 2009

Wednesday, November 26, 2008

How to get rid of "Warning as an Error" message

In the web config file, added the following add in Red under the compilers section for each compiler you have.

<compilers>

<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

<providerOption name="WarnAsError" value="false"/>
</compiler>

</compilers>

The type or namespace name 'Script' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)

To resolve this problem, please ensure that you have the system.web.extension dll added as a reference in your project.

Alternatively, copying the system.web.extension.dll to the bin directory for a deployment project should resolve the problem.

Wednesday, November 05, 2008

How to Show File Dialog

Here is some code to allow users to select Folder.

public class FolderBrowser : FolderNameEditor
{
private FolderNameEditor.FolderBrowser m_obBrowser = null;
private string m_strDescription;
public FolderBrowser()
{
m_strDescription = "Select folder";
m_obBrowser = new FolderNameEditor.FolderBrowser();
}

public string DirectoryPath
{
get{return this.m_obBrowser.DirectoryPath;}
}

public DialogResult ShowDialog()
{
m_obBrowser.Description = m_strDescription;
return m_obBrowser.ShowDialog();
}
}

Wednesday, July 16, 2008

How to Restore a MSSQL backup (.bak)

Run the command in MSSQL to restore a .bak file

RESTORE DATABASE [abc]
FROM DISK = 'C:\backup_200807102327.bak'
with move 'abc' to 'C:\Database\abc.mdf',
move 'abc_LOG' to 'C:\Database\abc.LOG',
Replace
GO

Monday, June 30, 2008

How to sort and allow paging manually using Gridview

private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;

switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;

case SortDirection.Descending:
newSortDirection = "DESC";
break;
}

return newSortDirection;
}

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = gridView.DataSource as DataTable;

if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

gridView.DataSource = dataView;
gridView.DataBind();
}
}

Thursday, June 26, 2008

How to have a pop out dialog box in ASP.NET

JHaIn all good web applications, the user is asked to confirm whether he/she wants to delete something in case the delete button was pressed accidentally.

Although it seems like a pain to do, it is actually really easy if you find it acceptable to use javascript's “confirm” statement, which will popup a dialog box with a particular question with “ok” and “cancel” buttons. You have no control of the title of the popup, but in IE it says “Microsoft Internet Explorer“ and I believe it says “[Javascript Application]“ or similar in Firebird.





The javascript code for it is simple:


function confirm_delete()
{
if (confirm("Are you sure you want to delete the custom search?")==true)
return true;
else
return false;
}


Using code-behind, you can attach the javascript popup dialog to the button:


_myButton.Attributes.Add("onclick", "return confirm_delete();");

When you click on the delete button, the javascript popup dialog asks if you want to delete the search. If you choose “cancel“, your “DeleteSearch_Click” event is never fired. If you choose “ok”, the event is fired and you can delete the item.

How to Select a Row in GridView without using select button


....
....
....


protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs
e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick",
ClientScript.GetPostBackEventReference(MyGridView, "Select$" +
e.Row.RowIndex.ToString()));
e.Row.Style.Add("cursor", "pointer");
}
}

protected void MyGridView_SelectedIndexChanged(object sender, EventArgs e)
{
string strSelectedID = MyGridView.SelectedValue.ToString();
}

Wednesday, June 18, 2008

How to Authenticate User using a customed Database

If you want to authenticate a user against your own custom database then you can use the Authenticate event of the Login control. Here is a small example that shows how to achieve it.

// Use Authenticate event if you want to do custom authentication

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)

{

string userName = Login1.UserName;

string password = Login1.Password;

bool result = UserLogin(userName, password);

if (result)

e.Authenticated = true;

else

e.Authenticated = false;

}

private bool UserLogin(string userName, string password)

{

string query = @"SELECT UserName FROM Users WHERE

UserName = @UserName AND Password = @Password";

string connectionString = (string)ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

SqlConnection myConnection = new SqlConnection(connectionString);

SqlCommand myCommand = new SqlCommand(query, myConnection);

myCommand.Parameters.AddWithValue("@UserName", userName);

myCommand.Parameters.AddWithValue("@Password", password);

myConnection.Open();

string userId = (string) myCommand.ExecuteScalar();

myConnection.Close();

if (userId != null && userId.Length > 0)

return true;

else return false;

}

As you can see that I am simply sending the values from the Login control to UserLogin method and returns true or false based on the authentication status.

When using custom authentication always remember to set the Authenticated property of the Login control to true or false based on the result of authentication. Also when authenticating a user against a custom database you don't need to provide the membership settings in the web.config file.

How to use CheckBox in GridView.

Introduction

In the preceding tutorial we examined how to add a column of radio buttons to the GridView for the purpose of selecting a particular record. A column of radio buttons is a suitable user interface when the user is limited to choosing at most one item from the grid. At times, however, we may want to allow the user to pick an arbitrary number of items from the grid. Web-based email clients, for example, typically display the list of messages with a column of checkboxes. The user can select an arbitrary number of messages and then perform some action, such as moving the emails to another folder or deleting them.

In this tutorial we will see how to add a column of checkboxes and how to determine what checkboxes were checked on postback. In particular, we’ll build an example that closely mimics the web-based email client user interface. Our example will include a paged GridView listing the products in the Products database table with a checkbox in each row (see Figure 1). A “Delete Selected Products” button, when clicked, will delete those products selected.

Each Product Row Includes a Checkbox

Figure 1: Each Product Row Includes a Checkbox (Click to view full-size image)

Step 1: Adding a Paged GridView that Lists Product Information

Before we worry about adding a column of checkboxes, let’s first focus on listing the products in a GridView that supports paging. Start by opening the CheckBoxField.aspx page in the EnhancedGridView folder and drag a GridView from the Toolbox onto the Designer, setting its ID to Products. Next, choose to bind the GridView to a new ObjectDataSource named ProductsDataSource. Configure the ObjectDataSource to use the ProductsBLL class, calling the GetProducts() method to return the data. Since this GridView will be read-only, set the drop-down lists in the UPDATE, INSERT, and DELETE tabs to “(None)”.

Create a New ObjectDataSource Named ProductsDataSource

Figure 2: Create a New ObjectDataSource Named ProductsDataSource (Click to view full-size image)

Configure the ObjectDataSource to Retrieve Data Using the GetProducts() Method

Figure 3: Configure the ObjectDataSource to Retrieve Data Using the GetProducts() Method (Click to view full-size image)

Set the Drop-Down Lists in the UPDATE, INSERT, and DELETE Tabs to “(None)”

Figure 4: Set the Drop-Down Lists in the UPDATE, INSERT, and DELETE Tabs to “(None)” (Click to view full-size image)

After completing the Configure Data Source wizard, Visual Studio will automatically create BoundColumns and a CheckBoxColumn for the product-related data fields. Like we did in the previous tutorial, remove all but the ProductName, CategoryName, and UnitPrice BoundFields, and change the HeaderText properties to “Product”, “Category”, and “Price”. Configure the UnitPrice BoundField so that its value is formatted as a currency. Also configure the GridView to support paging by checking the “Enable Paging” checkbox from the smart tag.

Let’s also add the user interface for deleting the selected products. Add a Button Web control beneath the GridView, setting its ID to DeleteSelectedProducts and its Text property to “Delete Selected Products”. Rather than actually deleting products from the database, for this example we’ll just display a message stating the products that would have been deleted. To accommodate this, add a Label Web control beneath the Button. Set its ID to DeleteResults, clear out its Text property, and set its Visible and EnableViewState properties to False.

g="{0:c}" HeaderText="Price" HtmlEncode="False" SortExpression="UnitP

T
ake a moment to view the page in a browser (see Figure 5). At this point you should see the name, category, and price of the first ten products.
The Name, Category, and Price of the First Ten Products are Listed

Figure 5: The Name, Category, and Price of the First Ten Products are Listed (Click to view full-size image)

Step 2: Adding a Column of Checkboxes

Since ASP.NET 2.0 includes a CheckBoxField, one might think that it could be used to add a column of checkboxes to a GridView. Unfortunately, that is not the case, as the CheckBoxField is designed to work with a Boolean data field. That is, in order to use the CheckBoxField we must specify the underlying data field whose value is consulted to determine whether the rendered checkbox is checked. We cannot use the CheckBoxField to just include a column of unchecked checkboxes.

Instead, we must add a TemplateField and add a CheckBox Web control to its ItemTemplate. Go ahead and add a TemplateField to the Products GridView and make it the first (far-left) field. From the GridView’s smart tag, click on the “Edit Templates” link and then drag a CheckBox Web control from the Toolbox into the ItemTemplate. Set this CheckBox’s ID property to ProductSelector.

Add a CheckBox Web Control Named ProductSelector to the TemplateField’s ItemTemplate

Figure 6: Add a CheckBox Web Control Named ProductSelector to the TemplateField’s ItemTemplate (Click to view full-size image)

With the TemplateField and CheckBox Web control added, each row now includes a checkbox. Figure 7 shows this page, when viewed through a browser, after the TemplateField and CheckBox have been added.

Each Product Row Now Includes a Checkbox

Figure 7: Each Product Row Now Includes a Checkbox (Click to view full-size image)

Step 3: Determining What Checkboxes Were Checked On Postback

At this point we have a column of checkboxes but no way to determine what checkboxes were checked on postback. When the “Delete Selected Products” button is clicked, though, we need to know what checkboxes were checked in order to delete those products.

The GridView’s Rows property provides access to the data rows in the GridView. We can iterate through these rows, programmatically access the CheckBox control, and then consult its Checked property to determine whether the CheckBox has been selected.

Create an event handler for the DeleteSelectedProducts Button Web control’s Click event and add the following code:

Protected Sub DeleteSelectedProducts_Click(sender As Object, e As EventArgs) _ Handles DeleteSelectedProducts.Click

Dim atLeastOneRowDeleted As Boolean = False
' Iterate through the Products.Rows property For Each row As GridViewRow In Products.Rows
' Access the CheckBox Dim cb As CheckBox = row.FindControl("ProductSelector")
If cb IsNot Nothing AndAlso cb.Checked Then
' Delete row! (Well, not really...)
atLeastOneRowDeleted = True
' First, get the ProductID for the selected row
Dim productID As Integer = _ Convert.ToInt32(Products.DataKeys(row.RowIndex).Value)
' "Delete" the row DeleteResults.Text &= String.Format( _ "This would have deleted ProductID {0}
", productID)

The Rows property returns a collection of GridViewRow instances that makeup the GridView’s data rows. The For Each loop here enumerates this collection. For each GridViewRow object, the row’s CheckBox is programmatically accessed using row.FindControl("controlID"). If the CheckBox is checked, the row’s corresponding ProductID value is retrieved from the DataKeys collection. In this exercise, we simply display an informative message in the DeleteResults Label, although in a working application we’d instead make a call to the ProductsBLL class’s DeleteProduct(productID) method.

With the addition of this event handler, clicking the “Delete Selected Products” button now displays the ProductIDs of the selected products.

When the “Delete Selected Products” Button is Clicked the Selected Products’ ProductIDs are Listed

Figure 8: When the “Delete Selected Products” Button is Clicked the Selected Products’ ProductIDs are Listed (Click to view full-size image)

Step 4: Adding “Check All” and “Uncheck All” Buttons

If a user wants to delete all products on the current page, they must check each of the ten checkboxes. We can help expedite this process by adding a “Check All” button that, when clicked, selects all of the checkboxes in the grid. An “Uncheck All” button would be equally helpful.

Add two Button Web controls to the page, placing them above the GridView. Set the first one’s ID to CheckAll and its Text property to “Check All”; set the second one’s ID to UncheckAll and its Text property to “Uncheck All”.

Next, create a method in the code-behind class named ToggleCheckState(checkState) that, when invoked, enumerates the Products GridView’s Rows collection and sets each CheckBox’s Checked property to the value of the passed in checkState parameter.

Private Sub ToggleCheckState(ByVal checkState As Boolean) ' Iterate through the Products.Rows property For Each row As GridViewRow In Products.Rows ' Access the CheckBox Dim cb As CheckBox = row.FindControl("ProductSelector") If cb IsNot Nothing Then cb.Checked = checkState End If Next End Sub

Next, create Click event handlers for the CheckAll and UncheckAll buttons. In CheckAll’s event handler, simply call ToggleCheckState(True); in UncheckAll, call ToggleCheckState(False).

Protected Sub CheckAll_Click(sender As Object, e As EventArgs) _ Handles CheckAll.Click ToggleCheckState(True) End Sub Protected Sub UncheckAll_Click(sender As Object, e As EventArgs) _ Handles UncheckAll.Click ToggleCheckState(False) End Sub

With this code, clicking the “Check All” button causes a postback and checks all of the checkboxes in the GridView. Likewise, clicking “Uncheck All” unselects all checkboxes. Figure 9 shows the screen after the “Check All” button has been checked.

Clicking the “Check All” Button Selects All Checkboxes

Figure 9: Clicking the “Check All” Button Selects All Checkboxes (Click to view full-size image)

Note: When displaying a column of checkboxes, one approach for selecting or unselecting all of the checkboxes is through a checkbox in the header row. Moreover, the current “Check All” / “Uncheck All” implementation requires a postback. The checkboxes can be checked or unchecked, however, entirely through client-side script, thereby providing a snappier user experience. To explore using a header row checkbox for “Check All” and “Uncheck All” in detail, along with a discussion on using client-side techniques, check out Checking All CheckBoxes in a GridView Using Client-Side Script and a Check All CheckBox.

Summary

In cases where you need to let users choose an arbitrary number of rows from a GridView before proceeding, adding a column of checkboxes is one option. As we saw in this tutorial, including a column of checkboxes in the GridView entails adding a TemplateField with a CheckBox Web control. By using a Web control (versus injecting markup directly into the template, as we did in the previous tutorial) ASP.NET automatically remembers what CheckBoxes were and were not checked across postback. We can also programmatically access the CheckBoxes in code to determine whether a given CheckBox is checked, or to chnage the checked state.

This tutorial and the last one looked at adding a row selector column to the GridView. In our next tutorial we’ll examine how, with a bit of work, we can add inserting capabilities to the GridView.


Wednesday, June 11, 2008

Method Error 500

I've been assigned a bug concerning an AJAX cascading drop down combo box. When the Ajax cascading drop down combo box's value is changed by the user, a secondary combo box has its values reloaded. This is done by calling a web service. The bug is that "Method Error 500" is displayed as the only item on occasion.

After some rooting around, it turns out that this is caused by too much data being returned in the SQL query behind the web service call, so the web service returns an error. A simple change to the web.config file can increase the size limit of data returned:

<system.web.extensions>
<scripting>
<webservices>
<jsonserialization maxjsonlength="5000000">
</jsonserialization>
</webservices>
</scripting>
<system.web.extensions>
<scripting>
<webservices>
<jsonserialization maxjsonlength="5000000">
</jsonserialization>
</webservices>
</scripting>
</system.web.extensions></system.web.extensions>