Skip to content

Search Results

Keyword: error

Did you ever have a method that returned a generic list of some type but you actually needed a generic list of one of its interfaces or base class? You probably solved this by cloning the method or by creating a new list while looping through all items. In the article below I will show you a nice and simple generic solution for this problem.

Let’s assume you have a class named Car that has an interface named IVehicle and you also have a class named Plane that also has the interface IVehicle. We also have a data repository that has a method for each of them for retrieving a list of items. Now we want to execute the IVehicle method named Move on all Car objects and Plane objects. We will start by retrieving both lists from our data repository object named MyRepository:

    var cars = MyRepository.GetCars()
    var planes = MyRepository.GetPlains()

Wouldn’t it be nice if we could just concatenate those 2 lists so that we could call the IVehicle method for all of them in one simple loop?

    var vehicles = cars.Concat(planes);
    foreach(var vehicle  in vehicles)
    {
        vehicle.Move();
    }

Unfortunately trying this will give you this error:
Error 1 The type arguments for method ‘System.Linq.Enumerable.Concat(System.Collections.Generic.IEnumerable, System.Collections.Generic.IEnumerable)’ cannot be inferred from the usage. Try specifying the type arguments explicitly.

If we do want to Concat the two collections together, then we first have to cast both collections to th IVehicle interface. At this moment C# 3.0 does not have a simple option to convert a generic list to one of its interfaces or base classes. The .ConvertAll is not easy to use. Fortunately Microsoft recognized this missing feature and in C# 4.0 you will be able to perform this cast by using Covariance and Contravariance. For now you have to use the difficult .ConvertAll method. The simple helper class below will make this easy for you.

    public static class GenericListConverter
    {
        public static T2 AsType<T1, T2>(this T1 model) where T1 : T2
        {
            return model;
        }
        public static IList<T2> ToListOfType<T1, T2>(this IEnumerable<T1> myList) where T1 : T2
        {
            return (new List<T1>(myList.ToList())).ConvertAll<T2>(AsType<T1, T2>);
        }
        public static IList<T2> ToListOfType<T1, T2>(this IList<T1> myList) where T1 : T2
        {
            return (new List<T1>(myList)).ConvertAll<T2>(AsType<T1, T2>);
        }
    }

Using this class is simple. You can just perform a ToListOfType on any generic IEnumerable or IList.

    var cars = myRepository.GetCars().ToListOfType<Car, IVehicle>();
    var planes = myRepository.GetPlains().ToListOfType<Plain, IVehicle>();

The result of this is that you have 2 generic lists of IVehicle and the Concat will now work.

In this case there is an alternative to the above helper class. It is possible to create a helper method that accept anything that implements the IVehicle interface. The code would then look something like:

    ...
        Move((List<Car>)cars);
        Move((List<Plane>)planes);
    ...
    public static void Move<TItem>(List<TItem> vehicles) where TItem : IVehicle
    {
        foreach (var vehicle in vehicles)
        {
            vehicle.Move();
        }
    }

Today I thought about my problem of having my old site still 1/2 alive next to my new WordPress site. On the internet there are still a couple of links that directly point to various files that aren’t used anymore. Wouldn’t it be nice if you could just remove all those old files and still come up with the right WordPress page?

I just made this possible by changing my custom 404 urlrewrite page. This is what my page now does:
1. get whatever is after the domain name from the url and open the wordpress index.php with that part behind it.
2. if the result is not a regular page, then get the words from the url and perform a search.

for instance the link http://evict.nl/error will search for the word error because there is no page named error. One of my old pages http://evict.nl/comdoc/default.asp will now search for ‘comdoc’ and still find the comdoc content (below this post).

Here is the complete sourcecode of my error.asp

<%
Response.Buffer = True
Response.Status = "200 OK"
Response.CharSet = "UTF-8"
Session.CodePage = 65001
myurl = QueryPath()
content = ReturnPage(myurl)
notfound = "Sorry, but you are looking for something that isn't here. You can search again by using the form on upper right of the page..."
if instr(content, notfound) > 1 or len(trim(content)) < 1 then
	Response.Write ReturnPage(SearchQueryPath())
else
	Response.Write content
end if
Response.End()

