Archive for General

Sell your domain with an auction

I was giving a look around for some way to make money :) and i noticed that the domain name after market is a very good opportunity. If you have a good domain name and it’s registration is old enough you can plan to sell it on tdnam.com
TDNAM is The Domain Name After Market, a service provided by Godaddy.com, there you can open a new auction to sell your domain. Before starting to sell you can get a domain name appraisal so you can figure out the possible selling price, maybe you’re rich but you don’t know yet. I request the appraisal for one of my domains and the resulting value was of 64.000$, not so bad :)

Godaddy gets about 5$ for a simple appraisal and about 15$ for a professional appraisal but you can find free appraisal sites all over the web.

If you’re planning to sell your domain go to www.tdnam.com and open your auction, i’ve seen domains selled for 250.000$, icredible but true!!!

Making money with the web is not so difficult, you just need to be a little lucky and know what the web can offer ;)


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

globalwarming awareness2007

It’s the keyword choosen for the SEO Wolrd Championship 2007.
I like very much this choice because the Global Warming is a really dangerous issue to be threated as soon as possible if there’s time left to recover the damages made by man.
Overheating is causing a lot of troubles all around the world and you can see it in Europe too. This year, for the first time, Europe has been invested by a tornado, it’s because of globalwarming for sure.
Italian Cities like Venice and Livorno have an high risk to be fully covered by sea and become the future Atlantis, it’s getting really dangerous… there’s no more time to waste.
Important informations about globalwarming awareness2007 can be found clicking these links:

Giuseppe Liguori globalwarming awareness2007 site
Ivano Di Biasi globalwarming awareness2007 site


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Google and Yahoo Bowling

This month i discovered a new interest, Search Engine Optimization.
Few days ago the SEO world championship is started and i created a website for fun to see if i could have some results. It’s incredible but sometimes i reached very high positions in the contest leaderboard. This morning i was 11th and in the scoreboard history i’ve seen i’ve been 4th too. Very hard to figure out the reason of this high position but i have to tell that it’s very intrigating. I hope i’ll not loose my mind with this thing :)

SEO World Championship

When i saw this high position i decided to buy backlinks (one way links) to my website to grow the site popularity and reach higher positions on search engines. As the new links was indexed i noticed that the website was listed on top of searchs, the result was good but after a little while my website disappeared from Google and Yahoo, it was only rated 4th on MSN. Giving a look around on the web i knew about Google and Yahoo Bowling. It’s called so because it’s like throwing a bowling ball thowards your site, it goes down. Google and Yahoo are commercial search engines that earns money with text advertisement, so they have an algorithm to detect high incoming links to a website in a short time interval, so if you buy 5000 links it’s suddenly detected by Google and Yahoo. They penalise the website that receives the incoming links because in this case they’re loosing a potential customer. MSN doesn’t penalise these sites because they’re focusing their work on the search engine improvement and not on commercial aspects. It’s what i read on various websites, will it be true? I really don’t know but it’s sure that this thing happened to me too, my website disappeared from Google and Yahoo when i bought text links. All that i can say is, “be careful and add links in a slow and progressive way”.


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Play wav file in vb.Net

Today i was working on a restaurant software, the customer asked me to play a sound alarm when a new order arrives because he can’t stay all the time looking at the software. I found it very easy, the .net framework is really rich of useful classes to use :)

Here is the code to play a wav file:

Dim Sound As New System.Media.SoundPlayer()

Sound.SoundLocation = “your path to the .wav file” ‘ex.: c:\mysound.wav
Sound.Load()
Sound.Play()

That’s all, extremely easy… i really don’t know why i wrote this :) maybe you could save 1 minute of time


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Class Diagrams in Visual Studio.Net

Today i gave a look at a new feature of Visual Studio.Net, the Class Diagrams.
I found this new functionality really interesting for Object Oriented Programming. A lot of times i had to make really complex classes and when the project growed up it was an hard task to have clear in mind the classes hineritance, methods, events etc…
In the past i used specialized tools but they was just for drawing, they had no integration with the source code. The .Net Class Diagrams is fully integrated with the code instead. When you design a class diagram you can add fields, methods, hineritance and properties and the editor generates the source code for the classes you’re designing.

