Wednesday, December 23, 2009

Tester vs. Developer

Developer vs. Tester

This is just an intermezzo... lol :D


Monday, December 7, 2009

Error while trying to debug VB.NET desktop application

Error while trying to run project: Could not load file or assembly "AssemblyName" or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

This error appears as a dialog box while trying to debug an application.

1. Check if the assembly name used for the project contains ' (apostrophe). If it does, go change it, and do not use ' (apostrophe)
2. Check if the name "Program" (without quotes) is used as the assembly name. If it is, go change the name.
3. If still, it does not work, right-click on the Project -> Properties -> Choose tab Debug -> Uncheck the option "Enable the Visual Studio Hosting Process"


Tuesday, November 10, 2009

Ado command object returns method 'Execute' of object '_Connection' failed

Error: method 'Execute' of object '_Connection' failed

Solution: Check the query used while executing the recordset, it may contain keyword used in the database. In my case, my query is:

select languageid, language from masterlanguage order by languageid

The error occurs because I use a keyword in the query, i.d. language.
To fix the error, either change the column name on the database, or use []:

select languageid, [language] from masterlanguage order by languageid


Friday, November 6, 2009

Disabling web.config inheritance for child application

Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Could not load file or assembly 'Control' or one of its dependencies. The system cannot find the file specified. (d:\Web\VS\Website\web.config line 82)

Source Error:

Line 77: <httphandlers>
Line 78: <remove path="*.asmx" verb="*">
Line 79: <add path="*.asmx" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false">
Line 80: <add path="*_AppService.axd" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false">
Line 81: <add path="ScriptResource.axd" verb="GET,HEAD" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false">
Line 82: <add path="SecurityImageHandler.ashx" verb="*" type="Control.SecurityImageControlHandler, Control">
Line 83: </httphandlers>

I have an application which has a child (sub folder) application in it. In my case, I added a tag in the parent application:

<add path="SecurityImageHandler.ashx" verb="*" type="Control.SecurityImageControlHandler, Control">

When deployed, an error occurs in the child application, since the assembly added in the parent application is also recognized by the child application. To avoid the child application from reading the tag added on the parent application, we have to remove the tag on the web.config of the child application.

After adding the code to remove the tag, it will look like this:

<remove verb="*" path="SecurityImageHandler.ashx"/>


Pinky award :D

Another award from a sweet friend, Ria Adria ^^


Wednesday, November 4, 2009

Error uploading file in ASP.NET

XML Parsing Error: no element found
Line Number 1, Column 1:

This error occurs because the size of the file uploaded is too big and not handled in the web.config.

Solution: add this tag to the web.config in the <system.web></system.web> section:

<httpRuntime maxRequestLength="2048000">

There's a limitation used in the maxRequestLength. 2048000 is the value I use in VS 2008. If I'm not mistaken, in VS 2003, the maxRequestLength is 1024000. Note that this value is in KB (Kilo Byte).

Sunday, November 1, 2009

Another blog award ^^

Have just got a lovely blog award, my second one, from a friend, Mona ^^

But there is a rule to accept this award.. hehehe... Post it on your blog together with the name of the person who has granted the award, and his or her blog link. Pass the award to 15 other blogs that you’ve newly discovered. Remember to contact the bloggers to let them know they have been chosen for this award.

I don't have too many blogging friends, so I'll just give it to...


Wednesday, October 14, 2009

Creating Sub Report using TTX in VB

Before creating sub report using TTX in VB, you should have already known how to create report using TTX. Otherwise, you may want to find out how to create report using TTX in my previous post.

Before going to the sub report, it's a good idea to share the code query in Visual Basic used to retrieve the data first.

Private Sub cmdPrint_Click()
Dim rs As New ADODB.Recordset 'recordset for main report
Dim rs1 As New ADODB.Recordset 'recordset for subreport
Dim sql As String
With CrystalReport1
'Set data for main report
sql = "select CustomerID, CompanyName, ContactName, ContactTitle, " & _
"Address from Customers where Country = '" & cmbCountry.Text & "'"
Set rs = New ADODB.Recordset
Set rs = con.Execute(sql)

.ReportFileName = App.Path & "/RptTest.rpt"
.Destination = crptToWindow
.SetTablePrivateData 0, 3, rs
'End set data for main report

'Set data for subreport
.SubreportToChange = .GetNthSubreportName(0)
sql = "select a.customerid, d.productname, c.quantity, c.unitprice " & _
"from customers a " & _
"left join orders b " & _
"on b.customerid = a.customerid " & _
"left join orderdetails c " & _
"on c.orderid = b.orderid " & _
"left join products d " & _
"on d.productid = c.productid " & _
"order by a.customerid, d.productname"
Set rs1 = New ADODB.Recordset
Set rs1 = con.Execute(sql)
.SetTablePrivateData 0, 3, rs1
'End set data for subreport

.WindowState = crptMaximized
.WindowShowPrintBtn = True

.Action = 1
End With
End Sub

Suppose here's the data retrieved in the main report:

And here's the data retrieved in the sub report:

In this case, we would retrieve the data on the main report, while at the same time, show the orders made by each customer.

Note that there has to be one or more linking fields between the report and sub report in this case. In the data shown above, the linker is the field CustomerId.

Steps in creating the sub report:
1. Assume the main report is done, like the following picture (if you have not tried making the main report, you may want to refer to my previous post about making the main report):

2. To insert sub report, choose menu Insert -> Subreport, then a dialog box will be prompted, insert the desired sub report name, then click Report Expert.

3. Another dialog boxes will be prompted, we will have to create new TTX for the sub report. The steps are the same as those used in creating the TTX for the main report.

4. After finished creating the TTX, add the TTX to the report.

5. Then, go to tab Fields, Add the fields to be displayed on the report, then click OK.

6. And here's the report with the sub report embedded in it.

7. To Edit the view of sub report, double click on the report, and arrange it to get desired layout.

8. After done with the layout of the sub report, we have to go back to the main report to link the report and the sub report to get desired data grouped by certain field(s). In the data used above, the linker field is CustomerId. Right-click on the sub report, choose Change Subreport Links. As we're going to link the field CustomerId in the main report and the subreport, choose the field on the main report, then select the linking field in the sub report (Make sure the field linked on the lower right is the field which belongs to the sub report, not the main report). Click OK.

9. Now we're finished with the main and sub report.

After running the program, we will get a report which contains the data of the Customers and the order details of each customer as the picture shown below.

That's all folks... Good Luck ^^

