Archive | Programming RSS feed for this section

Html helper for showing line breaks from a text area in ASP.NET MVC

5 Apr

This is a quick tip. When getting started with ASP.NET MVC I used to have problems for example when I got some user input inside a textarea and wanted to show this text with the html <br /> tags instead of the system newlines.  I couldn’t get it to work. The line breaks never used to display and the text displayed as one really long paragraph.

So I created this simple custom html helper that takes input from your source and properly formats it to show the line breaks. For lack of a better name,  I called it FormatLines. Here’s the code.


namespace WebUI.Helpers
{
    public static class FormatLinesHelper
    {
        public static string FormatLines(this HtmlHelper helper, string stringToFormat)
        {
            StringBuilder sb = new System.Text.StringBuilder();
            StringReader sr = new System.IO.StringReader(stringToFormat);
            string buffer = null;
            do
            {
                buffer = sr.ReadLine();
                if (buffer != null)
                {
                    sb.Append(buffer);
                    sb.Append("<br />");
                }
            } while (buffer != null);

            return sb.ToString();
        }
    }
}

Usage.

Before you use it make sure to compile the code and import the namespace containing this helper method. You can do the import right in your target view like so …

<%@ Import Namespace=”WebUI.Helpers” %>

or include it in the web.config file under the namespaces section like so …

<add namespace=”WebUI.Helpers”/>

Use the helper anywhere in your view like so …

<%= Html.FormatLines (Html.Encode(Model.Notes)) %>

And your text will clearly be displayed with the new lines.

If you look at the source of the page, you’ll see the <br /> tags placed where your new lines used to be.

Hope this was helpful,

Till next time, yours truly.

ASP.NET MVC 2 Partial Validation

17 Mar

This post was inspired by the technique from Steven Sanderson’s blog post on this same topic.  Since the introduction of validation with the DataAnnotations, the behavior with ASP.NET MVC 2 now is that the framework validates all your model fields when you post a form, regardless of how many fields the form submitted.

This brings some frustration if you need to do some partial validations.  For example if you need to validate just a subset of the fields in your model, and you create a view just for those fields, but when you submit the form you see errors for all the other fields in your model that were not shown in the view. This will bring some confusion for your users.

Partial Validation in Asp.NET MVC

I recently had this scenario where I had a model that goes through four stages. A user creates a document (View 1), submits to the first approving officer(View 2) who approves and submits to the second approving officer(View 3) , who approves and finally submits the approved document back to the initial user(View 4).  Each step has a different view, all of which are bound to the same model. I wouldn’t want the second approving officer to see errors for the third approving officer, etc.

So I tried to use the custom filter “as is”  from Steve’s blog post but it didn’t work.  UpdateModel was throwing the model errors without applying the filter.  I coudn’t trace the source for this behavior. So I modified the code into some kind of a hack just to get the job done, right there in the controller Action.

How it works

I wrap the UpdateModel process in a try catch.  When it throws and exception I catch it and clear all the errors from ModelState for the model fields that were not included/posted in the form.  I then validate the model, now for the fields that were posted with the form and catch any model errors . I then resubmit the view with the right error messages.  It works like a charm.


[HttpPost]
        public ActionResult Edit(int id, FormCollection formValues)
        {
            Document doc = GetDocumentFromDB(id);

            try
            {
                var valueProvider = formValues.ToValueProvider();

                try
                {
                    //tries to update all properties in the model
                    //throws an exception for properties  which were not posted in the form
                    UpdateModel(doc, valueProvider);
                }
                catch (Exception)
                {
                  //clear all the errors for the properties whose values were not posted by the form

                   var keysWithNoIncomingValues = ModelState.Keys.Where(x => !valueProvider.ContainsPrefix(x));

                    foreach (var key in keysWithNoIncomingValues)
                    {
                        ModelState[key].Errors.Clear();
                    }
                }

                //Now we validate only against those properties whose values were posted in the form.
                if (ModelState.IsValid)
                {
				// do your stuff here

                       //commit changes to the database
                        docsRepository.SaveChanges();
                else
                {
                    return View(doc);
                }
            }
            catch (Exception)
            {
                return View(doc);
            }

        }

And thats it.  If you can find a way to create an action filter for the functionality then it’ll be even better because you can use the same attribute in different places in your code and hence DRY.  Hope it was helpful.  Till next time, yours truly.

Custom Action Filters in ASP.NET MVC

23 Feb

In this post we are going to see how to create a custom action filter in ASP.NET MVC.  I am still using MVC 1 but I’m sure this’ll work just fine with MVC 2. I’ll update the post if it works differently on MVC 2.

See this link for an overview of action filters.

Say you have this problem like I did in one of my recent projects.
I needed to show a company logo on all pages but the home page. I know there are a million ways of doing this but I chose to use a custom action filter.

Here’s how I did.

Step 1.
I created a folder called Helpers and added the following class.  The only thing you need to do is inherit from ActionFilterAttribute class. For this particular case I am making the filter work with non AJAX, GET requests only. Notice that I am only adding some text ViewData which will be passed by the action method where we will apply the filter.

public class DataForMasterPageAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //work fot GET requests only
            if (filterContext.RequestContext.HttpContext.Request.RequestType != "GET")
                return;

            //DO NOT work with AJAX requests
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                return;

            filterContext.Controller.ViewData["message"] = "NoLogo";
        }

    }