I tried to create a really unuseful class diagram as test:

class diagram

Please don’t care about the classes meaning :) it’s just a test.
Here you can see a base class “veicle” and specialized classes for each veicle (Cars,Trucks, Bikes etc…).
The Class Diagram Designer generates the class source code for each class you design. Double clicking on a class design you’ll access the source code to make your modifications.
I recommend to use this new functionality, it’s really timesaving for project managers and a wonderful resource to create documentations for your source code.


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

web.config appsetting section in asp.net 2.0

Storing configuration informations has never been so easy like in ASP.Net 2.0.

You can store all your config parameters inside the appSettings section of the web.config file.

Example (Into the web.config file) :
As you can see, you can store every parameter you need for your website.

<configuration/>
    <appSettings>
          <add key="DBHost" value="localhost"/>
          <add key="DBPort" value="3306"/>
          <add key="DBUser" value="root"/>
          <add key="DBPass" value="test"/>
          <add key="DBName" value="mysitedatabase"/>
          <add key="SiteTemplate" value="Default"/>
          <add key="SiteName" value="www.mywebsite.domain"/>
          <add key="EnterpriseName" value="My Enterprise"/>
          <add key="SMTPHost" value="out.myserver.domain"/>
          <add key="SiteEMail" value="info@mywebsite.domain"/>
    </appSettings>
</configuration>

Download this code: webconfig.txt

Now to read configuration parameters from an asp.net page you just need to do this:

dim dbhost as string = System.Configuration.ConfigurationManager.AppSettings(”DBHost”).ToString()
dim DBPort as string = System.Configuration.ConfigurationManager.AppSettings(”DBPort”).ToString()

and so on for all parameters….

It’s a simple task but i hope it will helps…


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Thread synchronization in .Net

Multithreading is a great thing but you need to know that operations are not performed perfectly as you write them in your code. If you write a=a+1 you assume that the thread will execute it in just an operation but it’s not so. Multithreading happens at a very lower level (like in assembly), so your operations could be splitted in smaller one and could not be completed while passing the CPU control to another thread. What happens if different threads uses the same variables? Maybe that variables values could not be exactly what you where expecting :), so give a look at this article i found on the web, it’ talks about locking and synchronization in general.

Imagine the following lines of code:

Dim X as Integer
X = 1
X = X + 1

The line X = X + 1 is a single operation to a programmer. But consider this line from a computer’s perspective. Computers use machine language, which could mean many separate operations for each line of code. For example, the line above could be broken down into several operations, such as: Move the value of X into a register, move the value 1 into another register, add the two registers and place the value into a third register and finally, move the added values into the memory address of the variable X.

Imagine the above situation with multiple threads trying to access the variable X at the same time. Synchronization is the process of eliminating these kinds of errors. Without synchronization programming, the computer could stop the first thread at any point in time and let the second thread access the variable. If the second thread was also incrementing X by 1, it might finish and then the computer would resume the original thread that was running. This thread would restore its variable information, replacing the new X with the old value and nullifying the work that the second thread accomplished. This is called a race condition. These errors are very hard to find and it is best to put time in preventing them.

To synchronize code, you utilize locks. A lock is a way to tell the computer that the following group of code should be executed together as a single operation and not allow other threads to have access to the resource that is locked until the locking code is finished. In the case study we will examine the different types of locks and objects that allow locking and discuss when to use each method. When your code can handle multiple threads safely, it is considered thread safe. This common term is used on code libraries and controls to designate that they are compatible with multiple threads.

Synchronization also adds a new type of bug you need to watch out for, deadlocking. Deadlocking can occur if you are not careful with your locking techniques. For example, assume that we have two resources, A and B. Thread 1 calls and locks resource A at the same time thread 2 calls and locks resource B. Thread 1 then requests resource B and thread 2 requests resource A. This is called a deadlock. Thread 1 cannot release resource A until it gets resource B and thread 2 cannot release resource B until it gets A. Nothing happens and your system cannot complete either of the two threads. Needless to say, this is very bad.