Friday, October 2, 2009

Playing with Query - Grouping

Query Language : SQL

Simply saying, here are the tables:
table users (userid, name)
table book (bookid, bookname, author)
table review (reviewId, UserId, BookId, Comment, ReviewDate)

Question: Find users who have reviewed 2 different books on the same day!

Query for creating tables:
create table users (userid int , [name] varchar(50))
create table book (bookid int, bookname varchar(50), author varchar(50))
create table review (reviewId int , UserId int, BookId int, Comment varchar(50), ReviewDate datetime)

Query for data sample:
insert into users values (1, 'A')
insert into users values (2, 'B')
insert into users values (3, 'C')

insert into book values (1, 'Book A', 'Author A')
insert into book values (2, 'Book B', 'Author B')
insert into book values (3, 'Book C', 'Author C')

insert into review values (1, 1, 1, 'AAAA', getdate()-5)
insert into review values (2, 1, 2, 'AAAA', getdate()-5)
insert into review values (3, 1, 3, 'AAAA', getdate()-5)
insert into review values (4, 2, 1, 'AAAA', getdate()-4)
insert into review values (5, 2, 2, 'AAAA', getdate()-4)
insert into review values (6, 2, 1, 'AAAA', getdate())
insert into review values (7, 3, 2, 'AAAA', getdate())
insert into review values (8, 3, 1, 'AAAA', getdate())

By using the query below:
select a.userid, a.userid,, a.bookid, c.bookname, a.reviewdate
from review a
left join users b on b.userid = a.userid
left join book c on c.bookid = a.bookid

The resulting records will be:

select * from
   select userid, bookSum = count(userid), reviewDate = convert(char(10), reviewdate, 105)
   from review
   group by userid, convert(char(10), reviewdate, 105)
) a
where bookSum = 2


select userid, bookSum = count(bookid), reviewDate
from review
group by userid, convert(char(10), reviewdate, 105)
having count(bookid) = 2

And the resulting records will be:

PS: Convert to type 105 is only aimed to convert the type of the date to dd-MM-yyyy so that the date to be compared does not include the time.

Wednesday, September 30, 2009

Fail creating virtual directory

Error: Creation of the virtual directory http://localhost/web failed with error: Could not find the server 'http://localhost' on the local machine. Creating a virtual directory is only supported on the local IIS server.

This error appear as a dialog box when trying to load a project whose virtual directory had been created formerly.

Actually, there are two dialog box:
1. The first dialog box sounds: The local IIS URL http://localhost for Web project web has not been configured. In order to open this project the directory needs to be configured. Would you like to create the virtual directory now?

2. After clicking yes, the second dialog box appears: Creation of the virtual directory http://localhost/web failed with error: Could not find the server 'http://localhost' on the local machine. Creating a virtual directory is only supported on the local IIS server.

The solutions may vary in this case. Here are some possible solutions:
1. Make sure the is already registered to the IIS. You may want to try registering it to IIS

2. The virtual directory of the project might not have been set properly, so it can not be loaded. Edit the virtual directory of the project by right-clicking the project, choose Edit project (.csproj) file, then at the bottom part of the file, you may find something like <iisurl>http://localhost/</iisurl>
Change / add the name of the web project, e.g. <iisurl>http://localhost/webname</iisurl>

3. Make sure the IIS is running well on services.msc. To check it, press windows + Run, type "Services.msc" (without quotes), then restart IIS Admin.

Afterwards, restart the IIS by pressing windows + Run, type "inetmgr" (without quotes), then start the service.

