Archive for Web development

Using DevExpress XPO in asp.net websites

For several months i developed applications using the wonderful XPO persistent objects library. This month i had to develop a website for an important customer and, satisfied by the XPO performances, i decided to use it for the website too. I developed the full website the same way i developed applications and everything worked fine but when i published it and users started to navigate the website i had serious troubles. The reason is that using XPO in a desktop application is fine considering that the SESSION is just for one user so the data will be always up to date. Using a single SESSION in a web application is impossible because the session objects will be accessed by multiple threads and the data could change while we’re working on it. When we load a persistent object it will have an unique identifier in the session but what if someone else does something that make change this identifier? It happens that XPO generates an error saying “trying to access a disposed object”.
How we can use XPO in a web application?
The first step is creating a DAL object and store it in Application (the same for all the website’s sessions)
The DAL is the XPO data abstraction layer. We’ll create a specific DAL based on our database structure (it’s automatically done by XPO don’t be scared)
We’ll write this specific code in the Global.asax file.
Global.asax

First of all we need to get the connection string to our database (i used mysql)
Dim conn As String = DevExpress.Xpo.DB .MySqlConnectionProvider.GetConnectionString (DBHost, DBUser, DBPass, DBName)

Second step is to obtain the DataStore Schema
Dim dict As New DevExpress.Xpo.Metadata.ReflectionDictionary()
dict.GetDataStoreSchema(GetType(CommunityUser).Assembly)
‘Here i used the type CommunityUser, it’s an XPObject derived class, you can use one of your own classes, doesn’t matter which one you use, it’s just necessary to obtain the assembly, just use one of your persistent objects ;)

Dim store As DevExpress.Xpo.DB.IDataStore = DevExpress.Xpo. XpoDefault.GetConnectionProvider (conn,  DevExpress.Xpo.DB.AutoCreateOption. SchemaAlreadyExists)

Now that you obtained the DataStore interface you can create the DAL, we’ll call it layer
Dim layer = New DevExpress.Xpo.ThreadSafeDataLayer (dict, store)

Last step, store the layer in an application variable, we need it to create connections in the whole website
Application.Add(”XpoLayer”, layer)

We finished with the Global.asax file, now we just need to do the rest in each aspx page.

‘Use this variable in each web page
Dim theSession As Session

In the Page Load sub create the Session object to access the persistent objects of your website.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        theSession = New Session( DirectCast( Application(”XpoLayer”), DevExpress.Xpo.ThreadSafeDataLayer ))
end sub

Last thing to do in your webpages is to override the sub Render to dispose the theSession Object created in the page load event.

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
        MyBase.Render(writer)
        theSession.Dispose()
End Sub

These steps need to be done in each web page accessing persistent objects.
Remember that you need an extra work too, each of your persistent classes needs the new constructor to accept a session object as parameter, we need it to don’t use the default session object.

Public Sub New(ByVal session As Session)
     MyBase.New(session)
End Sub

I hope i’ve been clear enough and that it could be useful.


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

Asp.Net Panel and Internet Explorer 7

I developed an ecommerce web solution for my customers. I made it using Visual Studio .Net and the 2.0 Framework. When i developed it there wasn’t Internet Explorer 7 yet. It worked fine until Internet Explorer 7 was released. As long as users installed Explorer 7 the website become unutilisable because the new rendering routines clipped the panels to it’s height. With older versions of internet explorer the panel was resized to it’s content so there were no problems but with explorer 7 everything out of the height bounds is clipped. I had to work on each website page using panels. The remedy is very simple, just remove the height property of all the panels used in your website pages. If no height is provided then explorer 7 enlarge them showing all the content inside. It’s just a little question of rendering but i think that a lot of people encountered this panel clipping problem with explorer 7.


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

AJAX in .Net - ATLAS

The most boring thing of websites is the continuos page reloading, it takes a lot of bandwidth and when site users number grows you can experience notable slowdowns. In the past i tried to use Remote Scripting but it was time expensive considering the project delivery time, so i decided to give up. With ATLAS (it’s Microsoft AJAX Library) everything becomes really easy and powerful. First thing i tried was to fill a combobox when i changed the selectedindex of another combobox. The result was really nice, no more full page reloading!!!
Try to thing a situation like Country selection, then City selection. When the country changes you have to fill the Cities combo to let the user choose it. If your website has a lot of graphics it could be very boring using the traditional postback approach.