The only way to avoid deadlocks is to never allow a situation that could create one. Code both threads to allocate resources in the same order. Have thread 1 allocate A and then B and the same with thread 2. This way thread 2 will never start until thread 1 is finished with resource A. Then it will wait until thread 1 is finished with resource B before continuing and avoid the deadlock. Another good practice is to lock resources as late as possible. Try to avoid getting locks until you absolutely need them and then release them as soon as possible. Next, we shall take a look at all the different methods of thread synchronization that the common language runtime provides.

Interlocked Class

Because they are very common programming techniques, variable increment and decrement have their own framework class, the Interlocked class. This class provides simple thread-safe methods to do some common tasks with variables. The Increment and Decrement methods add or subtract 1 from a variable. These methods can be considered €œatomic.” This means that the operating system will consider the entire operation as one, not allowing other threads to interrupt their execution. The class is a member of System.Threading namespace. To use the functions without fully qualifying the name, add an Imports System.Threading line. I will assume that the System.Threading namespace has been imported for all of the examples in the case study.

Listing 2

Dim X as Integer
X = 1
X = Interlocked.Increment(X)
X = Interlocked.Decrement(X)

The above code ensures that the computer will not interrupt the increment or decrement of the variable X.

There are two additional methods in the Interlocked class, Exchange and CompareExchange. Let us take a closer look at the two. The Exchange method replaces the value of a variable with the value supplied. The second value could be a hard coded value or a variable. Do not let the name of the method, Exchange, confuse you though. Only the first variable passed in the first parameter will be replaced by the second. The method will not really exchange the values of two variables.

Listing 3

Dim X as Integer = 5
Dim Y as Integer = 1
Interlocked.Exchange(X, Y) ‘X now equals 1 Y isstill 1
Interlocked.Exchange(X, 4) ‘X now equals 4CompareExchange will do a comparison of two variables and if they are equal, replace the one used as the first parameter with the supplied value.

Listing 4

Dim i As Integer
i = 200
Interlocked.CompareExchange(i, DateTime.Now.Day, 200)

The above code creates a new integer and then assigns the value 200 to it. We then call the Interlocked.CompareExchange. The method compares the variable i with 200 and since they are the same, it will replace i with DateTime.Now.Day, the current day of the month.

The Interlocked class allows you to do basic programming techniques and make them thread safe. Let us examine how to do more than just basic commands now. The .NET Framework provides several classes and Visual Basic .NET provides one method to handle complete synchronization. First, we will take a look at the SyncLock Visual Basic .NET keyword.

SyncLock Keyword