Step 2.
I applied the filter on my action method in the controller, in this case its the index action method which serves my homepage ( where the logo is not needed)

        [DataForMasterPage]
        public ActionResult Index(int? page)
        {
            //implementation
            return View();
        }

Step 3.

I added a simple conditional check on the master page thats checks if the page has the viewdata we passed with the filter. If it doesn’t exist we show the logo. If it exists we know its the home page so no logo is shown.

Simple as that.

<% if((string)ViewData["message"] == null){ %>
    <img src="../../Content/images/logo.jpg" alt="logo" height="77" width="263" />
 <% } %>
  

And that’s it.
This is just a very simple way to use custom filters. You can do much more powerful stuff with them.
Till next time, yours truly.

Extending NerdDinner: Using AJAX to cancel RSVPs

4 Dec

This is my first post on ASP.NET MVC.  So I decided to choose something small to start with. I’m going to add functionality to the Nerddinner application that will enable users to cancel their RSVPs using a simple AJAX call to a controller.

Okay, if you totally have no idea or clue about what I’m talking about, have a look here, download and read this pdf here and then see the definition below from wikipedia.

The ASP.NET MVC Framework uses a Model-view-controller pattern. Microsoft added this framework to ASP.NET. It allows software developers to build a Web application as a composition of three roles: ModelView and Controller. A Model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the table. A Controller handles interactions and updates the model to reflect a change in state of the application. A View extracts necessary information from a model and renders a user interface to display that

I personally love ASP.NET MVC. Having a strong background in windows development, I totally get it. I didn’t get webforms at all. I tried, but it was too much for me. When I saw MVC for the first time I couldn’t help saying “hellow beautiful!” Its simple and straight forward.

Okay enough talking lets see some code now.  I’ll skip all the deep explanations by assuming that you have read the e-book and probably have built the nerddinner application.  So I’ll go straight to the code and details.

This is how a particular dinner looks like after you log in but before you RSVP.

When you click the link to RSVP you see a smooth animation confirming you reservation, like the image below shows.

And when you come back to the dinner, if you are logged in you’ll just see a notice that you are registered for the event but no option whatsoever for you to Cancel your RSVP, incase you change your mind or you couldn’t make it.

Cancelling RSVPs

Our aim is to enable the user to cancel their RSVP. And we’ll do this using a simple AJAX call to an Action method in the dinners controller.

Steps.

We’ll accomplish this in as a  few as three steps.

1. Create a DeleteRSVP method in dinner repository

The method takes a RSVP as a parameter and deletes it from the database.

Here’s the code,  one line thanks to LINQ to SQL.

public void DeleteRSVP(RSVP rsvp)
{
db.RSVPs.DeleteOnSubmit(rsvp);
}

2. Add an ActionResult method in the DinnersController.  Name it Cancel

The method takes a dinner ID and checks to see if the current user RSVP’d for the dinner. If yes, it cancels the RSVP (by calling our DeleteRSVP method above) and returns a simple message as content. We’ll use some javascript code to display the message to the user with some animation.  See the code below.

// AJAX: /Dinners/RSVPCancel/1