HOW TO START
Download and install the ATLAS library, you can find it on google, search for “ASPAJAXExtSetup.msi”

NEW CONTROLS IN VISUAL STUDIO
After the installation you can find in Visual Studio.net 2005 a new tab of controls named AJAX EXTENSIONS.
Try to create a new website selecting “ASP.NET AJAX-Enabled website”.

THE NEW ATLAS CONTROLS
In the controls toolbar you can find the new tab AJAX Extensions with the following new controls:

  • Timer
    Very useful functionality to execute temporized tasks
  • ScriptManager
    This is a fundamental ATLAS control, you have to instanciate it in each page you want to have the ATLAS support. If you are using MasterPages you can place it inside the MasterPage so you have no need to put it in each website page.
  • ScriptManagerProxy
    You may have a ScriptManager on your master page, but you may want to add additional script or service references in your content page. However, you can only have one ScriptManager on your page. Therefore we have the accompanying ScriptManagerProxy control.
  • UpdateProgress
    This is useful if you want to show something during the update progress. If you have a button lo fill a datagrid, when you click it the updateprogress content will be shown, then when the datagrid is filled the updateprogress content disappear
  • UpdatePanel
    This is the most important ATLAS control, everything you put inside it will be AJAX enabled. Consider the above example of Country/City, if you put the two comboboxes inside an UpdatePanel you’ll se that the page will not be completely reloaded on the Country postback, you’ll just see the City combobox content changing.

As you can see it’s really simple to add AJAX functionalities to your websites :)
This is just the starting point of the ATLAS programming but it can be useful to know what you can do…

CONSIDERATIONS
AJAX functionalities are really nice but consider that the extensions are in beta release so you may experience bugs.
A known bug is that the FileUpload control doesn’t work if placed inside an UpdatePanel but there will be something else :)


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

High quality thumbnails in VB.Net

When i started .Net programming i appreciated all the new functionalities of the framework, everything was easier and faster to do. I tought the same thing about thumbnails generation when i found the GetThumbnailImage method of the System.Drawing.Bitmap class but giving a deeper look at it’s behaviour i understood it was not so easy.

WHY IT WASN’T SO EASY
The GetThumbnailImage method isn’t so useful because image formats like JPG can store the thumbnail image inside the same file. A lot of graphics softwares store the thumbnail version of the image into the .JPG file and you can’t choose it’s width, height and quality. The GetThumbnailImage method checks if there’s a thumbnail image stored into the file and, if the thumb is found, it returns that thumbnail version scaled to the width and height you requested. If the thumbnail version of the image is smaller then the size you asked for you can imagine what will be the result, a very low quality and pixelated image. If you want to have the full control over the thumbnail quality you have to use something different by the GetThumbnailImage method.

THE APPROACH
What we have to do is to load the JPG file into a System.Drawing.Image object, scale it to the desired width and height preserving a good quality and save it to a new file.

To preserve the image quality we have to follow these few steps:

  • Load the original file into a System.Drawing.Image object
  • Create the target image with the desired size as System.Drawing.Bitmap
  • Create a System.Drawing.Graphics object from the target Bitmap to draw the scaled image
  • Set the System.Drawing.Graphics object property SmoothingMode to HighQuality
  • Set the System.Drawing.Graphics object property CompositingQuality to HighQuality
  • Set the System.Drawing.Graphics object property InterpolationMode to High
  • Draw the original image into the target Graphics object scaling to the desired width and height
  • Get the System.Drawing.Imaging.ImageCodecInfo object of the JPEG file format
  • Set the Codec param System.Drawing.Imaging.Encoder.Quality to the desired quality (for jpg is 0-100)
  • Save the new image using the Codec and the filled quality parameter

THE CODE
I wrote a simple class CImageHelper where i put all the imaging routines, here there’s a simple version with the SaveImage function to save ThumbNails (or scaled versions of any image) with a very high quality.

Click here to download the code


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

Master Pages in VB.Net 2.0

This month i wrote just one article because i was very busy to develop an ecommerce software. I just finished it and i learned new interesting things.