Function QueryPath()
	' The WordPress location
	w = "http://" + Request.ServerVariables("HTTP_HOST") + "/index.php"
	' Take whatever is after the host name
	q = mid(request.QueryString, instr(request.QueryString, Request.ServerVariables("HTTP_HOST")) , 999)
	' Take the part behind the first /
	QueryPath = w + mid(q, instr(q, "/") , 999)
End Function

Function SearchQueryPath()
	' The WordPress location
	w = "http://" + Request.ServerVariables("HTTP_HOST") + "/index.php?submit=Find&s="
	' Take whatever is after the host name
	q = mid(request.QueryString, instr(request.QueryString, Request.ServerVariables("HTTP_HOST")) , 999)
	' Take the part behind the first / and remove all / and \
	c = LCase(replace(replace(mid(q, instr(q, "/") + 1 , 999),"/"," "),"\"," "))
	' Remove the default.asp or .asp or .
	SearchQueryPath = w + replace(replace(replace(c,"default.asp",""),".asp",""),"."," ")
End Function

Function ReturnPage(myPage)
    on error resume next
	br = Request.ServerVariables("HTTP_USER_AGENT")
	set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
	xmlhttp.open "GET", myPage, false
	xmlhttp.setRequestHeader "Content-Type", "text/HTMI"
	xmlhttp.setRequestHeader "CharSet", "UTF-8"
	xmlhttp.setRequestHeader "User-Agent",br 	' Required for the WPtouch iPhone Theme
	xmlhttp.send ""
	if err.number <> 0 then
		Response.Status = "404 Page not found"
		ReturnPage = "404 Page not found"
	else
		ReturnPage = xmlhttp.responseText  'responseBody
	end if
	set xmlhttp = nothing
End Function
%>

It’s now a litle more than a week since I installed WordPress on my website. Installing WordPress, finding a good looking theme, finding and adding nice plugins and migrating the content from my old site was quite easy. The thing that costed me the most time was a good way to do the url rewrite. I solved that by creating a simple error.asp page and assigning that page to the 404 error. You can find more info about this error.asp here.

One other point that I wanted to solve is that I have multiple domains running on 1 website and I do want multiple WordPress installations but not for all domains. I also did not want to use WordPress MU because of compatibility and flexability issues. I solved this by conditionally setting the database table prefix in the wp-config.php for the WordPress instances I wanted and adding a conditional redirect in the index.php for the none WordPress domains I have. Here is the code that I use.

wp-config.php