[Authorize, AcceptVerbs(HttpVerbs.Post)]
public ActionResult Cancel(int id)
{
Dinner dinner = dinnerRepository.GetDinner(id);

if (dinner.IsUserRegistered(User.Identity.Name))
{
RSVP rsvp = dinner.RSVPs.Single(r =&amp;amp;gt;       r.AttendeeName.Equals(User.Identity.Name,       StringComparison.InvariantCultureIgnoreCase));
dinnerRepository.DeleteRSVP(rsvp);
dinnerRepository.Save();
}
return Content("Sorry to hear you can't make it! ");
}

3. Add an Ajax.ActionLink to the partial view RSVPStatus.

The Ajax.ActionLink will call our CancelRSVP in the dinners controller and display an animation notifying the user that we are sorry to see them go.  See the full code for the view at the end of the post

Thats it.  Now if a user is logged in and registered for a dinner, they’ll see a link offering to cancel the RSVP (like on this image below.)

When they click the link, our view will call the cancel action method in our dinners controller and cancel the RSVP on the fly, without a full refresh of the page . The user will get an animated notification as shown on the image below.

So thats all. Simple functionality which I think would take longer and be more dificult to implement in web forms..well, at least for me. Till next time, yours truly.

Full Code for the RSVPStatus View. Sorry for the image quality wordpress wouldn’t allow me to post anything with even one line of javascript.



An Overview of Processes and Threads in .Net

24 Sep

It’s been a while since I last posted. I had been tied to projects and couldn’t escape to update the blog. But now I am back and ready to roll.

Today I’ll define the differences between a Process and a Thread. First things first, let’s see the definitions.

A process:

Simply put a process is a term used to describe the set of resources (such as external code libraries and the primary thread) and the necessary memory allocations used by a running application.

For each .exe loaded into memory, the OS creates a separate and isolated process for use during it lifetime. Using this approach to application isolation, the result is a much more robust and stable runtime environment, given that the failure of one process does not affect the functioning of another.

Every win32 process is assigned a unique process identifier (PID).

A Thread:

A thread can simply be defined as a path of execution within a process. The first thread created by a process’s entry point is called the primary thread.

Every Win32 process has exactly one main thread that functions as the entry point for the application. A Win32 Graphical User Interface (GUI) application defines a method called WinMain() as the application entry point, while a console based application defines the Main() method as the entry point.

process-thread relationship

The .Net Framework provides the System.Diagnostics namespace that offers, among others, some types that help with the interaction and manipulation of processes programmatically.

This code below for example will enumerate and list all the running processes and all the active threads running under each process.

I will not go into the details of explaining all the keywords in the code at this moment, but this is simply to further elaborate the differences between a Process and a Thread.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//for processes
using System.Diagnostics;

namespace ThreadvsProcess
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("xxxxx Processes and Threads in .Net xxxxx\n");

ShowRunningProcesses();

//press Enter to exit
Console.ReadLine();
}

static void ShowRunningProcesses()
{
// List all the processes currently running on the local machine.
Process[] allProcesses = Process.GetProcesses(".");

// Show the Process ID (PID) and name of each process.
foreach (Process p in allProcesses)
{
string details = string.Format(" Process ID: {0}\tName: {1}",
p.Id, p.ProcessName);
Console.WriteLine(details);
//show the Threads running under this process
DisplayThreadsForPID(p.Id);
}
Console.WriteLine("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
}

static void DisplayThreadsForPID(int pID)
{
try
{
Process currProc = null;
currProc = Process.GetProcessById(pID);

// List out the details for each thread in the specified process.
Console.WriteLine(" Threads used by: {0}",
currProc.ProcessName);
ProcessThreadCollection allThreads = currProc.Threads;
foreach (ProcessThread th in allThreads)
{
string detail =
string.Format(" Thread ID: {0}\tTime Started: {1}\tPriority: {2}",
th.Id, th.StartTime.ToShortTimeString(), th.PriorityLevel);
Console.WriteLine(detail);
}
Console.WriteLine("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
}
catch (Exception)
{
//ignore the exception for simplicity
return;
}
}

}
}

If you run this code, you’ll see the output similar to the one shown in the  image below depending on the processes currently running on your machine.

output

There’s a lot more you can do with Processes and Threads apart from just enumerating and dumping them to the console window and this was just a scratch at the top to show the differences between the two.

Till next time, yours truly.

Sorting by IComparable vs IComparer

29 Jun

These are two interfaces that used to confuse me. I didn’t know when to use one or when to use the other. The aim of this post is to make it easier for someone to understand the differences and choose appropriately.