I had to Develop two ecommerce sites for my customer so i preferred to make a really versatile ecommerce solution that could be skinned with templates.

I thought that i had to make something that could cover these aspects:

  • Fully skinnable ecommerce solution so i just need to make html for new customers commerce sites
  • Fully customizable database connections
  • Fully object oriented to make easier to change things
  • Fully customizable email messages
  • Fully customizable payment methods
  • Fully customizable products structure so the customer could sell everything giving the maximum parameters details
  • Unlimited category tree

In the next articles i’ll wrote i’ll cover all the single aspects of this development experience but now i’d like to talk about the more interesting thing i found in asp.net 2.0, the MasterPage architecture.

The main things to understand about MasterPages are these:

  • A MasterPage is a special asp.net 2.0 page (a template page) that can be filled with the HTML Layout of the site so you’ll never need to copy HTML in each site’s page.
  • In a Master Page you can define the content areas using the new ContentPlaceHolder control (it’s just a container where the site “pieces” will be placed).
  • A Master Page acts as a base class for all the site pages you’ll create, so you can write common source code inside it. Ex.: You can check user authentication in the master page if you prefer
  • A website can have all the MasterPages you want and you can load the master page at runtime too. It’s very useful if you plan to use multiple template sites.

Whe you add a new asp.net page to your project, visual studio asks you which master page to use for the new page, you just have to choose one. Consider to make a default template master page and assign it to each page of your site.

Create a simple Asp.net website project and try to add a new MasterPage, fill it with HTML, create ContentPlaceHolders and then add a new WebForm choosing the Master Page. In your new page you’ll see the HTML layout (not editable) and the content placeholders where you can place the page specific content.

A really important thing is the Master Page loading at runtime. I found this functionality really exciting because it solved all my problems.

How to load a master page at runtime

Loading a master page at runtime is really simple, you just have to create the PreInit function for your new pages:

Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Me.MasterPageFile = Application(“Template”) + “.master”
End Sub

As you can see i have the template name into Application, Application(”Template”).

You can change the site template with just one row of code:

Application(”Template”)=”TemplateBlue”

or

Application(”Template”)=”MyNewTemplate”

remember that to have this functionality you’ll need to write two masterpages:
TemplateBlue.master and MyNewTemplate.master

In this article i’ll not write source code, it’s really simple to do this, just try and in 10 minutes you’ll finish it :)


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

Shopping Cart in Asp.Net

Today i needed to add Shopping Cart functionality to one of my websites.
The solution i adopted is really simple, i did it in few minutes but i think it could be useful. It can be improved but it’s a good starting point if u just need a simple shopping cart.

I choosed this way:

  • Create a class named ShoppingCart
  • Create a class named CartItem to store item infos
  • In the Session_Start event of Global.asax i create the ShoppingCart instance and add it to session. I named it Session(”ShoppingCart”)
  • In each page that needs to access the Shopping Cart i use the stored Session(”ShoppingCart”) and use it’s methods

The Shopping Cart Class methods i wrote are:

  • New, to create the empty cart
  • Add, to add a CartItem object
  • Modify, to vary the count of an item or remove it setting it’s count to zero
  • Empty, to empty the Shopping Cart
  • ItemTotal, to get the total price for an object (count * price)
  • Total, to get the Shopping Cart total price to pay

The CartItem class contains these infos:

  • ID
  • Name
  • Price
  • Count

Here is the Code:

Public Class CartItem
    Public ID As String
    Public Name As String
    Public Price As Double
    Public Count As Integer
 
    Public Sub New()
        ID = "-1"
        Name = ""
        Price = 0
        Count = 0
    End Sub
End Class
 