4. This is a rare case, but someones might encounter it too. If you are using another web server on your computer, e.g. Apache, xampp, etc., make sure you stop the web server first, then start the IIS. In a case I met, it still didn't work, after about half an hour trying to find the problem, I found the issue. Someone changed the port used for the web server. So, I had to change it again.
On the IIS window, right click on the Default Web Site, choose Properties, then make sure the port used is 80 (I'm not sure if using another port is ok here).


Friday, August 21, 2009

Login fail for Sql User

Error: server: msg 18452, level 16, state 1 [microsoft][odbc sql server driver][sql server]login failed for user 'user_name'. Reason: not associated with a trusted sql server connection

Solution: Open Sql Server Enterprise Manager, go to SQL Server Group -> Choose the server -> right-click, Properties -> choose tab Security -> Choose Sql Server and Windows for Authentication, then click OK, and don't forget to restart the service to make sure the new settings work.


Thursday, August 13, 2009

Awards from friend

I've just noticed the way to put awards from friends... hahaha.. lol
Awards from Ria Adria ^^


Tuesday, July 28, 2009

Unable to start debugging on the web server

Error : Error while trying to run project: Unable to start debugging on the web server. Server side-error occurred on sending debug HTTP request.

Make sure the server is operating correctly. Verify there are no syntax errors in web.config by doing a Debug.Start without Debugging. You may also want to refer to refer to the ASP.NET and ATL Server debugging topic in the online documentation.

This error appears as a dialog box while trying to debug a web application.

Solution : Run the application without debugging. You can :
1. Use Ctrl + F5, not F5, or
2. Directly type the URL address on the browser, or
3. Open IIS by pressing window + R, then type inetmgr, expand the web application under development, and browse it

You'll see the source of the error.

In a case I met, it's because of the unavailability of an impersonate user on the computer, while in the web.config, an impersonate user is used.

In case you meet the same condition; and in the web.config, there exists such code as:

<identity impersonate="true" username="uploaduser" password="uploaduser">

Go to Computer Management by pressing Window + R, then type "compmgmt.msc" (without quotes) -> Expand Local Users and Groups -> Users. If the user : uploaduser defined in web.config does not exist there, make the user by right-clicking, New User -> fill the user's information. Otherwise, if the user already exists, make sure that the account is not disabled. Just enable it by going to the properties if it is currently disabled.

Saturday, July 25, 2009

Making table of contents in ms. word 2007

There are times when we need to make table of contents after making an article. It would be quite troublesome to make it manually if the article is long enough. Fortunately, if you're writing it in ms. office, there has been a functionality provided for it.

Here is a video about how to make table of contents using ms. word 2007. It should be more or less the same using earlier or later version of ms. word ^^


Friday, July 24, 2009

Retrieving Tables and Columns in a Database

This is how to retrieve tables & columns in the table from a database:

Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Set rs = con.OpenSchema(adSchemaColumns)

While Not rs.EOF
Text1.Text = Text1.Text & rs!Table_Name & " - " & rs!COLUMN_NAME & vbCrLf


Retrieving Tables in a Database

This is how to retrieve all tables in a database:
Object needed:
A Textbox named Text1

Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Set rs = con.OpenSchema(adSchemaTables)
While Not rs.EOF
If rs!Table_Type = "TABLE" Then Text1.Text = Text1.Text & rs!TABLE_NAME & vbCrLf


How to get column names of a table

This is how to retrieve column / field names of a table from VB using adodb connection:

con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\database.mdb;Persist Security Info=False"

Set rs = New ADODB.Recordset
sql = "select * from table_name"
Set rs = con.Execute(sql)

Dim i As Integer
For i = 0 To rs.Fields.Count - 1
MsgBox rs.Fields(i).Name


Thursday, July 23, 2009

CustomError mode

Error :

Server Error in '/' Application.
Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

Details: To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".

<!-- Web.Config Configuration File -->

<customErrors mode="Off"/>

Notes: The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's <customerrors> configuration tag to point to a custom error page URL.

<!-- Web.Config Configuration File -->

<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>

Solution : The exact error hidden in this error message may vary. To reveal and see the error, changing the customErrors mode is necessary.
In web.config, change to mode to RemoteOnly or Off.
Changing the mode to RemoteOnly will enable the error message to be displayed when the web is viewed on the server.
Meanwhile, changing the mode to Off will enable the error message to be displayed when the web is viewed either on the server of outside.

<customErrors mode="Off" defaultRedirect="ErrorPage.aspx">
<error statusCode="404" redirect="ErrorPage.aspx?errNo=404"/>

Error detected by database DLL

Error : Error detected by database DLL

This error occurs when trying to open report produced using Crystal Report in application, one of which is application developed using VB.

Solution :
1. If you are using ODBC, make sure the ODBC has been created.

Here are the steps to create ODBC for the connection to the database, press Window + Run, then type "ODBCAD32" (without quotes). Then, on the User DSN tab, press Add.

A dialog box will be shown:

Click the Add button and choose SQL Server.

Insert the name of the database and server.

Next, if you're using SQL Server authentication, insert the login ID and password; otherwise, choose Windows Authentication.

2. If you've created the ODBC in User DSN tab, and still get the error, try doing step 1 again for the System DSN tab while creating the ODBC.

3. If still, it does not work, check the query used in your report, and make sure the stored procedure used in the report (in case you are using stored procedure) has been granted for the application itself. This is sometimes forgotten by developer ^^
To grant the stored procedure to the database user used in the application:
grant exec on spr_spname to database_user_name


Adding web reference in Visual Studio 2008 or later

Some people get confused adding web reference in Visual Studio 2008 or later, since it's not by default in the Solution explorer. Only Service reference is shown.

Web reference is actually still available on Visual Studio 2008 or later.
Just right-click on the project where the web reference is to be added, choose Add Service Reference, then click Advanced button. Click Add Web Reference beneath, then insert the URL address of the web service, Go. If the URL address is correct, it will be shown in the listbox saying "Web services found at this URL". Insert the reference name, then click Add Reference, OK.

That's all folks ^^

Wednesday, July 15, 2009

Operation is not allowed when object is closed

Error: Operation is not allowed when object is closed.

1. Check if a recordset or connection is opened before recordset operation is performed.

2. If stored procedure is used while retrieving the data to recordset, REMEMBER to use "SET NOCOUNT ON" at the beginning of the stored procedure. This is a problem which usually occurs when multiple actions are executed in a stored procedure.

3. Again, if stored procedure is used, make sure the stored procedure does return a record. Otherwise, make sure there is a routine in the code checking if the record doesn't return nothing.


create procedure dbo.spr_getData
set nocount on

select ......

select ......

set nocount off

Friday, July 3, 2009

Posting to blog from Ms. Office 2007

You can directly post to your blog without having to go your blog first.

Simply open your Microsoft Word 2007, then choose New -> New Blog Post.


Tuesday, June 30, 2009

Validation of viewstate MAC failed

Error : Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machinekey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Solution : Add this part to the web.config System.Web section:
<pages enableEventValidation="false" viewStateEncryptionMode ="Never" enableViewStateMac="false" />

Thursday, June 25, 2009

Fail loading Web Application Project

Error : I do not quite remember the exact error, encounter it long time ago, and just now, a friend asked about it again. The error contain the words ..... System.Runtime.InteropServices.COMException...

It is characterized by web application project not being loaded while opening a solution, while any other projects open well.

Solution : Check whether IIS is installed on the computer. Press window + Run, type "inetmgr" (without quotes). If IIS is installed on the computer, Internet Information Services window should appear. Otherwise, you should install IIS first, then try opening the solution again.

To install IIS, go to Start Menu -> Control Panel -> Add or remove programs -> Add or remove windows components -> Check Internet Information Services, then click details -> don't forget to check FrontPage 2000 Server Extensions (if not checked yet) -> Click Next. It will asks to insert windows installer CD.
Yes, the IIS is on the windows installer CD, so you have to own a windows installer CD.

Debug not working on VS 2003.Net

Problem : Debug is not working on Visual Studio.NET 2003. There are some problems with Visual Studio 2003. Yet, still using it in some projects. One common problem is that the debug is not attached to the process while run in debugging mode. Hence, the breakpoints set will not be hit. This is sometimes annoying, when errors occur, and we're looking for the source of error.

Solution : Just run the application as usual, using F5, then on VS, choose menu Debug -> Processes -> look for aspnet_wp.exe. If more than 1 version are used on the computer, there might be more than 1 aspnet_wp.exe listed on the processes.

Choose any (if more than one available) aspnet_wp.exe process, then click Attach. A dialog box will appear. The process detail will be prompted, e.g.
It should look more or less like this :
[3644] c:\windows\\framework\v1.1.4322\aspnet_wp.exe

Notice that if the text in blue is not in v1...., then you should have chosen the wrong aspnet_wp.exe process. Cancel, and choose another aspnet_wp.exe process.

If there are more than 2 versions of VS used in the computer, i.e. 2003, 2005, 2008, etc., there should be :
[3708] C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_wp.exe -> .net Framework 2, for VS 2005 and above

[3644] c:\windows\\framework\v1.1.4322\aspnet_wp.exe -> .Net Framework 1, for VS 2003 and prior

Then, check only the Check box which says : Common Language Runtime, then OK.

Thursday, June 18, 2009

Can not add service reference / web reference

Error : The components required to enumerate web references are not installed on this computer. Please re-install Visual studio.

This error pops up as a dialog box while trying to add service reference / web reference.

Solution : Press window + Run, then type "devenv /resetskippkgs"
(without quotes), then press Enter.

This command clears all options to skip loadings added to VS Packages.

Then, try adding the service reference / web reference again.


Error with web service

Error variations:
- No connection could be made because the target machine actively refused it.
- The request failed with HTTP status 404: Not Found

Solution : Check whether the URL for the web service is set properly.

This problem appears to be a debugging problem when web service is used for desktop application. Yet, it appears to be a deploying problem when the web service is used for web application.

Wednesday, June 17, 2009

Creating Simplified Duwamish from a scratch

This is a step by step on how to create an C# web application using simplified Duwamish framework. I call it simplified Duwamish framework, because it is not the real Duwamish. It is my own version. I like it better, after eliminating some parts of the Duwamish framework I rarely use.
FYI, sample for the Duwamish template is already provided when installing Visual Studio .Net 2003.
This is a picture which describes the plot of Duwamish framework.

Picture Source :

For more information about Duwamish, refer to

For my Simplified Duwamish framework, I only use these projects:
- BusinessFacade (Class Library)
- DataAccess (Class Library)
- Common (Class Library)
- Control (Class Library) -> this project is not in Duwamish framework
- Web Application (ASP.NET Web Application)

1. Create a blank solution
Menu File -> New Project -> Visual C# -> Other Project Types -> Visual Studio Solutions -> Blank Solution, name the solution, and it will appear on the right side of the Solution Explorer.

2. Some things which should be known:
- Common -> does not depend on any other projects
- Control -> depends on Common
- DataAccess -> depends on Common
- BusinessFacade -> depends on Common and DataAccess
- Web Application -> depends on BusinessFacade, Common, and Control
Therefore, this would be the order used in creating projects in the solution.
To create a new project, right-click on the solution, choose Visual C#, then choose the project type.

3. Create Common Project
Add a new project of type Class Library, then name it Common. A class named Class1.cs will be automatically created. It can be renamed later.

4. Create Control Project
Add a new project of type Class Library, then name it Control. A class named Class1.cs will be automatically created. It can be renamed later.

5. Create DataAccess Project
Add a new project of type Class Library, then name it DataAccess. A class named Class1.cs will be automatically created. It can be renamed later.

6. Create BusinessFacade Project
Add a new project of type Class Library, then name it DataAccess. A class named Class1.cs will be automatically created. It can be renamed later.

7. Create Web Application Project
Add a new project of type ASP.Net Web Application, then name the web. A page named Default.aspx will be automatically created. This is usually set as the default page of the web.

8. Manage Project Dependencies
Manage project dependencies as explained in step 2. Right-click on the solution, then choose Project Dependencies.
- Common does not depend on any other projects, so we just skip this.
- Choose Control -> Check Common, since Control depends on Common.
- Choose DataAccess -> Check Common.
- Choose BusinessFacade -> Check DataAccess and Common.
- Choose Web Application -> Check BusinessFacace, Common, and Control.
Then, OK.

9. Adding Project References to the projects
To add references to the project, right-click on the project, choose tab Projects, then choose the project to be referenced.
- Control -> Add reference to Common.
- DataAccess -> Add reference to Common.
- BusinessFacade -> Add references to DataAccess and Common.
- Web Application -> Add references to BusinessFacade, Common, and Control.

10. Setting start-up project and start-up page
Right-click on the Web Application project, then Set as StartUp Project.
Right-click on the index page, then Set as Start Page (Default.aspx is usually set as start page).

11. Rebuild the Solution by right-clicking on the solution, then rebuild.

12. Running in debug mode may be necessary for the first time, after creating the application. Just press F5 to debug.

13. That’s all folks.

Tuesday, June 16, 2009

Logon failed on Crystal Report

Error : Logon failed. Details: ADO Error Code: 0x Source: Microsoft OLE DB Provider for SQL Server Description: Login failed for user 'UserXXX'. SQL State: 42000 Native Error: Error in File E:\TEMPSY~1\Tmp\temp_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}.rpt: Unable to connect: incorrect log on parameters.