In as a few words as possible:
i)A class that implements IComparable can be sorted or compared to another class instance in a manner that you define.

ii)A class that implements IComparer can be used to sort or compare classes that do or do not implement IComparable.

The List.Sort() Method.

Every list(generic list, array, arraylist) has a built-in method called Sort(). The Sort() method knows how to sort all objects that implement the IComparable interface. The method uses an object’s CompareTo() method to compare it with other objects and use its return value to figure out which object comes first.

To sort objects that do not implement IComparable, you have the IComparer Interface. It’s used to assist the list’s Sort() method in sorting its members.

IComparable.
You implement this within the class you want to be sorted. The interface has only one method called CompareTo() that takes an object as a parameter, compares it with the class and returns an integer value that figures out which object comes first.

See the sample class below.

Public Class Person
    Implements IComparable(Of Person)
    'these should be properties
    Public FirstName As String
    Public LastName As String
    Public Age As Integer

    Public Sub New(ByVal first As String, ByVal last As String, ByVal age As Integer)
        Me.FirstName = first
        Me.LastName = last
        Me.Age = age
    End Sub

    Public Function fullName() As String
        Return Me.FirstName & " " & Me.LastName & ": Age - " & Me.Age
    End Function

    Public Function CompareTo(ByVal other As Person) As Integer Implements System.IComparable(Of Person).CompareTo
        If Me.Age > other.Age Then
            Return 1
        ElseIf Me.Age < other.Age Then
            Return -1
        Else
            Return 0
        End If
    End Function
End Class

Notice the CompareTo() method. It takes another Person class as a parameter, compares the Ages and returns a number indicating
which one comes first. In this method you can create any sorting logic that you need.
You could for example compare by Age, FirstName or Lastname. In this sample the classes will be sorted by Age.

Implementation:
One you have a list of objects that implement IComparable, all you have to do to sort them is just call the List.Sort() method without
passing any parameters. See sample code for a button bellow.

Dim list As List(Of Person)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        list = New List(Of Person)
        list.Add(New Person("Nick", "Masao", 27))
        list.Add(New Person("Sydney", "Mtaita", 3))
        list.Add(New Person("Ruth", "Mtaita", 23))

        Debug.WriteLine("")
        Debug.WriteLine("Unsorted:")
        For Each p As Person In list
            Debug.WriteLine(p.fullName)
        Next

'Just call the sort method without passing any parameters and you are done
‘The Sort() method uses the logic in the CompareTo() method in the class to ‘sort the list members

        list.Sort()

        Debug.WriteLine("")
        Debug.WriteLine("Sorted by Age:")
        For Each p As Person In list
            Debug.WriteLine(p.fullName)
        Next
End Sub

The code produces the following output.
IComparable_Output
As you can see the objects were sorted by age.

IComparer.

Implement this in a class that you will use to sort other classes that may or may not implement IComparable. This class will be a ‘comparer’ and will impose the sorting order in the List.Sort() method. The interface has only one method called Compare() that takes two objects and returns a value which determines which object comes first.

To sort a list using IComparer, you need to create a new instance of the class that implements it and pass that instance to the List.Sort() method. The list object will then use the class’s Compare() method to sort the members.

Say for example you have a person class with the following definition.  Note that it doesn’t implement any interface.

Public Class Person
    'these should be properties
    Public FirstName As String
    Public LastName As String
    Public Age As Integer

    Public Sub New(ByVal first As String, ByVal last As String, ByVal age As Integer)
        Me.FirstName = first
        Me.LastName = last
        Me.Age = age
    End Sub

    Public Function fullName() As String
        Return Me.FirstName & " " & Me.LastName & ": Age - " & Me.Age
    End Function
End Class

Now to use IComparer to sort a list of objects like the above, you need to create a simple class that implements IComparer and define the sorting manner, like so.

Public Class PersonComparer_ByAge
    Implements IComparer(Of Person)

    Public Function Compare(ByVal x As Person, ByVal y As Person) As Integer Implements System.Collections.Generic.IComparer(Of Person).Compare
        If x.Age > y.Age Then
            Return 1
        ElseIf x.Age < y.Age Then
            Return -1
        Else
            Return 0
        End If
    End Function
End Class

The Class sorts the Person objects by Age. You could also sort by FirstName or LastName. The only limitation of
IComparer is that it has access to public members of the class only.