$table_prefix  = 'wp_';
$sl = strlen($_SERVER['SERVER_NAME']);
$d = substr($_SERVER['SERVER_NAME'], $sl - 10);
if ($d == 'taalvos.nl'){
	$table_prefix  = 'taalvos_';

index.php

$d = substr($_SERVER['SERVER_NAME'], $sl - 16);
if ($d == 'de-rozemarijn.nl'){
	/** redirect function from wp-app.php should also be included. */
	redirect('default_rozemarijn.asp');
}

The number of Plugins that are available for WordPress can be overwhelming. Below is a list of the Plugins that I installed. Thanks Thushan for a couple of nice tips.

Add to Any: Share/Bookmark/Email Button

Help readers share, bookmark, and email your posts and pages using any service.

Acronyms

A plugin to wrap acronyms in posts and comments with appropriate acronyms. Allows users to manage lists of acronyms through admin interface. Based on Joel Bennett’s Acronym Replacer plugin (http://www.huddledmasses.org/) and Joel Pan’s NP_Acronym plugin for Nucleus CMS.

Akismet

Akismet checks your comments against the Akismet web service to see if they look like spam or not. You need a WordPress.com API key to use it. You can review the spam it catches under “Comments.” To show off your Akismet stats just put <?php akismet_counter(); ?> in your template. See also: WP Stats plugin.

All in One SEO Pack

Out-of-the-box SEO for your Wordpress blog. Options configuration panel

Google XML Sitemaps

This plugin will generate a special XML sitemap which will help search engines like Google, Yahoo, Bing and Ask.com to better index your blog.

New Tag Cloud

The plugin provides an widget wich shows a tag cloud with the tags used by the new WordPress own tagging feature

SyntaxHighlighter Plus

An advanced upload-and-activate WordPress implementation of Alex Gorbatchev’s SyntaxHighlighter JavaScript code highlighting package. See WordPress.com’s “How do I post source code?” for details. Click here for options.

TinyMCE Advanced

Enables advanced features and plugins in TinyMCE, the visual editor in WordPress.

Tweetable

Integrate Twitter with your WordPress blog. Automatically tweet new posts, display your latest tweet in your sidebar, etc.

WordPress Related Posts

Generate a related posts list via tags of WordPress

WPtouch iPhone Theme

A plugin which formats your site with a mobile theme for the Apple iPhone / iPod touch, Google Android and other touch-based smartphones.

This is an FTP library that (like most commercial components) acts as a ‘wrapper’ around’ the wininet.dll FTP api calls and takes that dll to its functional limits. This object makes it easy to add FTP functionality to your application at a proffesional level.

Click here to download the complete source code, the compiled DLL and the demo.

Below you can see some sample code:

Dim oFTP
Set oFTP = CreateObject("EVICT_FTP.FTP")
Dim lngReturn, intLoop, lngFileCount, strFile
oFTP.Disconnect
oFTP.SessionName = "EVICT FTP - http://www.evict.nl"
oFTP.OpenFlag = 0                 ' (0 = Synchrone)
oFTP.OpenType = 0                 ' (0 = PreConfig)
oFTP.PassiveMode = 0              ' (0 = Active)
oFTP.TransferType = 2             ' (2 = Binary)
oFTP.SendTimeOut = 180000
oFTP.ReceiveTimeOut = 180000
oFTP.ConnectTimeOut = 180000
oFTP.ConnectRetries = 10
oFTP.SetLogging "./ftp.log", 31   ' (31 = Log_All)

lngReturn = oFTP.Connect("ftp.microsoft.com", 21, _
    "test_user", "test_password")
If lngReturn = 1 Then
  If oFTP.IsConnected Then
    lngFileCount = oFTP.GetDirListing("", "*.*")
    If lngFileCount >= 0 Then
	  For intLoop = 0 To lngFileCount
        strFile = oFTP.GetDirListingFilename(intLoop)
	    lngReturn = oFTP.GetFile(strFile, "./" & strFile)
	    If lngReturn <> 1 Then MsgBox "Error: " & _
	    lngReturn & " proplem retrieving file " & strFile
	  Next
    Else
      MsgBox "There are no files available", _
      vbExclamation, "Looking for files"
    End If
  End If
End If
lngReturn = oFTP.Disconnect()
Set oFTP = Nothing</span></span>

This is the easiest way to create your own true NT service. Just look at the testService project. This has all the code you need.

Instructions: Before opening the testService project you first need to compile or register EVICT_Service.dll and NTSVC.ocx. NTSVC.ocx is created by Microsoft and written in Visual C. Remember that you always run the compiled version (the testService recognizes this). Otherwise the VB IDE will be registered as the service.

If you run the test service with desktop interaction then you can see the status in the modified title in the task manager. Running the executable will start up the service setup. Also look what happens if you start the executable twice. If you look at the services (in computer management) then you must be aware that it needs a refresh for showing an changed state.

Click here to download the complete source code, the compiled DLL and the demo.

NT Service

Public WithEvents service As EVICT_Service.service
Dim strSaveTitle As String

Private Sub Form_Load()
   strSaveTitle = App.Title
   ' You probably do not want the IDE to become a service
   If isExe = False Then
      If MsgBox("If you are running inside the VB IDE environment, then you are not able to run as a service otherwize you would make a service out of the IDE. But then you would probably like to debug the service Code. so if you like you can still run the code. Press OK to continue or Cancel to stop.", vbOKCancel, "You are running in the VB IDE" ) = vbCancel Then End
      Service_StartApp ' For debugging in the IDE
      Exit Sub
   End If

   ' Make a service out of this application
   Set service = New EVICT_Service.service
   service.ServiceName = "myTestService"
   service.ServiceTitle = "This is my own test service"
   service.ServiceInteractive = False
   service.ServiceStartMode = svcStartAutomatic
   service.ServiceControlsAccepted = svcCtrlPauseContinue
   service.WriteLog = True
   service.MakeMeAService
   ' You can use the following 2 variables if you like. You probably don't need these
   Debug.Print service.isServiceInstalled
   Debug.Print service.ServiceState
End Sub

Private Sub Service_StartApp()

App.Title = strSaveTitle &amp;amp;amp;amp; " (Started)"
' Put here your code for starting the service
End Sub

Private Sub service_StartSetup()
App.Title = strSaveTitle &amp;amp;amp;amp; " (Setup)"
' Just show that we entered startup mode
End Sub

Private Sub Service_ContinueApp()
App.Title = strSaveTitle &amp;amp;amp;amp; " (Restarted)"
' Put here your code for a restart of the service
End Sub

Private Sub service_Control(lngEventNum As Long)
App.Title = strSaveTitle &amp;amp;amp;amp; " (Event=" &amp;amp;amp;amp; lngEventNum &amp;amp;amp;amp; ")"
' Put here your code for control events
End Sub

Private Sub Service_PauseApp()
App.Title = strSaveTitle &amp;amp;amp;amp; " (Paused)"
' Put here your code for pausing a service
End Sub

Private Sub Service_StopApp()
' This one will not show because we will be unloade automaticaly
App.Title = strSaveTitle &amp;amp;amp;amp; " (Stopping)"
' Put here your code for stopping the service (like unloading created objects)
End Sub

Private Sub service_ExitSetup()
' Since we did a setup and are now ready we can quit.
Unload Me
End Sub

Private Sub Form_Unload(Cancel As Integer)
  Set service = Nothing
End Sub

' Test if we are running in the IDE or in a EXE
Private Function isExe() As Boolean
On Error Resume Next
   Debug.Print 1 / 0
   If Err.Number = 0 Then
     isExe = True
   Else
      isExe = False
   End If
End Function

This is a module with one function that will give you some more functionality than what you can do with the App.LogEvent method in VB6.

1. You will be able to specify the EventLog (Application, Security or System)

2. You are able to specify the Source (Your own Application identifier instead of the VBRuntime)

This module is also used in the ExeptionHandler dll.

Click here to download the complete source code.

Here is some sample code:

writelog EventLog_Application,"My Special APP", vbLogEventTypeError, "Oeps, Something went wrong"

With this class object you can send Email using the SMTP protoclol. In general it works like this: Set the properties then call the send method. You can add multiple attachments to the email and it is possible to send HTML formatted mail

There are much more properties, methods and events available than the demo below will show you. Some of the available properties are: Importance, Priority, MSMailPriority, ExpiryDate, Sensitivity, MessageFlag and ReplyBy

Attachments are seperated by a ; You can make these attachments visible inside your HTML email by giving them a name. You can do that by putting a | in front of it and the name before that. sample: attachmentname|attachment.gif You can then show that file (image) in your HTML email with a tag like: <img src=”cid:attachmentname”> This way you can send email messages with embeded pictures without the need for the recipient to click on the download pictures warning.

Click here to download the complete source code, the compiled DLL and the demo.

Here is some sample code:

Public WithEvents SMTPMail As EVICT_SMTP.SMTP
Private Sub cmdSend_Click()
   Set SMTPMail = New EVICT_SMTP.SMTP
   SMTPMail.SMTPHost = "smtp.myprovider.com"
   SMTPMail.SMTPPort = 25
   SMTPMail.From = "me@hotmail.com"
   SMTPMail.FromDisplayName = "Edwin Vermeer"
   SMTPMail.Recipient = "you@hotmail.com"
   SMTPMail.RecipientDisplayName = "It's You"
   SMTPMail.CcRecipient = "other@hotmail.com"
   SMTPMail.CcDisplayName = "Someone else"
   SMTPMail.BccRecipient = secret@hotmail.com
   SMTPMail.ReplyToAddress = "bitbucket@hotmail.com"
   SMTPMail.AsHTML = Me.chkHTML
   SMTPMail.Attachment = "image|c:\windows\Greenstone.bmp"
   SMTPMail.Subject = "this is just a test"
   SMTPMail.Message = "<html><h1>Hello</h1><br/><img
                       src="cid:\image"></html>"
   On Error Resume Next
   SMTPMail.Send
   If Err.Number <> 0 Then MsgBox "Error:" & Err.Number & _
       vbCrLf & Err.Description, vbCritical, "Could not send mail"
   On Error GoTo 0
End Sub

Handeling Errors, Exceptions and warnings is an undervalued part of programming. If you do it well, it could make your debugging life much easier.

Adding code for handeling Errors, Exceptions and Warnings should be:
1. Easy = Just add a dll, add 2 lines to install and uninstall, Add 4 lines of code to each sub
2. Generic = Handle all errors in the same way.
3. Tracable = You do not need an error stack. Just let the error float up in the procedure tree while adding information in each step.
4. Locatable = Use line numbers. The only disadvantage is that it will add 10% to your .exe file size. I find it strange that so litle source code uses line numbers. That is probably because it reminds people to much ot the old Basic versions.
5. Robust = Even handle GPF exceptions. (They are getting rare aren’t they)

Credits: Large parts of the Exception hanler is from a publication by Thushan Fernando.

Click here to download the complete source code, the compiled DLL and the demo.

Here is some demo code that will show you how to user the error handler:

Private Sub Form_Load()
On Error GoTo ErrorHandler
1   InstallExceptionHandler Me, App, True
2   msgbox 1/0
3   Exit Sub
ErrorHandler:
4   HandleTheException "Demo :: Error in Form_Load() on line " & Erl() & " triggered by " & Err.Source & "   (Error " & Err.Number & ")" & vbCrLf & Err.Description, "Error in cmdException2_Click()", enumExceptionHandling_Exception
End Sub

Private Sub Form_Unload(Cancel As Integer)
On Error GoTo ErrorHandler
21   UninstallExceptionHandler
22   Exit Sub
ErrorHandler:
23   HandleTheException "Demo :: Error in Form_Unload() on line " & Erl() & " triggered by " & Err.Source & "   (Error " & Err.Number & ")" & vbCrLf & Err.Description, "Error in cmdException2_Click()", enumExceptionHandling_Exception
End Sub

Private Sub cmdCrash_Click()
On Error GoTo ErrorHandler
32   Call RaiseAnException(cmbException.ItemData(cmbException.ListIndex))
33   Exit Sub
ErrorHandler:
34   HandleTheException "Demo :: Error in cmdCrash_Click() on line " & Erl() & " triggered by " & Err.Source & "   (Error " & Err.Number & ")" & vbCrLf & Err.Description, "Error in cmdCrash_Click()", enumExceptionHandling_Exception
End Sub

In the period 2000 – 2004 I have done a lot of Visual Basic 6 programming which also resulted in a nice collection of reusable code. I did my best to make this code as generic and reusable as possible. Below you can see a short explanation of those portions plus a download link for the source code.

  • Automating Internet Explorer You can open and fully control a Internet Explorer window. Unless you want to know how to hook into IE, i can advice using WatiN instead of this library.
  • Client Server communications This library let you create a client or a server in an easy to use object oriented way. By calling the wininet.dll directly instead of using the winsock control this dll excells in performance and memory usage.
  • ComDoc If you have a OLE/COM component (dll or ocx) and you want to write documentation for it, then ComDoc is the tool for you. ComDoc will use the component itself for building the structure of the documentation and can also make use of the descriptions that are part of the component. For the publication ComDoc uses the DBPublisherobject. Because all the publications are based on templates the outcome is 100% customizable.
  • DBPublisher is a template driven database publication tool. with support for email and ftp.
  • Encryption is a very easy to use ActiveX dll for encrypting and decrypting data. It can be used from almost any programing language. It Has support For RC2, RC4, DES, Triple DES and Triple DES 112.
  • Error handling You can bennefit a lot if you use a generic method for your error handling in your application. Using line numbers in VB is undervalued. You will only get a 10% bigger .exe but it will make your life much easier to debug your application. The demo will also show you how to build an error trace and how to capture GPF errors.
  • Event log is a module with one function that will give you some more functionality than what you can do with the App.LogEvent method in VB6.
  • FTP is a library that (like most commercial components) acts as a ‘wrapper’ around’ the wininet.dll FTP api calls and takes that dll to its functional limits. This object makes it easy to add FTP functionality to your application at a proffesional level.
  • Object browser lets you have a look at the structure of any OLE/COM object. This can be an ActiveX dll, an OCX or an ActiveX EXE. It’s even possible to read out the entire object model of any MS Office application.
  • QuickTip adds a very nice help function to your application. There is even support for getting the help text out of a chm help file.
  • Receiving e-mail using POP3
  • Scraping the web The WebGrabber object is meant to help you to parse table structured data into a database. This is not only usefull for html files with data in a table but it can also be used to parse a csv file into the database
  • Sending e-mail using SMTP
  • Telnet is a library that will let you interact with a host using the Telnet protocol. You can send any command and get the data that is returned by it. It is also possible to react on various events that are triggered.
  • Windows Service is the easiest way to create your own true NT service. Just look at the testService project. This has all the code you need.