Solution : Open the report, then Verify Database, using the login used while deploying!

This error takes me a lifetime to solve. It actually doesn't make sense to verify database for a report using the real login while deploying. That means all reports created while developing will have to be verified. The login info should be able to be set programmatically.

In my case, there are already some pages on the web that use similar reporting. I've printed the report using the same code, but no matter how I try, none works. I've tried a lot of ways to make it print, but all to no avail.

At last, I verify the report using the login used while deploying, then re-upload it. It works fine. phew -.-""""""

I set the login information for the report from web.config:

<!--<add key="ConnectionInfo" value="Database_name, server, user, password">-->
<add key="ConnectionInfo" value="DB1,, steven, steven"||/add>

Here's the .cs code I use for the report, and it should work fine, I guess.

private void BindConnectionInfo()
ConnectionInfo connectionInfo = new ConnectionInfo();
string conInfo = SystemConfiguration.ConnectionInfo; //get from web.config

connectionInfo.DatabaseName = conInfo.Split(',')[0].Trim();
connectionInfo.ServerName = conInfo.Split(',')[1].Trim();
connectionInfo.UserID = conInfo.Split(',')[2].Trim();
connectionInfo.Password = conInfo.Split(',')[3].Trim();

TableLogOnInfo t = new TableLogOnInfo();
t.ConnectionInfo = connectionInfo;

if (crystalViewer.LogOnInfo.Count == 0)
crystalViewer.EnableDatabaseLogonPrompt = false;
crystalViewer.EnableParameterPrompt = false;

protected void btnPrint_Click(object sender, EventArgs e)
litXXX.Text = "";

ReportDocument rd = new ReportDocument();

ParameterDiscreteValue value = new ParameterDiscreteValue();
value.Value = Period;
ParameterValues parameterValuesPriod = new ParameterValues();

value = new ParameterDiscreteValue();
value.Value = Convert.ToByte(Semester);
ParameterValues parameterValuesSem = new ParameterValues();

ParameterField parameterField = rd.ParameterFields[0];
parameterField.DefaultValues = parameterValuesPriod;
parameterField.CurrentValues = parameterValuesPriod;

parameterField = rd.ParameterFields[1];
parameterField.DefaultValues = parameterValuesSem;
parameterField.CurrentValues = parameterValuesSem;

crystalViewer.ReportSource = rd;