See another class that implements IComparer but this time sorts by the FirstName field.

Public Class PersonComparer_ByFistName
    Implements IComparer(Of Person)

    Public Function Compare(ByVal x As Person, ByVal y As Person) As Integer Implements System.Collections.Generic.IComparer(Of Person).Compare
        If x.FirstName > y.FirstName Then
            Return 1
        ElseIf x.FirstName < y.FirstName Then
            Return -1
        Else
            Return 0
        End If
    End Function
End Class

Implementation:
If you have a list of objects, and you have a class that implements IComparer and has the sorting criteria like
the above class then you have to do the following to sort your list.

  1. Create an instance of your sorting class.
  2. Pass that instance to the list.sort() method.
  3. That’s it.

Sample button code that implements the code above.

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        list = New List(Of Person)
        list.Add(New Person("Nick", "Masao", 27))
        list.Add(New Person("Sydney", "Mtaita", 3))
        list.Add(New Person("Ruth", "Mtaita", 23))

        Debug.WriteLine("Unsorted:")
        For Each p As Person In list
            Debug.WriteLine(p.fullName)
        Next

        Debug.WriteLine("")

'instantiate the sorter/comparer class that implements IComparer

        Dim sortName As New PersonComparer_ByFistName

'pass it as criteria to the sort method

        list.Sort(sortName)

        Debug.WriteLine("Sorted by Firstname:")
        For Each p As Person In list
            Debug.WriteLine(p.fullName)
        Next

        Debug.WriteLine("")
'instantiate the comparer class and pass it to the sort method
        Dim sortAge As New PersonComparer_ByAge
        list.Sort(sortAge)

        Debug.WriteLine("Sorted by Age:")
        For Each p As Person In list
            Debug.WriteLine(p.fullName)
        Next
    End Sub

The above code produces the following output.

IComparer_Output

Advantages & Limitations.

The advantage of IComparable is that you have access to the private members. i.e you can create your sorting criteria using private members in the class since the CompareTo() method is withing the class. The limitation is you only have that one way of sorting.

The limitation of IComparer is that the object that implements it doesn’t have access to private members of the objects it sorts. It only has access to public members.

Its advantages are, as seen in the sample code above, you can create a number of sorting options, and you have the option of passing the more specific and more appropriate sorting criteria to the Sort() method.

This post is getting too long  and I think I’ll end it here. Hopefully it was an eye opened of some sorts. Till next time, yours truly.

Bug caused by not paying attention.

24 Jun

I recently wrote the function below in MS Access VBA. I have a string that represent a year formatted as yyyy/yy and the function should return the string as yyyy-yyyy. It makes use of the Access Mid function that gets a substring of a text from any position. So here’s the function.

'returns the year in format 2010-2011
Public Function FormatYear(ByVal theYear As String) As String
On Error GoTo errHandler

Dim first, last, result As String

    first = Mid(theYear, 1, 4)
    last = Mid(theYear, 6, 2)
    result = first & "-20" & last

    FormatYear = result

exitHere:
 Exit Function

errHandler:
 MsgBox err.Description
 Resume exitHere

End Function

So I called the function as shown below and got the weird results. Can you spot the not??

debugWindow

Yeah. The problem was that I supplied the year to the function as a string but without the quotation marks.  Like 2010/11 instead of  “2010/11″ . And that was the cause of the weird results. I guess I was tired.

So after a cup of coffee and a 10 minute break I realized the bug and as you can see below, voila.

debugWindowCorrect

So please pay attention or take a break if you feel like your concentration level is going down.

Till next time, yours truly.

Create a Visual Basic Dynamic-Link Library(dll) from the command line.

28 Apr

A Dynamic-Link Library is a non executable program made of one or more files, which contains classes, procedures, and/or other resources that other programs can use.  Because it is not an executable, it doesn’t need an entry point or the main() procedure  and it usually ends with .dll

Well, you can read more about Dynamic link libraries(dlls) on msdn or wikipedia.

In this post I’ll show you how to create a VB.Net DLL from the command line.

First you need to set up your system to use the vbc compiler. If you do not know how to do this, please read my previous post here.  So from now on I’ll assume you have set up your compiler and we are ready to go.

Steps:

  • Open notepad,  create a class, call it Person and save it as a VB file (Person.vb) . For this post we’ll create a simple Person class.  See the code for the class at the end of the post below.