Public Class ShoppingCart
    Public Items As New Hashtable
 
    Public Sub New()
        Items.Clear()
    End Sub
 
    'Add an item to the Shopping Cart
    Public Function Add(ByVal c As CartItem) As Boolean
        Dim tmpItem As CartItem
 
        If c.Name <> "" And c.Count > 0 Then
            tmpItem = Items(c.Name)
            If Not tmpItem Is Nothing Then
                tmpItem.Count += c.Count
            Else
                Items.Add(c.Name, c)
            End If
            Return True
        Else
            Return False
        End If
    End Function
 
    'Modify an object quantity
    'If quantity is zero the item is removed
    Public Function Modify(ByVal c As CartItem) As Boolean
        Dim tmpItem As CartItem
        If c.Name <> "" Then
            tmpItem = Items(c.Name)
            If Not tmpItem Is Nothing Then
                If tmpItem.Count > 0 Then
                    tmpItem.Count = c.Count
                Else
                    Items.Remove(c.Name)
                End If
                Return True
            Else
                Return False
            End If
        Else
            Return False
        End If
    End Function
 
    'Empty the Shopping Cart
    Public Sub Empty()
        Items.Clear()
    End Sub
 
    'calculate an object total price (items*price)
    Public Function ItemTotal(ByVal itemName As String) As Double
        Dim tmpItem As CartItem
        If itemName <> "" Then
            tmpItem = Items(itemName)
            If Not tmpItem Is Nothing Then
                Return tmpItem.Count * tmpItem.Price
            Else
                Return 0.0
            End If
        Else
            Return 0.0
        End If
    End Function
 
    'Calculate the total price to pay
    Public Function Total() As Double
        Dim totale As Double = 0.0
        For Each k As String In Items.Keys
            Dim ci As CartItem = Items(k)
            totale += ci.Price * ci.Count
        Next
        Return totale
    End Function
End Class

Download this code: ShoppingCart.vb.txt

In the Global.asax file you need to write

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Session(”ShoppingCart”) = New ShoppingCart
End Sub

To Add an item to the Shopping Cart

Dim cart As ShoppingCart = Session(”ShoppingCart”)
Dim it As New CartItem
it.Name = “Test Object”
it.ID = “1″
it.Price = 100.22
it.Count = 1
cart.Add(it)

To Show the cart items

Dim cart As ShoppingCart = Session(”ShoppingCart”)
For Each k As String In cart.Items.Keys
Dim ci As CartItem = cart.Items(k)
Response.write(ci.Name + “-” + ci.Count.ToString() + ” Price: ” + ci.Price.ToString + ”
“)
Next
Response.Write(”Total: ” + cart.Total.ToString())


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

Browse images and media files in Asp.Net like in a photo gallery

Two or three years ago i needed a way to show my users the content i published on my web community. Due to hosting problems (i had no database) i needed something to list the files into the directories and show the content. I decided to write a little custom control that permits the users to navigate throug the directories and see the images, videos and ear the audio streams. Due to the high number of files i provided pagination too.

Here is the code i wrote to make this:

Imports System.IO
 
Public Class MediaLister
    Inherits System.Web.UI.UserControl
 
#Region " Codice generato da Progettazione Web Form "
 
<System.Diagnostics.DebuggerStepThrough()>_
Private Sub InitializeComponent()
 
End Sub
Protected WithEvents LitFiles As System.Web.UI.WebControls.Literal
Protected WithEvents LitPages As System.Web.UI.WebControls.Literal
Protected WithEvents LitDirs As System.Web.UI.WebControls.Literal
 
Private designerPlaceholderDeclaration As System.Object
 
Private Sub Page_Init(ByVal sender As System.Object, _
ByVal e As System.EventArgs)  Handles MyBase.Init
InitializeComponent()
End Sub
 
#End Region
Public FirstItem As Boolean = True
 
Private Sub BuildPagers(ByVal ItemsCount As Integer, _
ByVal MaxItems As Integer)
  Dim i As Integer
  Dim pages As Integer
  pages = ItemsCount / MaxItems
  If (pages * MaxItems) < ItemsCount Then
      pages += 1
  End If
  LitPages.Text = "<br><center>"
  For i = 0 To pages - 1
      LitPages.Text += "<a   href=index.aspx?Cat=" + _
      Request("Cat").Replace(" ", "%20") + "&SCat=" + _
      Request("SCat").Replace(" ", "%20") + _
      "&Page=" + i.ToString() + ">" + (i + 1).ToString() + _
      "</a>&nbsp;"
      If (i + 1) Mod 18 = 0 Then
          LitPages.Text += "<br>"
      End If
  Next
 
End Sub
 
