Archive for 'Programmering'

Running and debugging a SQL Server 2000 DTS Package in Visual Basic 6.0

If you have a fairly complex DTS-package (Data Transformation Services) in SQL-Server 2000 and don’t have a clue of what it does and have a limited understanding of dts read this. You can ”export” the package to VB6 and by doing so you can read the code and run and debug the script from the VB6-IDE. You can even run it in VB.NET. This is quite old school but sometimes necessary to do in legacy systems if you want to edit a complex dts-script.

Step 1 – Export the dts-package to visual basic

Open your DTS-package in SQL-server 2000.

Choose ”Package -> Save as” in the menu and then change ”Location” to ”Visual Basic file” in the dialog. Press OK and then a bas-file (VB-module) is saved to disk.

Step 2 – Create a visual basic project

Open Microsoft Visual Basic IDE. Choose to create a new ”Standard EXE” project then click ”Open”. Remove the default Forms1 from the project. Then you add the dts bas-file to the project with ”Project -> Add module”. The result should should look like below.

Step 2 – Executing and debugging the dts-package

Go to ”Project -> References” and add references to ”Microsoft DTSPackage Object Library” and ”Microsoft DTS Custom Task Object Library”. Now you are ready to edit your package.

To debug the package you simply set a breakpoint and hit F5.

Now feel free to fool around with the package/module and make the changes that you need. It is not easy at first but after a while you get the hang of it.

Step 3 -Saving the dts-package to SQL-server

When your package is ready for deployment you can deploy it through VB. Instead of executing the package you can easily save it to your SQL-server.

Search for the ”Save or execute package” section in the module. Comment the Execute statement and uncomment the SaveToSQLServer row.

Hit F5 to run the module. If everything works fine your new dts-package shows up in SQL-server.

More help with DTS can be found and at sqldts.com/

How to create a printerqueu with .NET and WMI

This is an example of how you create a printerqueue with .NET and WMI (Windows Management Instrumentation).

A list of properties can be found at MSDN Win32_Printer

Other topics:
How to install printerdrivers with wmi and VB.NET
How to create TCP/IP printerports with .NET

Imports System.Management

Dim shared as Boolean = true

Try
 Dim mp As ManagementPath = New ManagementPath("Win32_Printer")
 Dim co As ConnectionOptions = New ConnectionOptions()
 co.EnablePrivileges = True
 co.Impersonation = ImpersonationLevel.Impersonate

 Dim ms As ManagementScope = New ManagementScope("\\" + Environment.MachineName + "\root\cimv2", co)

 Dim printerObject As ManagementObject = New ManagementClass(ms, mp, Nothing).CreateInstance()
 printerObject("PortName") = "IP_192.168.0.2"
 printerObject("DriverName") = "DriverName"
 printerObject("DeviceID") = "queuename"
 printerObject("Location") = "Placement of printer"
 printerObject("Comment") = "Some comments"

 If (shared) Then
  printerObject("Shared") = True
  printerObject("ShareName") = "Sharename"
  'printerObject("Published") = False ' Publish printer
 End If

 Dim options As PutOptions = New PutOptions()
 options.Type = PutType.UpdateOrCreate
 printerObject.Put(options)

Catch ex As Exception
 ' Do something
End Try

Install printerports with WMI and VB.NET

This is an example of how you install TCP/IP printerports with .NET and WMI (Windows Management Instrumentation).

A list of properties can be found at MSDN Win32_TCPIPPrinterPort

Other topics:
How to install printerdrivers with wmi and VB.NET
How to create a printerqueu with .NET and WMI

Imports System.Management

Try
  Dim mp As ManagementPath = New ManagementPath("Win32_TCPIPPrinterPort")
  Dim co As ConnectionOptions = New ConnectionOptions()
  co.EnablePrivileges = True

  Dim ms As ManagementScope = New ManagementScope("\\" + Environment.MachineName + "\root\cimv2", co)

  Dim port As ManagementObject = New ManagementClass(ms, mp, Nothing).CreateInstance()
  port.SetPropertyValue("Name", "portname")
  port.SetPropertyValue("Protocol", 1)
  port.SetPropertyValue("HostAddress", "10.15.12.12")
  port.SetPropertyValue("PortNumber", "9100")

  Dim po As PutOptions = New PutOptions()
  po.UseAmendedQualifiers = True
  po.Type = PutType.UpdateOrCreate
  port.Put(po)
Catch ex As Exception
  ' do something
End Try

Install printerdrivers with WMI and VB.NET

This is an example of how you install printerdrivers with .NET and WMI (Windows Management Instrumentation). Most examples on the Internet shows how this can be done with vbscript, printui.dll and such…

A list of properties can be found at MSDN Win32_PrinterDriver

Other topics:
How to install printerports with WMI and VB.NET
How to create a printerqueu with .NET and WMI

Imports System.Management

Dim infPath  as String = "c:\driver\printerdriver.inf"
Dim mp As ManagementPath = New ManagementPath("Win32_PrinterDriver")

Dim co As ConnectionOptions = New ConnectionOptions()
co.EnablePrivileges = True

Dim ms As ManagementScope = New ManagementScope("\\" + Environment.MachineName + "\root\cimv2", co)

Dim mcPrinterDriver As New ManagementClass(ms, mp, Nothing)
mcPrinterDriver.SetPropertyValue("Name", "drivername")
mcPrinterDriver.SetPropertyValue("SupportedPlatform", "Windows NT x86") ' x86-architecture
'mcPrinterDriver.SetPropertyValue("SupportedPlatform", "Windows x64") ' x64-architecture
mcPrinterDriver.SetPropertyValue("Version", 3)
mcPrinterDriver.SetPropertyValue("FilePath", System.IO.Path.GetDirectoryName(infPath))
mcPrinterDriver.SetPropertyValue("InfName", infPath)