The SyncLock keyword (lock in C#) gives an easy way to quickly lock parts of code. It is now a built in keyword in Visual Basic.Net. Take a look at the following code segment:

Listing 5

Dim sText as String
Dim objLock as Object = New Object()
SyncLock objLock
sText = “Hello”
End SyncLock

First we declare a new string, sText. Then we set up a SyncLock block to control access to the object using another locking object, objLock. This guarantees that only one thread at a time can set the object to the string “Hello”. A lock object must be used or an exception will be thrown on the Exit call. If you try to use an object that has changed since the Enter call, the Exit will fail, so you cannot lock on sText itself. The most common use of SyncLock is to lock the entire object it is in by using the Me keyword as the parameter of the SyncLock. This will lock the object for all threads except the executing one. This provides a very high degree of control over the locking patterns of the object at the cost of flexibility.

Listing 6

Public Sub Foo()
Dim sText As String
SyncLock Me
sText = “Hello”
End SyncLock
End Sub

Locking the entire object is usually a great waste of time and processing power. Other methods in the Me object that have locking code based on the Me object will not be accessible to any threads while in the lock. If a more flexible approach is needed, a locking variable can be used. Locks can only be obtained on reference types. If a lock on a value type is needed, you must use a locking object as shown below. The code locks access to iData via a reference type, System.Object. Imagine the locking object as a key to the code. Only one thread at a time can have the key. This allows for much greater control over what gets locked. This method will also not lock the whole Me object. Other threads are free to access other methods of Me, which is much more efficient and will reduce the possibility of deadlocks.

Listing 7

Public Sub Foo()
Dim iData As Integer
Dim objLock As Object = New Object()
SyncLock objLock
iData = 3
End SyncLock
End Sub

One drawback to using SyncLock is that other threads must wait forever for the lock to be released if they need the locked resource. They will never time out. If you are not careful and enter an infinite loop in the locking thread, or hog resources, you can easily create deadlocks or periods of time where nothing happens. In later sections, better methods of synchronization will be discussed.

Flow control statements such as GoTo cannot move the code flow into a SyncLock block of code. The thread must execute the SyncLock keyword. Old Visual Basic 6 error handling cannot be used from inside a SyncLock block either since it uses exception handling internally. Since all new code should be written with exception handling, you probably will not run into a situation like this unless upgrading a legacy application. I would highly recommend rewriting any legacy error handling even if the methods are not used for multithreading. Neither of the following code blocks will compile:

Listing 8

SyncLock Me
On Error GoTo Errhandle ‘won’t compile
Dim i As Integer
i = 5
End SyncLock
Exit Sub
Errhandle:
Or:
GoTo Enter
Here ‘won’t compile
SyncLock Me
EnterHere:
Dim i As Integer
i = 5
End SyncLock
Monitor Class

To examine how SyncLock works, we have to explore a framework class, the Monitor class. The Monitor class does exactly what it says: monitors the access to a region of code and prevents multiple threads from entering. If you are familiar with win32 programming using C++, Monitor is similar to a critical section. Monitor creates a lock on an object that does not allow any other threads to obtain access to the object until released by the locking thread. These locks are on sections of memory, hence the common name critical section. We will first see how to control access to a block of code, just like with the SyncLock keyword.

The Enter function of the Monitor class works just like the SyncLock keyword and the Exit function like the End Synclock keywords. Internally SyncLock uses the Monitor class to implement its functionality and generates the inner Try Finally block of the code sample for you. Let us look at the code now:

Listing 9

Public Sub Foo()
Dim sText As String
Dim objLock As Object = New Object()
Try
Monitor.Enter(objLock)
Try
sText = “Hello”
Finally
Monitor.Exit(objLock)
End Try
Catch e As Exception
MessageBox.Show(e.Message)
End Try
End Sub

This provides the exact same functionality that the above SyncLock example did. You will also notice that the Exit is contained in the finally clause of a Try Catch Finally block. This is to ensure that Exit gets called so the thread will not get locked infinitely. Monitor.Enter is also called outside of the Try Catch Finally block. This is so Monitor.Exit will not get called if the Enter method does not, as it will throw another exception. So why should we use Monitor, if the SyncLock keyword provides the same functionality without the extra work of Monitor? We will examine the reasons why Monitor should be used as we look at the other methods of Monitor.

We said earlier that the SyncLock block would wait indefinitely on the executing thread to release the lock. The Monitor class provides a much better method to handle this, the TryEnter method. This is the first reason why you would use Monitor over SyncLock. This method will allow the calling thread to wait a specific amount of time to acquire a lock before returning false and stopping its execution. This allows graceful handling of long running threads or deadlocks. If a deadlock has occurred, you certainly do not want to add more threads that are trying to get to the deadlocked resource.

The default method of no parameters will try to acquire a lock and if unsuccessful it will immediately return false. There are also two additional overloads that will wait for the specific number of milliseconds, or the specified TimeSpan. This offers much more flexibility than SyncLock.

Listing 10

Dim objLock As Object = New Object() ‘Object in yourClass
Public Sub Foo()
Dim sText As String
Dim bEnteredOk As Boolean
bEnteredOk = Monitor.TryEnter(objLock, 5000)
If bEnteredOk = True Then
sText = “Hello”
Monitor.Exit(objLock)
End If
End Sub

This example will try to acquire a lock for five seconds. If successful, the string is set to “Hello.”

The rest of Monitor’s methods must be examined together. The SyncLock keyword and the Monitor.Enter rely on putting waiting threads to sleep to stop their execution. This is not the best practice to follow as there is no way to get them to stop waiting unless aborted. The Monitor.Wait and Monitor.Pulse allow threads to wait on other conditions before starting. The methods will place the thread in a wait state allowing other threads to specify when they need the waiting thread to run. An example of this is a queue. You could have a thread that waits in an idle state until other threads place objects in the queue for it to work on.

To use the methods, you first tell a thread to wait on an object with a Monitor.Wait call, like below.

Listing 11

Dim objLock As Object = New Object()
Dim bPulsed As Boolean
Monitor.Enter(objLock)
bPulsed = Monitor.Wait(objLock)
If bPulsed Then
‘thread was pulsed
End If
Monitor.Exit(objLock)

The thread is automatically unlocked with the Wait call. You must be sure to call Monitor.Exit when the thread is pulsed and done with its work or you will have a block that could result in a deadlock. The first thread will wait until the pulsing thread has released its lock. This will make the thread wait until a Monitor.Exit is called, like the following.

Listing 12

Monitor.Enter(objLock)
Monitor.Pulse(objLock)
Monitor.Exit(objLock)

If the Exit call is left off, a block occurs because the waiting thread cannot obtain its lock on the object that the pulsing thread has. You must also use the same object to lock on and pulse from the second thread that the waiting thread used to wait on, objLock. Also, both Wait and Pulse must be called from a locked block of code, hence the Enter and Exit calls in the above code. You should exit immediately after calling Pulse to allow the first thread to perform its work, since the pulsing code has the current lock on objLock.

The Monitor class also comes equipped with a PulseAll method. Unlike Pulse, which will only start the next waiting thread, PulseAll removes the wait state from all waiting threads and allows them to continue processing. As with the Pulse method, PulseAll must be called from a locked block of code and on the same object that the original threads are waiting on.

The Monitor class will provide for most of your threading synchronization needs. It should always be used unless a more specific task calls for the next few classes we will examine. Here is a review of some good practices to follow when using Monitor:

  • Exit MUST be called the same number of times Enter is called or a block will occur.
  • Make sure that the object used to call Enter is the same object that is used to call Exit or the lock will not be released.
  • Do not call Exit before calling Enter and do not call Exit more times than calling Enter or an exception will occur.
  • Place the Exit method call in a Finally block. All code that you wish to lock should be in the Try section of the corresponding Finally block. The Enter call should be in its own Try block. This eliminates calling Exit if the Enter fails.
  • Do not call Enter on an object that has been set to Nothing or an exception will occur.
  • Do not change the object that you use as the locking object, which brings in number 7.
  • Use a separate locking object and not the changing object. If you use an object that has changed, an exception will be generated.

TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Domain IP resolution in vb.net

Hi all, sometimes it could be useful to resolve a domain IP address so i wrote this simple function.

Public
function GetIP(ByVal domain as String) as String

Try
Dim Ips As New Collection
Dim i As Integer
Dim ipEntry As Net.IPHostEntry = System.Net.Dns.GetHostEntry(domain)
Dim ipAddr() As Net.IPAddress = ipEntry.AddressList
For i = 0 To ipAddr.GetUpperBound(0)
Ips.Add(ipAddr(i).ToString)
Next
Dim AddressIP As String
return Ips(1).ToString()
Catch ex As Exception
return “Can’t resolve the IP address”
End Try
end function


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Age calculation function in vb.net

I know this is a really simple task but i needed it in a project and i found a working function on www.freevbcode.com so i decided to publish it here too :)

