This is a nostalgic note. Someone asked me, "hey, how do you make a fixed len
string in VB6?"
As the computer geek that I am, that the kind of questions I like to be able to
answer.
These are important questions like all those questions from the 80's rally:
The name of all the original thundercats...
The planet where Luck Skywalker went to learn with Yoda...
Which Star Trek character appear in ALL the episodes (yes it is Spock, Kirk is
not in all of them)
Well, the thing is to define a fixed len string in VB6 you do something like:
Dim aString As String * 10
If you do something like:
aString = "Mau" ' aString ==> "Mau "
That's all
Fixed length strings are automatically filled with spaces to pad them to their
fixed-length. How do you get rid of the extra spaces? Duh!!! with RTrim$ don't
you remember
When a variable like aString is declared, it will be filled with Null characters
until it is used.
And yes functions (RTrim$, LTrim$, and Mid$) will not trim Null characters, so
be sure to assign it with an empty string "" immediately.
Ahh! and by the way when you translate that to .NET, .NET does not have a fixed
len string so the easiest thing to do is use:
Microsoft.VisualBasic.Compatibility.VB6.FixedLengthString.
[C#]
using Microsoft.VisualBasic.Compatibility;
...
void foo()
{
VB6.FixedLengthString aString = VB6.FixedLengthString(10, "Mau");
}
Yesterday someone told me and I checked out
El Financiero online.
There's an article about
Artinsoft there.
If you don't know about us. We do Software Migration, and BANAMEX decided to upgrade their platform from VB6 to .NET.
It's a huge amount of code, and a very interesting project :)
See:
Article
Sometimes you might have a situation where you have a VB Application you want to migrate to C# but you also have some PHP code you are depending on? Sounds familiar?
Well it isn't really a typical scenario jajaja
But anyway if you had the urge to do that now project Phalanger can help you with that just
check it out
And if you need help in the VB6 to C# stuff just write any question you have :)
As any geek I live frustrated by the lack of good tools in Windows.
Notepad, and Paint are just a couple of examples.
I was just dreaming for a nice, light replacement for those applications.
Well, recently somebody wrote a nice page with amazing freeware that you can use:
Amazing Tools
The first time you have to upgrade your database from SQL Server 2000 to SQL Server 2005, you might thing is simple process.
And and in very simplistic way of looking at the world it is.
But a REAL migration, from a REAL production database can be a lot more complex that what you can imagine.
A good friend of mine has had to experience recently the various venues of migration like this, and I really recommend his blog, he gives "Jedi" style tips you must consider if you want the Force to be with you.
For all things related to
VB6 to C# or VB.NET software migration, be sure to visit Artinsoft's website.
Localize a VB6 application can be cumbersome, specially if it was not even originally planned to be localized.
Nowadays is common that you're clients might demand support for different languages.
While a localization task is still difficult, we have found excellent results performing it during a VB Migration.
Our tools allow us to easily externalize all your strings. After that the traslation task becomes easy, and you can even use the help
of nice projets like
Automatically Translate your .NET resource files with Google Translate
There are a list of situations you might want to handle with Active Directory:
525 - user not found
52e - invalid credentials
530 - not permitted to logon at this time
532 - password expired
533 - account disabled
701 - account expired
773 - user must reset password
This is an extract of the Java Forum to handle these cases. Good Luck!
} catch (AuthenticationException e) {
String tempString;
StringTokenizer tokenizerTemp = new StringTokenizer(e.toString());
while (tokenizerTemp.hasMoreElements()) {
tempString = tokenizerTemp.nextToken();
if (tempString.equalsIgnoreCase("AcceptSecurityContext")) {
while (tokenizerTemp.hasMoreElements()) {
tempString = tokenizerTemp.nextToken();
if (tempString.startsWith("773"))
setIsPasswordExpired(true);
if (tempString.startsWith("52e"))
setIsPasswordWrong(true);
if (tempString.startsWith("533"))
setIsAccountDisabled(true);
}
}
}
throw new NamingException();
}
It is common that after a migration to Java, specially coming from legacy platforms like LINC or COBOL, that our clients want to take advantage of new technologies. So it happens that they are now authenticating against an Active Directory or another LDAP server. And thanks to the new platforms it is really easy for us to help them integrate this new functionality.
This is sample program that show how to authenticate with for example a Windows Active Directory.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LDAPTest
{
static class LDAP
{
static String ATTRIBUTE_FOR_USER = "sAMAccountName";
public Attributes authenticateUser(String username, String password, String _domain, String host, String dn)
{
String returnedAtts[] ={ "sn", "givenName", "mail" };
String searchFilter = "(&(objectClass=user)(" + ATTRIBUTE_FOR_USER + "=" + username + "))";
//Create the search controls
SearchControls searchCtls = new SearchControls();
searchCtls.setReturningAttributes(returnedAtts);
//Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchBase = dn;
Hashtable environment = new Hashtable();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
//Using starndard Port, check your instalation
environment.put(Context.PROVIDER_URL, "ldap://" + host + ":389");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, username + "@" + _domain);
environment.put(Context.SECURITY_CREDENTIALS, password);
LdapContext ctxGC = null;
try
{
ctxGC = new InitialLdapContext(environment, null);
// Search for objects in the GC using the filter
NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
while (answer.hasMoreElements())
{
SearchResult sr = (SearchResult)answer.next();
Attributes attrs = sr.getAttributes();
if (attrs != null)
{
return attrs;
}
}
}
catch (NamingException e)
{
System.out.println("Just reporting error");
e.printStackTrace();
}
return null;
}
}
public static void main(String[] args) throws Exception
{
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
System.out.println("Please type username:");
String username = in.readLine();
System.out.println("Please type password:");
String password = in.readLine();
LDAP ldap = new LDAP();
//Yo specify in the authenticate user the attributes that you want returned
//Some companies use standard attributes like 'description' to hold an employee ID
//The ActiveDirectory data can be enhanced to add custom attributes like
//printer
// Some instalations usually have several ACtiveDirectoryServers, lets say
// 192.150.0.8, 192.150.0.7 y 192.150.0.9 and they use a
// DNS round robin to balance the load
Attributes att = ldap.authenticateUser(username, password, "mydomain.com", "myactivedirectoryhost.com", "DC=mydomain,DC=com");
if (att == null)
{
System.out.println("Sorry your use is invalid or password incorrect");
}
else
{
String s = att.get("givenName").toString();
System.out.println("GIVEN NAME=" + s);
}
}
}
This is small Example. I had a POS Application in VB6 with this code.
Me.EpsonFPHostControl1.SendCommand
While EpsonFPHostControl1.State = EFP_S_Busy
DoEvents
Wend
This code is almost the same in VB.NET
Me.AxEpsonFPHostControl1.SendCommand()
While AxEpsonFPHostControl1.CtlState = EpsonFPHostControlX.TxFiscalState.EFP_S_Busy
Application.DoEvents()
End While
POS (Point of Sale) software is everywhere. Whether you're at a Bar, at Denny's, Pizza Hut, BK or at the Duty Free. It is maybe one of the software's more commonly used. A POS system is generally simple. It manages a basic inventory, registers sales, and somethings manages credit card payments. Obviously there are far more complex POS systems. A lot of POS systems where programmed in VB6. But as you know VB6 language (and I'm not discussing the reasons here) is now a dead language. A lot of customers do not want to buy VB6 applications, even if they get the job done. So it's time to move on. This is the First of a series of posts around issues migrating VB6 POS applications. If you have any comments just send them now!
I was developing a WebPart and I came up with a situation where my custom ToolPart did not fired the events.
I found this post that solved the problem.
"
I moved the databinding code into the CreateChildControls()
code:
protected override void CreateChildControls()
{
dllCatagory = new DropDownList();
dllCatagory.Visible = true;
dllCatagory.AutoPostBack = true;
dllCatagory.Attributes.Add("runat", "server");
dllCatagory.SelectedIndexChanged += new
EventHandler(dllCatagory_SelectedIndexChanged);
CdCatagoryList.CatagoryList cdCatL;
cdCatL = new CdCatagoryList.CatagoryList();
//cdCat.Catlist is a dll that will get the data.
DataView tviewFolders = cdCatL.CatList(true, "cdadmin", "",
"server=192.168.221.246;uid=DataSa;pwd=pa456;database=ContentDepot");
dllCatagory.DataSource = tviewFolders;
dllCatagory.DataValueField = "FolderNumber";
dllCatagory.DataTextField = "FolderName";
dllCatagory.DataBind();
Controls.Add(dllCatagory);
}
public void dllCatagory_SelectedIndexChanged(object sender, EventArgs e)
{
//Code to load the gridview
//This event now fires}
protected override void RenderToolPart(HtmlTextWriter output)
{
EnsureChildControls();
dllCatagory.RenderControl(output);
}
"
I recently had a situacion where I needed to extract images from a word document. This can be cumbersome, tedious and you can loose the fidelity of your images
I found two good aproaches: first see
Approach One. This approach indicates to save the document as a web page.
In my case I needed images with a sequence I could follow. Like Figure1 Figure2 etc and I needed them with the best quality possible. So I used another link recommended
Approach Two which has a macro that you can use to export your image as bmp.
Those two links were of great help to me. I recommended them.
Source IP for connected applications in DB2
Usually when there are performance problems you need to
track who is connected to the database. Especially in development environments
because production environments are more restricted with who has access to the
DB.
You can easily list the applications connected to your DB2
database using the control center application or from the command line.
From the control center:
- First
check that the Objects Detail Pane is active

- In the
Objects Details Pane, click the application list link

- This
will open a window like this:

From the command window just do something like:
DB2 LIST APPLICATIONS

Now to get the real juicy and useful information execute
from the command line:
DB2 GET SNAPSHOT FOR APPLICATION AGENTID ###
And use the number that is under the Appl.
Handle column, this will show the ip address and
other info.
I like Linux and consider it as a very interesting OS alternative
However sometimes there are simple things that I just do not know how to do.
Windows is still everywhere and specially getting thing
from a Windows to a LINUX box can be tricky.
For example recently I had to restore a database
from a Windows DB2 to a Linux DB2 so I had the backup and needed to
eove it to the linux box.
So use smbclient!
But how.
Ok.
to connect to a windows share do something like this:
smbclient -user domain/username //machine/sharename
this thing will ask for your password and now you are connected.
Smbclient is just like an ftp.
But how do you copy a directory
I found these instructions in the internet:
smb: > tarmode
smb: > lcd /tmp
smb: > recurse
smb: > prompt
smb: > mget your_directory/
as simple as that.
So hope that helps
Sample Code to Print in Java
import
java.io.ByteArrayInputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
public
class Class3 {
static String textToPrint = "Richard North Patterson's masterful portrayals of law and politics at the apex of power have made him one of our most important\n" +
"writers of popular fiction. Combining a compelling narrative, exhaustive research, and a sophisticated grasp of contemporary\n" +
"society, his bestselling novels bring explosive social problems to vivid life through characters who are richly imagined and\n" +
"intensely real. Now in Balance of Power Patterson confronts one of America's most inflammatory issues-the terrible toll of gun\n" +
"violence.\n\n" +
"President Kerry Kilcannon and his fiancée, television journalist Lara Costello, have at last decided to marry. But their wedding\n" +
"is followed by a massacre of innocents in a lethal burst of gunfire, challenging their marriage and his presidency in ways so shattering\n" +
"and indelibly personal that Kilcannon vows to eradicate gun violence and crush the most powerful lobby in Washington-the Sons of\n" +
"the Second Amendment (SSA).\n\n" +
"Allied with the President's most determined rival, the resourceful and relentless Senate Majority Leader Frank Fasano, the SSA\n" +
"declares all-out war on Kerry Kilcannon, deploying its arsenal of money, intimidation, and secret dealings to eviscerate Kilcannon's\n" +
"crusade and, it hopes, destroy his presidency. This ignites a high-stakes game of politics and legal maneuvering in the Senate,\n" +
"the courtroom, and across the country, which the charismatic but untested young President is determined to win at any cost. But in\n" +
"the incendiary clash over gun violence and gun rights, the cost to both Kilcannons may be even higher than he imagined.\n\n" +
"And others in the crossfire may also pay the price: the idealistic lawyer who has taken on the gun industry; the embattled CEO\n" +
"of America's leading gun maker; the war-hero senator caught between conflicting ambitions; the female senator whose career is at\n" +
"risk; and the grief-stricken young woman fighting to emerge from the shadow of her sister, the First Lady.\n\n" +
"The insidious ways money corrodes democracy and corrupts elected officials . . . the visceral debate between gun-rights and\n" +
"gun-control advocates . . . the bitter legal conflict between gun companies and the victims of gun violence . . . a\n" +
"ratings-driven media that both manipulates and is manipulated - Richard North Patterson weaves these engrossing themes into an\n" +
"epic novel that moves us with its force, passion, and authority.";
public static void main(String[] args) {
DocFlavor flavor = DocFlavor.INPUT_STREAM.
AUTOSENSE;
PrintRequestAttributeSet aset =
new HashPrintRequestAttributeSet();
/* locate a print service that can handle it */
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
/* create a print job for the chosen service */
int printnbr = 1;
DocPrintJob pj = pservices[printnbr].createPrintJob();
try {
/* * Create a Doc object to hold the print data.
* Since the data is postscript located in a disk file,
* an input stream needs to be obtained
* BasicDoc is a useful implementation that will if requested
* close the stream when printing is completed.
*/
ByteArrayInputStream fis =
new ByteArrayInputStream(textToPrint.getBytes());
Doc doc =
new SimpleDoc(fis, flavor, null);
/* print the doc as specified */
pj.print(doc, aset);
}
catch (Exception ex){
ex.printStackTrace();
}
}}
TIP: If you are just testing create a Printer. Just go to Add Printers, select FILE for port and Manufacturer Generic and TEXT Only
The idea was to create a harry potter like title jeje.
Today I had a new issue with DB2 (everyday you learn something new).
I got to work and we had some tables that you could not query or do anything. The system reported something like:
SQL0668N Operation not allowed for reason code "1" on table "MYSCHEMA.MYTABLE".
SQLSTATE=57016
So I started looking what is an 57016 code????
After some googling I found that the table was in an "unavailable state". OK!!
But how did it got there? Well that I still I'm not certain. And the most important. How do I get it out of that state?????
Well I found that the magic spell is somehting like
>db2 set integrity for myschema.mytable immediate checked
After that statement everything works like a charm.
DB2 Docs state that:
"Consider the statement:
SET INTEGRITY FOR T IMMEDIATE CHECKED
Situations in which the system will require a full refresh, or will check the whole table
for integrity (the INCREMENTAL option cannot be specified) are:
- When new constraints have been added to T itself
- When a LOAD REPLACE operation against T, it parents, or its underlying tables has taken place
- When the NOT LOGGED INITIALLY WITH EMPTY TABLE option has been activated after the last
integrity check on T, its parents, or its underlying tables
- The cascading effect of full processing, when any parent of T (or underlying table,
if T is a materialized query table or a staging table) has been checked for integrity
non-incrementally
- If the table was in check pending state before migration, full processing is required
the first time the table is checked for integrity after migration
- If the table space containing the table or its parent (or underlying table of a materialized query
table or a staging table) has been rolled forward to a point in time, and the table and its
parent (or underlying table if the table is a materialized query table or a staging table) reside
in different table spaces
- When T is a materialized query table, and a LOAD REPLACE or LOAD INSERT operation directly into T
has taken place after the last refresh"
But I really dont know what happened with my table.
Hope this help you out.
Active Directory is also LDAP. So to integrate with the Active Directory you can use code very similar to that one used with other LDAP servers.
To connect to the Active Directory you can do something like this:
import java.util.Hashtable;
import
javax.naming.Context;
import
javax.naming.NamingException;
import
javax.naming.directory.DirContext;
import
javax.naming.directory.InitialDirContext;
/**
* @author mrojas
*/
public class Test1
{
public static void main(String[] args)
{
Hashtable
environment = new Hashtable();
//Just
change your user here
String
myUser = "myUser";
//Just change your user password here
String
myPassword = "myUser";
//Just
change your domain name here
String
myDomain = "myDomain";
//Host
name or IP
String
myActiveDirectoryServer = "192.168.0.20";
environment.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL,
"ldap://" + myActiveDirectoryServer
+ ":389");
environment.put(Context.SECURITY_AUTHENTICATION,
"simple");
environment.put(Context.SECURITY_PRINCIPAL,
"CN=" + myUser + ",CN=Users,DC=" + myDomain + ",DC=COM");
environment.put(Context.SECURITY_CREDENTIALS,
myPassword);
try
{
DirContext context = new InitialDirContext(environment);
System.out.println("Lluvia de exitos!!");
}
catch
(NamingException e)
{
e.printStackTrace();
}
}
}
I found a super interesting blog called
Busy ColdFusion Developers' Guide to HSSF Features
http://www.d-ross.org/index.cfm?objectid=9C65ECEC-508B-E116-6F8A9F878188D7CA
HSSF is part of an open source java project that provides FREE OPEN SOURCE libraries to create Microsoft Office Files like Microsoft Word or Microsoft Excel.
So I was wondering could it be possible with Coldfusion to use those libraries. Specially now that Coldfusion MX relies heavily in Java. So I found this wonderfull blog that explains it all.
It just went to the HSSF download site:
http://www.apache.org/dyn/closer.cgi/jakarta/poi/
The project that holds these libraries is called POI.
When you enter in those links there is a release directory and a bin directory. I downloaded the zip file and you will find three files like: poi-Version-Date.jar; poi-contrib-Version-Date.jar and poi-scratchpad-Version-Date.jar
I downloaded the 2.5.1-final version. I renamed my jars to poi-2.5.1.jar, poi-2.5.1-contrib.jar and poi-2.5.1-scratchpad.jar because my memory cannot hold those complex names for a long time. I installed the library in C:\POI and put them in the Coldfusion Administrator classpath
And then I created a test file like the following:
Note: I used a recommendation from Cristial Cantrell http://weblogs.macromedia.com/cantrell/archives/2003/06/using_coldfusio.cfm
<cfscript>
context = getPageContext();
context.setFlushOutput(false);
response = context.getResponse().getResponse();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=unknown.xls");
out = response.getOutputStream();
</cfscript>
<cfset wb = createObject("java","org.apache.poi.hssf.usermodel.HSSFWorkbook").init()/>
<cfset format = wb.createDataFormat()/>
<cfset sheet = wb.createSheet("new sheet")/>
<cfset cellStyle = wb.createCellStyle()/>
<!--- Take formats from: http://jakarta.apache.org/poi/apidocs/org/apache/poi/hssf/usermodel/HSSFDataFormat.html --->
<cfset cellStyle.setDataFormat(createObject("java","org.apache.poi.hssf.usermodel.HSSFDataFormat").getBuiltinFormat("0.00"))/>
<cfloop index = "LoopCount" from = "0" to = "100">
<!--- Create a row and put some cells in it. Rows are 0 based. --->
<cfset row = sheet.createRow(javacast("int",LoopCount))/>
<!--- Create a cell and put a value in it --->
<cfset cell = row.createCell(0)/>
<cfset cell.setCellType( 0)/>
<cfset cell.setCellValue(javacast("int",1))/>
<!--- Or do it on one line. --->
<cfset cell2 = row.createCell(1)/>
<cfset cell2.setCellStyle(cellStyle)/>
<cfset cell2.setCellValue(javacast("double","1.223452345342"))/>
<cfset row.createCell(2).setCellValue("This is a string")/>
<cfset row.createCell(3).setCellValue(true)/>
</cfloop>
<cfset wb.write(out)/>
<cfset wb.write(fileOut)/>
<cfset fileOut.close()/>
<cfset out.flush()/>
If you are migrating a Powerbuilder Application to .NET the
more recommend language you can use is VB.NET. This because this language has a
lot of common elements with PowerScript. Lets see some simple comparisons.
Variable definition
A variable is defined writing the Data Type just before the name.
For example:
Integer amount
String name
In VB.NET this will
be
Dim amount as Integer
Dim name as String
Constants
constant integer MAX = 100
In VB.NET this will
be
Const MAX As Integer = 100
Control Flow: If Statement
If monto_cuota=13 Then
nombre= 'Ramiro'
ElseIf monto_cuota=15 Then
nombre= 'Roberto'
Else
nombre= 'Francisco'
End If
This code is almost exactly the same in VB.NET
If
monto_cuota = 13 Then
nombre = "Ramiro"
ElseIf
monto_cuota = 15 Then
nombre = "Roberto"
Else
nombre = "Francisco"
End If
Control Flow: Choose Statement
Choose case monto_cuota
Case Is< 13: nombre='Ramiro'
Case 16 To 48:nombre= 'Roberto'
Else
nombre='Francisco'
End Choose
This code is slightly different:
Dim
monto_cuota As Integer
Dim
nombre As String
Select Case monto_cuota
Case Is < 13
nombre = "Ramiro"
Case
16 To 48
nombre = "Roberto"
Case
Else
nombre = "Francisco"
End Select
Control Flow: For statement
For n = 5 to 25 step 5
a = a+10
Next
In VB.NET
Dim n, a As
Integer
For n = 5
To 25 Step 5
a = a + 10
Next
Control Flow: Do Until, Do While
integer
A = 1, B = 1
//Make
a beep until variable is greater than 15 variable
DO
UNTIL A > 15
Beep(A)
A = (A + 1) * B
LOOP
integer
A = 1, B = 1
//Makes
a beep while variable is less that 15
DO
WHILE A <= 15
Beep(A)
A = (A + 1) * B
LOOP
In VB.NET
Dim A As Integer = 1, B As Integer = 1
'Make a beep
until variable is greater than 15 variable
Do Until a > 15
Beep(a)
a = (a + 1) * B
Loop
'Makes a beep
while variable is less that 15
Do While A <= 15
Beep(a)
a = (a + 1) * B
Loop
This is the migration of a snippet of ASP classic to ASP.Net
Checking that a File Exists ASP Classic
<%
Dim strExists
Dim strNotExists
Dim objFileSystemObjectVar
``
strExists = "exists.txt"
strNotExists = "error.txt"
Set objFileSystemObjectVar = Server.CreateObject("Scripting.FileSystemObject")
' The FileExists method expects a fully qualified path and
' use Server.MapPath
%>
<p>
"<%= strExists %>" exists:
<b><%=objFileSystemObjectVar.FileExists(Server.MapPath(strExists)) %></b>
</p>
<p>
"<%= strNotExists %>" exists:
<b><%= objFileSystemObjectVar.FileExists(Server.MapPath(strNotExists)) %></b>
</p>
Checking that a file exists ASP.NET
<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<script language="VB" runat="server">
Dim strExists As String = "exists.txt"
Dim strNotExists As String = "error.txt"
</script>
<p>
"<%= strExists %>" exists:
<b><%=File.Exists(Server.MapPath(strExists))%></b>
</p>
<p>
"<%= strNotExists %>" exists:
<b><%= File.Exists(Server.MapPath(strNotExists))%></b>
</p>