Private Sub ShowItem(ByVal Cat As String, ByVal SubCat As String,_
  ByVal fName As String)
   Dim ext As String
   Dim fPath As String
   ext = fName.Substring(fName.LastIndexOf(".") + 1)
   ext = ext.ToLower()
   Select Case ext
       Case "jpg", "bmp", "gif"
           '    LitFiles.Text += _
           "<td><img width=160 src=""pub/Lib/" +_
           Cat + "/" + SubCat + "/" + fName + """ border=0></td>"
           fPath = "pub/Lib/" + Cat + "/" + _
           SubCat + "/" + fName
           If FirstItem Then
               FirstItem = False
               LitFiles.Text += "<IMG id=""Foto"" src=""" + _
               fPath.Replace(" ", "%20") + _
               """ width=500 name=""Foto"">"
           End If
           LitFiles.Text += _
           "<td><a href=# onClick=""ChangeImg('" + _
           fPath.Replace(" ", "%20").Replace("\", "/") + _
           "');""><img src=""ShowThumbnail.aspx?w=80&img=" + _
           fPath + """ border=0></a></td>"
       Case "wav", "mid", "mp3"
           LitFiles.Text += _
           "<td><embed width=160 height=50 src=""pub/Lib/"+_
           Cat + "/" + SubCat + "/" + fName + _
           """ type=audio/mpeg autostart=false loop=true></td>"
       Case "avi", "mpg", "wmv"
           LitFiles.Text += _
           "<td><embed width=160 height=160 src=""pub/Lib/"+_
           Cat + "/" + SubCat + "/" + fName + _
           """  autostart=false loop=false></td>"
   End Select
End Sub
 