Public Function GetAge(ByVal Birthdate As System.DateTime, _
Optional ByVal AsOf As System.DateTime = #1/1/1700#) _
As String

‘Don’t set second parameter if you want Age as of today

‘Demo 1: get age of person born 2/11/1954
‘Dim objDate As New System.DateTime(1954, 2, 11)
‘Debug.WriteLine(GetAge(objDate))

‘Demo 1: get same person’s age 10 years from now
‘Dim objDate As New System.DateTime(1954, 2, 11)
‘Dim objdate2 As System.DateTime
‘objdate2 = Now.AddYears(10)
‘Debug.WriteLine(GetAge(objDate, objdate2))

Dim iMonths As Integer
Dim iYears As Integer
Dim dYears As Decimal
Dim lDayOfBirth As Long
Dim lAsOf As Long
Dim iBirthMonth As Integer
Dim iAsOFMonth As Integer

If AsOf = “#1/1/1700#” Then
AsOf = DateTime.Now
End If
lDayOfBirth = DatePart(DateInterval.Day, Birthdate)
lAsOf = DatePart(DateInterval.Day, AsOf)

iBirthMonth = DatePart(DateInterval.Month, Birthdate)
iAsOFMonth = DatePart(DateInterval.Month, AsOf)

iMonths = DateDiff(DateInterval.Month, Birthdate, AsOf)

dYears = iMonths / 12

iYears = Math.Floor(dYears)

If iBirthMonth = iAsOFMonth Then
If lAsOf < lDayOfBirth Then
iYears = iYears - 1
End If
End If

Return iYears
End Function

As you can see it’s really simple, just cut & paste in your project, it works fine and you don’t loose 10 minutes of work :)


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Persistent objects in .Net