>>CodeListing No.1 – The Person Class

  • Create a new folder in your main drive (in my case C:\) and call it PersonLibrary.  Save the above class in this folder.
  • Click Start > Run > type cmd  and click OK to open the command prompt.
  • Change to the PersonLibrary directory as shown in the image below.

changedirectory

How to Create a Dynamic-Link Library from the command line.

  1. There are two options. The first one is you create a library that has the same name as the source file.
  • To create a Dll that has the same name as the source file, at the command prompt type the following command.

vbc /target:library Person.vb

  • The command is vbc /target:library nameOfSourceFile.vb notice the space after vbc and the other space after library. Make sure you include them.
  • Browse to the PersonLibrary folder and you’ll see that the Person.dll dynamic-link library has been created. See the image below.

personlibrary1

2.  The other option is that you can provide your own name for the library.

  • To create a Dll that has your own desired name, at the command prompt type the following command.

vbc /target:library /out:PersonLibrary.dll Person.vb

  • The command is vbc /target:library /out:DesiredNameOfLibrary.dll nameOfSourceFile.vb
  • Now browse to the PersonLibrary folder and you’ll see the newly created dll with our custom name PersonLibrary.dll, as well as the old one, Person.dll

personlibrary2

And thats all there is to it. You are done and you have your libraries and you can distribute them now or use them from an application.

How to use the Library.

Before you use the library you simply have to import it into your project and add it as a reference using the command line when compiling.

  • Open Notepad and type in the following code
Imports System
Imports PersonLibrary

Module MainModule
    Sub Main()
        Dim p As New Person("Mike F", "Masao")
        p.Addresses(0) = "6032, Olacity, Arusha"
        p.Addresses(1) = "Tanzania"
        p.Citizenship = "Tanzanian"
        p.BirthDate = #8/21/1982#

        Console.WriteLine("Full Name: " & p.FullName("Mr."))
        Console.WriteLine("Address1: " & p.Addresses(0))
        Console.WriteLine("Address2: " & p.Addresses(1))
        Console.WriteLine("Citizenship: " & p.Citizenship)
        Console.WriteLine("Age: " & p.Age)

        Console.Read()
    End Sub

End Module
  • Save the file as MainProgram.vb under our PersonLibrary folder.
  • Now go back to the command prompt and issue the following command, which will add the library as a reference to the project and then compile the MainProgram code to an executable.

vbc /reference:PersonLibrary.dll MainProgram.vb

  • The command is vbc /reference:NameOfLibrary.dll NameOfMainProgram.vb
  • After the above steps, browse again to the PersonLibrary folder and you’ll see your libraries and your MainProgram.exe executable file as seen in the image below.

aftercompiling

  • Now double click the MainProgram.exe file and you should see the following output on your screen.

output

And we are done.

So now you can create your own libraries by using just notepad and the command prompt.

Hope this was helpful. Till next time, yours truly.

CodeListing No.1  – The Person Class

Public Class Person
    'Fields
    Public FirstName As String
    Public LastName As String
    Public m_BirthDate As Date
    'You can define up to 4 addresses for this person
    Public m_Addresses(3) As String
    Public Citizenship As String = ""

    Sub New(ByVal firstname As String, ByVal lastname As String)
        Me.FirstName = firstname
        Me.LastName = lastname
    End Sub
    Public Property BirthDate() As Date
        Get
            Return m_BirthDate
        End Get
        Set(ByVal value As Date)
            m_BirthDate = value
        End Set
    End Property

    Function FullName(Optional ByVal title As String = "") As String
        FullName = ""
        'use the title if provided
        If title <> "" Then FullName = title & " "
        'append first and last names
        FullName &= FirstName & " " & LastName
    End Function

    'Age is a ReadOnly property
    Public ReadOnly Property Age() As Integer
        Get
            Return Year(Now) - Year(m_BirthDate)
        End Get
    End Property

    Public Property Addresses(ByVal index As Integer) As String
        Get
            If index < 0 Or index > UBound(m_Addresses) Then
                Throw New IndexOutOfRangeException("Invalid address Index")
            End If
            Return m_Addresses(index)
        End Get
        Set(ByVal value As String)
            If index < 0 Or index > UBound(m_Addresses) Then
                Throw New IndexOutOfRangeException("Invalid address Index")
            End If
            m_Addresses(index) = value
        End Set
    End Property

End Class