Private Sub LoadDirList(ByVal Cat As String, _
  ByVal SubCat As String)
   Dim tmpfile As String
   Dim tmpName As String
   Dim i As Integer
   Dim k As Integer
   Dim MaxCols As Integer = 4
   Dim MaxRows As Integer = 3
   Dim MaxItems = MaxCols * MaxRows
   Dim ItemsCount = 0
   Dim CurCol = 0
   Dim StartIndex As Integer
 
   tmpfile = Server.MapPath("/") + "pub\Lib\" + _
   Cat + "\" + SubCat
   Dim files() As String = Directory.GetDirectories(tmpfile)
   If files.Length > 0 Then
       LitDirs.Text += _
       "<table border=0 cellspacing=5 cellpadding=5><tr>"
       CurCol = 0
       For i = 0 To files.Length - 1
           tmpName = files(i).ToString()
           tmpName = tmpName.Substring(tmpName.LastIndexOf("\")+1)
           tmpName = tmpName.Replace(" ", "%20")
           CurCol += 1
           If CurCol > MaxCols Then
               LitDirs.Text += "</tr><tr>"
               CurCol = 1
           End If
           LitDirs.Text += _
           "<td align=center><a href=""Index.aspx?Cat=" + _
           Cat + "&SCat=" + SubCat + "\" + tmpName + _
           """ ><img src=Folder.gif border=0><br>"+_
           tmpName.Replace("%20", "&nbsp;") + "</a></td>"
       Next
       For i = CurCol To MaxCols
           LitDirs.Text += "<td>&nbsp;</td>"
       Next
       LitDirs.Text += "</tr></table>"
   End If
 
End Sub
 
 
Private Sub LoadFileList(ByVal Cat As String,_
  ByVal SubCat As String,ByVal StartPage As Integer)
  Dim tmpfile As String
  Dim tmpName As String
  Dim i As Integer
  Dim MaxCols As Integer = 6
  Dim MaxRows As Integer = 1
  Dim MaxItems = MaxCols * MaxRows
  Dim ItemsCount = 0
  Dim CurCol = 0
  Dim StartIndex As Integer
  If StartPage = 0 Then
      LoadDirList(Cat, SubCat)
  End If
  tmpfile = Server.MapPath("/") + "pub\Lib\" + Cat + "\" + SubCat
  Dim files() As String = Directory.GetFiles(tmpfile)
  If files.Length > 0 Then
      If SubCat.LastIndexOf("\") > 0 Then
          LitFiles.Text = "<center><font size=4>" + Cat + _
          "</font> (<font size=3>" + _
          SubCat.Substring(SubCat.LastIndexOf("\") + 1) + _
          ")</font><BR></center>"
      Else
          LitFiles.Text = "<center><font size=4>" + Cat + _
          "</font> (<font size=3>" + SubCat + _
          ")</font><BR></center>"
      End If
      BuildPagers(files.Length, MaxItems)
      i = StartPage * MaxItems
      StartIndex = i
      LitFiles.Text += _
      "<table border=0 align=center cellspacing=2 ><tr>"
      CurCol = 0
      While (i < (StartIndex + MaxItems) _
      	And i <= (files.Length() - 1))
          tmpName = files(i).ToString()
          tmpName = tmpName.Substring(tmpName.LastIndexOf("\")+1)
          tmpName = tmpName.Replace(" ", "%20")
          i += 1
          CurCol += 1
          If CurCol > MaxCols Then
              LitFiles.Text += "</tr><tr>"
              CurCol = 1
          End If
          ShowItem(Cat, SubCat, tmpName)
      End While
      For i = CurCol To MaxCols
          LitFiles.Text += "<td>&nbsp;</td>"
      Next
      LitFiles.Text += "</tr></table>"
      LitPages.Text += "<br><br><font  >Sei a Pagina. " + _
      (StartPage + 1).ToString() + "</font><br></center>"
  End If
 
End Sub
 
Private Sub Page_Load(ByVal sender As System.Object, _
   ByVal e As System.EventArgs) Handles MyBase.Load
     FirstItem = True
     If Not Page.IsPostBack Then
         LoadFileList(Request("Cat"), Request("SCat"),_
          Request("Page"))
     End If
End Sub
 
End Class

Download this code: medialister.ascx.vb.txt

A working example of this code is visible at www.ircfiles.com , try to browse and see the content, it’s fast enough considering the really high number of images and other media files :)

Here there is the correctly written version of the code, i had to use a lot of “_” into the code here to make it fit the page.
In the zip file you can find the ShowThumbnail.aspx page too, it’s used to create image thumbs for faster page loading.

Download the Media Lister Source code


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

Using MySQL database in .Net

Last year i had to choose a Database Server for a new application i had to develop for my customer. The options was Access, SQL Server, Oracle. As you can imagine i decided to exclude Access from the list due to it’s slow performances. I had to decide between SQL Server and Oracle but, considering my customer budget, i decided to add to the list another database server, MySQL. I think that MySQL is a very interesting option when u have to save money for your projects, it’s cheap and fast enough to compete with SQL Server and Oracle.
To use a MySQL database you need to download the MyODBC 3.51 or better driver. I use 3.51 because it’s more stable. So to go on with the test please download MyODBC and install it before testing. Obviously you need MySQL and a database too.

Here is the simple code to access a MySQL database from VB.Net using MyODBC.
In this test we’ll connect to a MySQL database and read all the records of a table then we display one field in a web page.
In a desktop application you can use it the same way but remove the Response.write and use something else.

Dim SQL As String
Dim ConnString as string
 
ConnString= "DRIVER={MySQL ODBC 3.51 Driver};_
    SERVER=localhost;DATABASE=DatabaseName;_
    UID=UserID;PWD=thePassword;OPTION=35"

Dim Conn As New System.Data.Odbc.OdbcConnection(_
     _ConnString)
 
SQL = "SELECT * FROM TableName"
Conn.Open()
 
Dim Cmd As New System.Data.Odbc.OdbcCommand(SQL, Conn)
Cmd.CommandTimeout = 20
 
Dim Reader As System.Data.Odbc.OdbcDataReader
Reader = Cmd.ExecuteReader()
 
While (Reader.Read)
        Response.Write(Reader("FieldName") + "<br>")
End While
 
Reader.Close()
Cmd.Dispose()
Conn.Close()
Conn.Dispose()

Download this code: MySQLVB.vb.txt

That’s all :) really simple


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

Download a file from web in .Net

This article is just written to help people with this task if they don’t know how to do. As you will see there’s not so much code to write to do this, it’s just provided by the .Net Framework

All that you have to do is:

  • add a reference to System.Net namespace
  • create a new WebClient object
  • call the WebClient method DownloadFile

it’s done.

Example:

Imports System.Net

public sub DownloadFile(SourceURL as string, DestFile as string)
dim WebC as new WebClient()

WebC.DownloadFile(SourceURL,DestFile)
end sub


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