And here's the .aspx code:

script type="text/javascript">
function PrintPartsViewer()
var objWindow ="about:blank", "print", "width=800, height=600, toolbar=no");
var strHtml = "<html>";
strHtml += "<head>";
strHtml += "</head>";
strHtml += "<body>";
var element = document.getElementById("divPrint");
strHtml += element.innerHTML;
strHtml += "</body>";
strHtml += "</html>";

<asp:literal id="litXXX" runat="server"></asp:literal>

<asp:button id="btnPrint" runat="server" text="Print Report" onclick="btnPrint_Click" />


Saturday, June 13, 2009

Appending ArrayList to another ArrayList

A friend of mine asked about how to append an ArrayList to another ArrayList in C#. I found out that it's an easy task as long as the type of the ArrayList is the same. Just have to typecast it to ICollection.

ArrayList a = new ArrayList();
a.Add("Array 1");
a.Add("Array 2");

ArrayList b = new ArrayList();
b.Add("Array 3");
b.Add("Array 4");


Tuesday, June 9, 2009

Open and close CD-ROM tray in VB

Create a module, and put this code in it:

Declare Sub mciSendStringA Lib "winmm.dll" (ByVal lpstrCommand As String, ByVal lpstrReturnString As Any, ByVal uReturnLength As Long, ByVal hwndCallback As Long)

To Open CD-ROM tray, use this method:

Sub OpenCDTray()
mciSendStringA "Set CDAudio Door Open", 0&, 0, 0
End Sub

To Close CD-ROM tray, use this method:

Sub CloseCDTray()
mciSendStringA "Set CDAudio Door Closed", 0&, 0, 0
End Sub

Delete data by date

Sometimes, new Visual Basic developers may meet such problems as retrieving data by date. Just need to use # to make it right

db.Execute "DELETE FROM table_name WHERE FieldDate < #" & Format(Date, "yyyy/mm/dd") & "#"

Tuesday, June 2, 2009

Data on report won't change

Problem : If you're using crystal report to design a report and the data displayed on the report won't change.

Solution : Go check the report. Open it, then make sure that on menu File -> Save Data With Report -> is NOT checked.

This is actually a minor problem, but sometimes, people forget or don't notice it.

Invalid Handle in Crystal Report

Error : Invalid Handle
An error dialog box which says "Invalid Handle" shows while saving crystal report document.

Solution : The solution may vary in this case. Sometimes, there isn't even any mistake with the report.
1. Search for crw32.exe on the computer, in accordance with the version of Crystal Report being used, right-click the file -> properties -> go to tab Compatibility -> check Run this program in compatibility mode for, and choose Windows 2000.
2. Check whether all data and connections are correct (be meticulous), i.e. stored procedures, tables, etc.
3. If everything seems fine, just try closing the crystal report, then opening it again.
4. If the error still occurs, try restarting the computer.
5. Last, if none of the points above works, go to point 2 ^^

NB : Try saving first, doing a little updates on the report, because if you've done a lot of revisions, then this error appears when you try saving it, all your works will be futile.

Monday, May 25, 2009

Kido Virus (continued)

I guess the virus is not clean yet -.-""""" Still facing the same problems when the computer starts -.-""""" Finally, do a system restore and have everything back. phew...

Wednesday, May 20, 2009

Kido Virus

This actually has nothing to do with programming, but can't help posting it here. I guess my computer was infected by a virus, tried every way to fix it, none succeeds. I was using Kaspersky antivirus, then one morning when I turn on the computer, the protection is not running, and the update tab disappears.

A virus named Kido has been attacking my computer lately, but after being discovered by Kaspersky, I always delete it.

Not sure, but it should be the Kido that causes the errors on the system. Symptoms:
- Update tab on Kaspersky disappears.
- I was able to open Internet Information Services, but the service is not running, and when I tried running it, it's not responding.
- Cannot open another Internet Information Services or Services.
- Cannot connect to some network parts.
- Cannot open system restore.
- Yahoo Messenger, Meebo Notifier, or MSN Messenger is not running.