Using the Timer object and Event Handlers to automatically control actions.

23 Apr

I know I haven’t been able to write for a long time now, and I’ll still be lagging up, but hopefully soon I’ll be back, with full speed, bringing you a new post every week.

Today I’ll show you how to use the System.Windows.Forms.Timer to control when to perform some action or call some procedures. A good example is when you maybe need to send a report to your boss,  say every day at 4pm.timers

In this case, you need a timer object, that calls an event handler which checks the time against your system time to see if it is 4pm or after and then call the procedure that sends the report. Let’s see how you can go about, doing that.

What we need.

  1. A Timer object.
  2. A method to serve as an event handler
  3. Your custom method that does whatever work you want done when it’s time.

We’ll make use of the AddHandler statement to hook up the Timer’s Tick event with our event handler. The AddHandler statement is used to associate an event with an event handler at run time.

See the full code below.

Imports System

Module Sample

Public Class Test

Private Shared myTimer As New System.Windows.Forms.Timer()

Public Shared Sub Main

	'hook up the event to the handler method

        AddHandler myTimer.Tick, AddressOf CheckTime

        ' Sets the timer interval to 1 second and start it.

        myTimer.Interval = 1000

        myTimer.Start()

	MsgBox("The timer is running now....")

	Console.Read()
   RemoveHandler myTimer.Tick, AddressOf CheckTime

End Sub

Public Shared Sub CheckTime(ByVal sender As System.Object, ByVal e As System.EventArgs)

        If DateTime.Parse(DateTime.Now.ToShortTimeString) > DateTime.Parse("11:00 AM") Then

            MsgBox("The time is : " & DateTime.Now.ToShortTimeString)

            'Call SendPendingInvoices()

        End If

    End Sub

End Class
End Module

As you can see above, we created a new Timer object, and in our main procedure, or start up procedure, we hooked up the Timer.Tick event to our CheckTime event handler method, so that it gets called every time the tick event of the timer is fired.  In our case that will be every 1 second.

To test the code, create a new blank console project and copy and paste the code above and simply click run. If your system time is greater than 11:00 AM then you should see a message box pop up every second showing you the current time from your system.

Hope this was helpful.

Till next time, yours truly.

A method for searching a ListView

1 Apr

Here is a simple method that will search a ListView and its subitems and select or highlight the ListViewItem or SubItem that begins with  the search criteria.

In this sample I make use of the ListView.FindItemWithText method which takes three parameters, the first a string specifying the item to find, second a boolen value to specify whether the subitems should be included and the third, the starting index in the listview items collection.

This is how the method works.

  1. The method takes two parameters, first the name of the ListView, and second the text to find.
  2. It starts the search at the first item and goes on until it finds a match. The found ListViewItem is then highlighted.
  3. If you click search again, its starts at the index of the last item and continues until it finds another match.
  4. If no match is found and you click search again, it starts from the beggining, at the first item’s index.

Using the code.

Create a listview object, load it with items and subitems. On your form, outside the method, create these 2 variables:

  • lastSearch, String - This will save your previous search text and compare it with the current text when you call the method again.
  • lastIndex - Integer – Set it to -1. - This will save the index of the found item so that the method starts from here when called again.

After this, call the method and pass the name of the listview you want to search and the text to find.

Here is the full code. You can use it as is, or you can modify it and add some changes as you see fit.

    Private lastSearch As String = ""
    Private lastIndex As Integer = -1

Private Sub SearchListView(ByVal listView As ListView, ByVal txtFind As String)

        Dim foundItem As ListViewItem = Nothing

        If lastSearch = txtFind Then
            If lastIndex < listView.Items.Count - 1 Then
                foundItem = listView.FindItemWithText(txtFind, True, lastIndex + 1)
            Else
                foundItem = listView.FindItemWithText(txtFind, True, 0)
            End If
        Else
            foundItem = listView.FindItemWithText(txtFind, True, 0)
        End If
        lastSearch = txtFind
        lastIndex = -1
        If Not (foundItem Is Nothing) Then
            lastIndex = foundItem.Index
            listView.Focus()
            listView.Items(foundItem.Index).Selected = True
        End If
    End Sub

I wrote this in .Net 2.0 but it should work with 3.0 and 3.5. The method is not perfect, its just an eye opener and the rest is up to the user to dig and improvise.

Till next time, yours truly.

Follow

Get every new post delivered to your Inbox.