Dim inParams As System.Management.ManagementBaseObject = Nothing
inParams = mcPrinterDriver.GetMethodParameters("AddPrinterDriver")
inParams("DriverInfo") = CType(mcPrinterDriver, System.Management.ManagementBaseObject)
Dim outParams As System.Management.ManagementBaseObject = mcPrinterDriver.InvokeMethod("AddPrinterDriver", inParams, Nothing)

Dim uiReturnValue As UInteger = System.Convert.ToUInt32(outParams.Properties("ReturnValue").Value)

I have tested this in Windows XP, Windows 7 and Windows 2008R2. Make sure your account has privileges to install drivers.

On Windows XP the drivers are installed physically to:
C:\WINNT\system32\spool\drivers

And in the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Environments

Sun Certifierad Java Programmerare (SCJP)

Det har inte blivit något skrivet här på sistone eftersom jag pluggat frenetiskt de senaste veckor för att certifiera mig inom programmeringsspråket Java. Idag skrev jag provet hos Cornerstone i Sundsvall och klarade det. Jag fick 68% rätt på de 72 frågorna, där gränsen var 59%. Yippie, fy fan vad jag fick slita…

Nu är jag alltså certifierad java utvecklare enligt Sun. Nästa mål är att certifiera mig som Microsoft Certified Technology Specialist (MCTS) i .NET Framework 2.0.

Detta ska firas i helgen!

champagnebottle

Confirm javascript on .NET Linkbutton in datagrids

Today I was struck with some really weird behaviour from a LinkButton in a Datagrid. I could not get the the confirm() javascript to fire. My code-behind was something like this:

LinkButton lb = ((LinkButton)dgItem.FindControl(”lb”));
lb.Attributes["onClick"] = ”return confirm(‘Do you really want to do that?’);”;

I dont really know why the onClick confirm-box does not fire before the href PostBack. However, the solution was to put the LinkButton inside a span and put the onClick attribute on the span.

// Web page
<span runat="server" id="spanLb">
<Linkbutton stuff/>
</span>

//Code-behind
HtmlControl spanLb = ((HtmlControl)dgItem.FindControl(”spanLb”));
spanLb.Attributes["onClick"] = ”return confirm(‘Do you really want to do that?’);”;

Strip tags from a string

It is often useful to have a way to strip html or other tags from a string. Php has the strip_tags function. Stripping tags could be done in .NET with the following code that returns the stripped string:

public static string StripTags(string str)
{
return Regex.Replace(str, @”<(.|\n)*?>”, string.Empty);
}

firstChild and nextSibling differences between Firefox and Explorer

This post describes a weird difference in how Internet Explorer and Firefox handles the Document Object Model (DOM). In my case I got different browser-behaviour when using firstChild and nextSibling in a javascript. The problem is that the Firefox DOM does not ignore line breaks and whitespaces while IE does.

Instead of using firstChild and nextSibling you can use these functions (look below) that searches for the correct element in both major browsers.

Use getNextSibling(element) instead of element.nextSibling.
Use getFirstChild(element) instead of element.firstChild.

function getNextSibling(startBrother)
{
endBrother=startBrother.nextSibling;
while(endBrother.nodeType!=1)
{
endBrother = endBrother.nextSibling;
}
return endBrother;
}

function getFirstChild(elm)
{
if ( !elm.childNodes.length )
{
return;
}
var children = elm.childNodes.length;
for ( var i = 0; i <= children; ++i )
{
if ( elm.childNodes[i].nodeType == 1 )
{
return elm.childNodes[i];
}
}
return;
}

Submitta asp.NET formulär med enter-knappen

En klassisk bugg i asp.NET (1.1 åtminstone) är att formulär med endast en textruta och en submit-knapp inte submittas då man fyller i rutan och trycker på enter-tangenten. Eller jo, sidan submittas men eventet för submit-knappen körs inte. Lösningen är enkel, men väldigt svår då man inte vet om att det är en bugg. Det räcker med att man skapar en osynlig textruta (input). En mer utförlig förklaring till fenomenet finns här.

Exempel:

<input type=”text” style=”display:none”/>

Focus till komponent vid postback utan SmartNavigation

Ett problem med web forms är att dom tappar focus då man gör en postback. Man kan däremot använda SmartNavigation för att lösa detta, men det finns situationer då detta inte fungerar tillfredställande. Då kan man använda sig av denna kodsnutt som sätter focus på den komponent som orsakade postbacken.

Lägg in i din Page_Load:

if(Page.IsPostBack)
{
SetFocusPostBackControl(this);
}

Samt lägg till metoden:

///
/// Sätter fokus vid postback på den kontroll som hade focus
///
///
public void SetFocusPostBackControl(System.Web.UI.Page webPage)
{
string[] ctlPostBack;

ctlPostBack = webPage.Page.Request.Form.GetValues(”__EVENTTARGET”);
if (ctlPostBack != null && ctlPostBack.Length > 0)
{
string ctlUniqueId;
ctlUniqueId = ctlPostBack[0];
System.Web.UI.Control findControl = webPage.Page.FindControl(ctlUniqueId);
if ((findControl != null) &&
(findControl is DropDownList ||
findControl is TextBox ||
findControl is RadioButton ||
findControl is RadioButtonList))
{
string ctlClientId;
ctlClientId = findControl.ClientID;
string jScript;
jScript = ””;;

webPage.Page.RegisterStartupScript(”focus”,jScript );

}
}
}