I solved it after I found out that there are 2 tasks running on the scheduler, at1 and at2. I notice that they have something to do with the virus which was encountered by Kaspersky, having to do with the Kido (which was deleted successfully by the Kaspersky -.-""""). I deleted both of them.

No sooner had I deleted them, the Messengers are logged in.. Everything goes fine. Phew... Strange case. (Though the update tab on Kaspersky does not appear yet).
Thanx to VX Tools, which helps me figure out there's something wrong with the running processes on the system, otherwise I wouldn't have figured it out only by looking on the task manager.

Monday, May 18, 2009

Redirecting and hiding URL

Problem : I wanted to make a link that will redirect the users to download a pdf file. Yet, I have to hide the URL, and can't let the users know the URL to the file.

Solution : I use repeater to hide the URL by using CommandArgument and CommandName attributes.

I make a repeater which looks more or less like this on the aspx:

<asp:repeater id="rpt" runat="server" onitemcommand="rpt_ItemCommand" onitemdatabound="rpt_ItemDataBound">
<asp:linkbutton id="linkFileName" runat="server" cssclass="link3"></asp:linkbutton>

Then on the CS:

protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
ClassData classData = (classData)e.Item.DataItem;
LinkButton linkFileName = (LinkButton)e.Item.FindControl("linkFileName");
string fileName = classData.FileName;
linkFileName.Text = fileName;
linkFileName.CommandArgument = classData.FileName;

protected void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + e.CommandArgument);
Response.WriteFile("D:\folder\" + e.CommandArgument);

Error using Server.Transfer

Error : Invalid path for child request 'http://localhost/Content/foldername/pdf_filename.pdf'. A virtual path is expected.

I was using Server.Transfer on links to redirect the web to another page, and this error occured.

Solution : DO NOT user Server.Transfer when redirecting to another web server. Use Response.Redirect instead.

Cannot create/shadow copy when file already exists

Error : Cannot create/shadow copy '..........' when that file already exists.

Solution : Rebuild solution / Clean solution, then rebuild.

Don't know why this actually happens. But it happens often, after building solution without debugging for times.

Tuesday, May 12, 2009

Using System.Web.Routing

Use URL Routing on application recently, and find some difficulties when developing.
When opening page which applies URL routing, it shows error that the page doesn't exist.

Should check this point:
Add a wildcard mapping .* to aspnet_isapi.dll and make sure that Check that file exists is unchecked.

Go to IIS, right click the virtual directory of the application, then choose Properties -> Configuration -> Add -> Browse Executable: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 (this path may differ), then find aspnet_isapi.dll, then set the Extension: .*, don't forget to uncheck Check that file exists -> OK.

Friday, May 8, 2009

Import data from excel to table in SQL

A friend asked about how to import data from Excel to table in SQL, then I searched for it. Found this code. Having tried it, I think it's a nice idea to share it.

SELECT column1, column2
FROM OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\ExcelTable.xls', 'SELECT * FROM [Sheet1$]')

Thursday, May 7, 2009

Read & Write .ini files

Reading from and writing to .ini files is very useful and is a widely used method to set or get some uncertain keys, such as database location, period, or any other things that are common, but are subject to change.

It is not necessarily .ini files. The extension may vary, depends on the developer will, but .ini is the most commonly used extension.

It's actually quite simple, with the utilization of API. API is very useful in VB. It can do a lot of things can't be done using classical VB components.

1. Make a text files with the format specified below: name it test.ini, and put it in the same folder where the application is made.


Header_Key1, Header_Key2 are the keys used for a group of keys.
key1, key2, key3 are the keys of the values to be read and written.

e.g. (To get current period and semester from text files)
AnotherContent=this is that other content

2. Make a module and put the following functions (to read and write text files) into the module:

Option Explicit
Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" _
(ByVal lpApplicationname As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long

Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" _
(ByVal lpApplicationname As String, ByVal lpKeyName As Any, ByVal lsString As String, ByVal lplFilename As String) As Long

Function GetfromINI(SectionHeader$, VarName$, FileName$) As String
Dim RetStr As String
RetStr = String(255, Chr(0))
GetfromINI = Left(RetStr, GetPrivateProfileString(SectionHeader$, ByVal VarName$, "", RetStr, Len(RetStr), FileName$))
End Function

3. To get the value of the keys on the .ini files :
Objects used:
3 textboxes named Text1, Text2, Text3
Dim isi1 As String, isi2 As String, isi3 As String

isi1 = GetfromINI("Period", "Period", App.Path + "\test.ini")
isi2 = GetfromINI("Period", "Semester", App.Path + "\test.ini")
isi3 = GetfromINI("Content", "AnotherContent", App.Path + "\test.ini")
Text1.Text = isi1
Text2.Text = isi2
Text3.Text = isi3

4. To save the value on textbox to the .ini files :
Objects used:
3 textboxes named Text1, Text2, Text3

WritePrivateProfileString "Period", "Period", Text1.Text, App.Path + "\test.ini"
WritePrivateProfileString "Period", "Semester", Text2.Text, App.Path + "\test.ini"
WritePrivateProfileString "Content", "AnotherContent", Text3.Text, App.Path + "\test.ini"

That's all.

Wednesday, May 6, 2009

Browser asks for username & password while debugging

Problem : The browser keeps asking for username and password while debugging.

Solution :
1. Check on IIS if you're using IIS, by pressing window + R, then type "inetmgr" without quotes. Go to the website on the default web site. Then right click, properties, on directory security, check Anonymous Access, and make sure you also check Integrated Windows Authentication.

2. Make sure the application being developed is not located on shared folders such as My Documents, Desktop, etc. If it is indeed on one of those folders, move it to another folder on the local drive, e.g. C:\, D:\, etc.

ADO: Recordcount return -1

Error : Recordcount May Return -1 while using ADO connection

The problem is ADO defaults to a Server side cursor. You can only use the RecordCount property with a Client side Cursor.

Do something like...
rsMyRecordset.CursorLocation = adUseClient

If I may guess, the reason the RecordCount doesn't work in your code is that the default cursortype, adOpenForwardOnly, of the recordset doesn't support it. ForwardOnly recordsets ("firehose cursors") are very fast when you just want to run through them from top to bottom. So, if you are using adOpenForwardOnly for the cursorType, you may have to change it.

Here's the code:

rs.CursorLocation = adUseClient
rs.Open sql, con, adOpenKeyset, adLockPessimistic

Friday, May 1, 2009

Generate random characters

There is a way to generate random characters in a simple way, just use :
select NEWID()

This function is quite useful in some occasions, though may not be it's main usage.
e.g. If you're going to generate a random quote from a table named MsQuote :
SELECT TOP 1 QuoteId, QuoteText
FROM MsQuote

Stored procedure's dependencies

Find the dependencies of a stored procedure / Find tables used in a stored procedure:
use sp_depends sp_name

Sys on SQL

Not sharing query, but some tips that might be useful when looking for a needle in a haystack.
Am using Microsoft SQL Server 2000, but won't differ too much on later versions, I guess.

Find tables with the specified name

select name from sysobjects where name like '%table_name%' and type = 'u'

Find stored procedures with the specified name
select name from sysobjects where name like '%sp_name%' and type = 'p'

Find the name of the tables which contain specified column
select TableName =, ColumnName = from sysobjects a, syscolumns b
where = and = 'column_name'

Find stored procedures which contain certain key / text
select name from sysobjects where id in ( select id from syscomments where text like '%text_in_sp%')

This is also useful when you would like to search for stored procedures which uses a certain table.
e.g. If you would like to know the stored procedures which use the table named table_name,
select name from sysobjects where id in ( select id from syscomments where text like '%table_name%')

Friday, April 24, 2009

Can't debug on IE

Error : I forget about the error messages. If I'm not mistaken, the error message was just as common. As far as I remember, it sounds like this :

Unable to Start Debugging on the Web Server... user is not a member of "debugger users"

Solution : Run Internet Explorer (it should be more or less the same in other browsers), choose menu Tools -> Internet Options -> Security tab -> Choose Local Internet -> click Sites button -> click Advanced -> add http://localhost to the zone, then ok.

ASP.NET State Service

Error :
Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same. If the server is on a remote machine, please ensure that it accepts remote requests by checking the
value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Param
eters\AllowRemoteConnection. If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either 'localhost' or '' as the server name.

This is also one of the mostly retrieved errors. This error occurs when using StateServer mode for the sessionState in web.config, yet the ASP.NET State Service is not started.
I met this error when I first made a web application. After I get the solution, I ask a little about about StateServer sessionState mode to a senior.

When making an application with login page, u can consider using StateServer for the sessionState mode, because when u use this mode, u don't have to login again and again, just have to refresh the web page, because the session is still kept on server. Yet, when deploying the application, should omit it, or change it to InProc mode. I used only these 2 modes. Never use the SQLServer mode.

<sessionState mode="StateServer" stateconnectionstring="tcpip=" sqlconnectionstring="data source=;Trusted_Connection=yes" cookieless="false" timeout="200000" />

Start the ASP.NET State Service on Services. Go to control panel -> Administrative Tools -> Services, or simply press window + Run, then type services.msc. Choose ASP.NET State Service, right-click, then Start the service. To start it automatically, choose startup type : Automatic.

Crystal Report error while deploying

Error : Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its
dependencies. The system cannot find the file specified.

Solution : Install crystal report runtime available in Visual Studio CD, on the server.

Error on connection string

Error : An error has occurred while establishing a connection to the server.
When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Solution : Check if the connection string is properly defined.

Error on event validation

Error :
Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Solution : If there is a part of the code where repeater is used, DO NOT bind data on pageload (ispostback) section.

Also cannot debug application

Error : Error while trying to run project: unable to start debugging on the web server. the project is not configured to be debugged.

This is the most widely retrieved error while developing web applications... Hahaha... And the solutions may vary greatly. This solution works in my case.

Solution : re-register aspnet to IIS. Go to start menu -> Programs -> Microsoft Visual Studio xxxx -> Visual Studio Tools -> Visual Studio xxxx Command Prompt -> type aspnet_regiis -r.

I was using 3 version of VS.Net, i.e. version 2003, 2005, and 2008. This maybe the reason of this error in some way.

Cannot debug application

Error : Cannot start service from the command line or a debugger. A Windows Service must first be installed (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command.

Solution : Check the start-up project. Make sure the start-up project is the web application, not a class library project.

Error while building on release mode

Error : "LC.exe" exited with code -1073741701

I was building a pre-compiled web in release mode (using WebDeployment program). As known, compiling in release mode always retrieves undiscovered errors -.-"""

Solution : Exclude licenses.licx file from project, then rebuild again.

There was a time when I faced the same problem, after my computer was attacked by a virus that caused the executable files became corrupted. In this case, just ask for a copy of LC.exe file from a friend and place it on the folder where LC.exe is located on the computer.

Parser Error

Error :
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type 'Web.MasterPages.GeneralTemplate'.

Source Error:
Line 1: <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="GeneralTemplate.Master.cs"
Line 2: Inherits="Web.MasterPages.GeneralTemplate" %>
Line 3: Source File: /Web/MasterPages/GeneralTemplate.Master

Version Information: Microsoft .NET Framework Version:2.0.50727.3053;

ASP.NET Version:2.0.50727.3053

Solution : Yet another weird error, I deleted the bin folder on the web application, then rebuilt the solution, and it just worked!

Ambiguous match found

Error :
Server Error in '/Web' Application.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Ambiguous match found.

Source Error:

Line 1: <%@ Control Language="c#" AutoEventWireup="false"
Codebehind="GeneralTemplate.ascx.cs" Inherits="Web.Service.MasterPages.GeneralTemplate"

Line 2: <%@ Register TagPrefix="uc1" TagName="MainMenu" Src="../UserControls/MainMenu.ascx" %>
Line 3: <%@ Register TagPrefix="Web" Namespace="Web.Web.Controls" Assembly="BLMS.BackEnd.Web.Controls" %>

Source File: /Web/MasterPages/GeneralTemplate.ascx Line: 1

This is actually a weird error, I've faced a lot of problems while deploying and debugging web application developed under, and these errors are sometimes not quite relevant to the error messages, so have to figure it out by myself. Phew...

Solution : Made a new web directory on IIS outside the default website, for the web application. And it worked like charm!! -.-"""

Error when using ajax component

Error : The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Solution : Put all the tags on the body, not on the head.

Error connecting to undo manager of source file

Error : Error connecting to undo manager of source file.
This error occur when debugging a web application on

Solution :
1. Delete the aspx.designer.cs file
2. Right-click the aspx, select convert to web application.

There are 3 layers (that's how I call it) on web application, i.e. Design layer(.aspx), Coding layer(.cs), and the other one is the layer that contains all the Components used in Design layer(.aspx.designer.cs).

I code more than dragging elements to the page while working on the design of a web page. Sometimes, the Components layer doesn't synchronize well with the design layer, so some elements used in the design layer are not created properly. Deleting the .aspx.designer.cs and converting to web application will create a new file, thus all the elements will be created more properly.

Username & Password requested when downloading

Problem : When downloading a file, username and password is requested.

Solution : If I'm not mistaken, I used impersonation on the web, so have to grant permission on the IIS. Go to control panel -> Administrative Tools -> Internet Information Services. Or simply press window + Run, then type inetmgr.

Right-click Default Web Site, properties, go to Home Directory tab, push button Connect as -> dialog box to fill username and password will be prompted, fill with the user used for impersonation.

Can't access local web aplication from another computer

Error : No error, it's just that local web application can not be accessed from another computer.

Solution : go to control panel -> windows firewall -> add port :
Name : HTTP
Port Number : 80
Type : TCP

Accessing web from local : http://localhost/webName/Default.aspx
When accessing from another computer, just use the ip address of the computer where the web is located, i.e. http://ip_address/webName/Default.aspx.

Error displaying report

Error : C:\DOCUME~1\STEVEN~1\ASPNET\LOCALS~1\Temp\temp_c31eb8a4-2e63-4b42-b43d-c91550cca5b4 {25A8AD89-FCF3-4B82-A544-375DE1838F98}.rpt: Unable to connect: incorrect log on parameters

This problem is quite typical, and happen under some typical conditions. I was using crystal report to view a report on a web page, and the connection used for the report is ODBC. I had made the ODBC on User DSN tab, yet the error still occurred. Have to create ODBC on System DSN.

Solution : Add ODBC to System DSN (on the server where the application is located), and make sure the connection in the application is using valid username & password.

Assemblies / DLL not included

Error : One or more Assemblies / DLL have not been included...
I forgot the exact error message, but it should include those words. This error is caused by the unavailability of one or more DLLs when deploying.

Solution : Some DLLs, that are imported components, are usually not copied to deployment folder. To make them copied when creating deployment project, we have to change the property of the DLL.

Goto References folder of the application, then select the DLL, right-click, choose copy local = true. Then rebuild the project, the DLLs will be automatically copied to the deployment folder.

File has not been pre-compiled

Error : The file '/Web/Default.aspx' has not been pre-compiled, and cannot be requested.

I used WebDeployment program to compile the web on release mode.

Solution : Re-copy the compiled files. This problem usually occurs when deploying pre-compiled web. Maybe missed some files while copying the files. Try re-copy the compiled files.

Wednesday, April 22, 2009

Error when creating deployment project

Error : The target directory could not be deleted. Please delete it manually, or choose a different target.

Solution : Delete publish folder (the folder where the published web is located), then try compiling in release mode again.

Problem with server / Web Service

Error : No connection could be made because the target machine actively refused it

Solution : If you use web service or get data from a server, check whether the web service is working properly, or the connection to the server is available.

Friday, April 17, 2009

Check whether a file exists or not

This is actually a simple code, but someones may not know it when first using VB, so I post it here.
Here's the code to find a file named file.txt:
If Dir(App.Path & "\file.txt") <> "" Then
MsgBox "Found: file.txt"
End If

How to detect running program

Make a module and use the functionality of API to make it work.

Code in the module:
Option Explicit
Private Declare Function GetWindowText Lib "user32.dll" Alias "GetWindowTextA" _
(ByVal hwnd As Long, ByVal lpString As String, ByVal nMaxCount As Long) As Long

Private Declare Function EnumWindows Lib "user32.dll" _
(ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long

Private Target As String
Private IsOpen As Boolean

Private Function EnumCallback(ByVal app_hWnd As Long, ByVal param As Long) As Long
Dim buf As String * 256
Dim title As String
Dim length As Long
Dim hWndREC As Long
length = GetWindowText(app_hWnd, buf, Len(buf))
title = Left$(buf, length)
If InStr(1, title, Target, vbTextCompare) Then
IsOpen = True
End If
EnumCallback = 1
End Function

Public Function WindowOpen(app_name As String) As Boolean
'app_name is the name of the application when tracked on Windows Task Manager
IsOpen = False
Target = app_name
EnumWindows AddressOf EnumCallback, 0
If IsOpen Then WindowOpen = True
End Function

To check whether a program is running, e.g. Notepad:

If WindowOpen("Notepad") Then
MsgBox "Notepad is opened"
MsgBox "Notepad is not opened"
End If


How to clear all textboxes in a form

Sometimes, when we use a lot of textboxes in a form, and want to clean all the textboxes the form, it's not efficient to clean it one by one by using Text1.Text = "", Text2.Text = "", etc.
There is a short way to do it:
Dim a As Control
For Each a In Form1
If TypeOf a Is TextBox Then
a.Text = ""
End If

Wednesday, April 15, 2009

Get file name from a path in VB

One of my friend once asked how to get file name from a path. There're actually a lot of ways to do it. I'll try a simple one, using Split and UBound function.

e.g. the path is C:\Test\DeeperPath\EvenDeeperPath\Test.txt
and we're going to get the file name, i.e. Text.txt

The name of the controls:
textbox : Text1, containing the path

Some things we have to know:
1. To split the path into array: Split(Text1.Text, "\")
We'll get array of string:
Split(Text1.Text, "\")(0) = C:
Split(Text1.Text, "\")(1) = Test
Split(Text1.Text, "\")(2) = DeeperPath
Split(Text1.Text, "\")(3) = EvenDeeperPath
Split(Text1.Text, "\")(4) = Test.txt

2. To get upper bound of an array: UBound(array)

So, to get the file name from a path, we just need a line of code:
Split(Text1.Text, "\")(UBound(Split(Text1.Text, "\")))

The result will be: Test.txt

Connecting Crystal Report and VB using TTX

I'd like to share how to make a report using Crystal Report, and connect it from VB here, since there has been several friends asking about this.
There are actually several ways to connect VB and Crystal Report, ones of which that I've ever used are using TTX and ODBC.

I'd like to share the usage of TTX here. I use Crystal Report 8.5, but it's more or less the same as the other versions.

Like it's data source type - Field Definition Only - implies, it makes a .ttx file to define the fields used in the report. Thus, when creating a report, we have to make a .ttx file that contains all the fields and type of the fields used in the report.

The advantages of this method are:
1. Flexible, we don't have to change the report if there is any changes on the logic while retrieving the data.

2. We only have to define the data type, that's all, and do the code in the application.

These are the steps need to be done for the report:
1. Run Crystal Report, choose Create a New Crystal Report Document [As a Blank Report].

2. Choose the type of the data source: Field Definition Only.
Data Source: Field Definition Only

3. It will ask to browse for a text file or make a new file, I'll make a new one.
Just insert the Field Name and the Field Type to be used in the report. Make sure the field name and the field type is correct. Add all fields used. When finished, click the close icon of the form. It will ask to save the file, then click OK.

4. Click Add to add the .ttx file to the report, then click Close.

Add TTX to report

5. Start designing the report by inserting the fields used in the report then save it.

I use the table [Customers] from the Northwind database.
I'll try to print Customers data by Country.
PS: I use ADODB for the database connection.

These are the steps in the VB:
1. Add Crystal Report component to the application by pressing ctrl+T or go to menu Projects -> Components. On the Controls tab, check [Crystal Report Control], then press ok. A crystal report component will be added to the toolbox window.

2. Drag the component to the form.

Crystal Report Component

3. The small programs will look like this.

Application View

4. Here's the code on the print button event:
The name of the Controls:
combo : cmbCountry
command button : cmdPrint

Private Sub cmdPrint_Click()
With CrystalReport1
Dim sql As String
sql = "select CustomerID, CompanyName, ContactName, ContactTitle, " & _
"Address from Customers where Country = '" & cmbCountry.Text & "'"
Set rs = con.Execute(sql)

.ReportFileName = App.Path & "/RptTest.rpt"
.Destination = crptToWindow
.SetTablePrivateData 0, 3, rs
.WindowState = crptMaximized
.WindowShowPrintBtn = True
.Action = 1
End With
End Sub

5. And the report looks like this.

Report View

That's all folks.



Related Posts

Dual Axis not Working in Tableau

Problem : When creating chart with Dual Axis, Synchronize Axis is disabled and cannot be clicked. Cause : Tableau identified this as ...

About Me

My photo
Is an ordinary unNoticed man, with a little knowledge to share and high dreams to achieve. I'd be glad if I can help others, 'coz the only thing for the triumph of evil is for a good man to do nothing. I like English and Chinese language, and know a little about them. Hence, for me, most things can best be expressed in Chinese, some in English, and the rest in others ^^

About Blog

You can find a lot of debugging and deploying problems while developing applications in .NET and Visual Basic here. There are also some querying tips in SQL and typical source codes which might be useful shared here.

Popular Posts



Follow by Email