This year my enterprise is growing very fast and a lot of new software requests are coming every month. Unfortunately we couldn’t get new employees, we’re a small company, so we looked around for something that could speed up the development process. This month i found a very interesting .net library, DevExpress XPO.
This library is something fantastic, with it you can have a total abstraction from the database layer of your applications so you don’t have to write a single row of code to add, modify, delete records from databases!

The only thing to do is a good Object Orientet Programming analysis for your application but i thing that everyone using .Net is familiar with it :)

All you have to do is:

  • Provide the connection string to a database (if you don’t provide it XPO will create an ACCESS .MDB database as default)
  • Design your classes inheriting from XPObject class
  • Call the Save, Delete method of your new class to store or delete data, it’s done!!!
  • Querying is really simple, i’ll show you later

An example:

public class User _
inherits XPObject

public Name as string
public Surname as string
public Phone as string
end class

In your program you just have to:

dim newUser as new User
newUser.Name=”John”
newUser.Surname=”Smith”
newUser.Save()

DONE!

Querying records:

If we want the full Users list we just need to do this:

dim Users as new XPCollection(Of User)

for each usr as User in Users
MessageBox.Show(usr.Name + ” ” + usr.Surname)
next

If you want to delete the 4th user you can just call Users(3).Delete() and it’s done (index starts from ZERO)

More complex queryes can be done using a Criteria, it’s long to explain you can find complete infos on www.devexpress.com

Personal experience
I bought Devexpress XPO last week so i have to be considered a newbie but it’s so easy that i finished a complete software in four days. My customer paid me so i can say i made a great choice, i spent 180$ and i earned 3500$ in few days. Without XPO my project progress would have been about 20%.

Great choice, i suggest it to everyone that needs TIME! Consider that you’ll be able to deliver 3 projects in the time you needed to deliver just 1.

Last consideration
Last but not less important thing i forgot is that if you use XPO you can change the database platform without writing a single row of code. XPO creates databases, tables, records everything database related!!!

Supported DB Engines

  • SQL Server
  • Access
  • MySQL
  • Oracle
  • PostgreSQL
  • Firebird
  • PervasiveSQL
  • VistaDB
  • SQL Anywhere
  • Advantage
  • DB2
  • Sybase

In each moment you can decide to make a different DB Engine version of your software just changing the connection string, no other rows of code needs to be touched!!!


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net