Bug Fix: Closing DB Connections After Use

Last post 08-10-2005 10:17 PM by ersheido. 22 replies.

Sort Posts:

  • Bug Fix: Closing DB Connections After Use

    04-21-2005, 5:15 AM
    • Participant
      1,412 point Participant
    • Jeff.aspx
    • Member since 09-12-2003, 2:16 AM
    • Redmond, WA
    • Posts 253
    • AspNetTeam
      Moderator

    If you are seeing your Personal Web Site hit the connection pool limit on your server, it is because there is a bug in the code where it doesn't close connections after it opens them.  The fix is easy:

    1. In the PhotoManager class, mark the class as IDisposable
    2. Add a Dispose() method to call connection.Close().

    We will be updating the kit soon to capture this fix and a few others, but I just wanted to give everyone a heads up just in case.

    Jeff King
    Program Manager
    ASP.net
  • Re: Bug Fix: Closing DB Connections After Use

    04-24-2005, 9:06 PM
    • Participant
      1,236 point Participant
    • Rafa
    • Member since 04-22-2005, 3:52 PM
    • Ladera Ranch, CA
    • Posts 250
    Ok, I know I am such a rookie, but how do I do that? Just learning programming and your kit has been such a great learning experience! Thanks
    http://incendy.spaces.live.com
  • Re: Bug Fix: Closing DB Connections After Use

    04-25-2005, 5:19 AM
    • Participant
      1,412 point Participant
    • Jeff.aspx
    • Member since 09-12-2003, 2:16 AM
    • Redmond, WA
    • Posts 253
    • AspNetTeam
      Moderator

    No problem, here's the code:

    C#

    public class PhotoManager : IDisposable {
       ...
       public void Dispose() {
          connection.Close();
       }
       ...
    }

    VB


    Public Class PhotoManager
       Implements IDisposable
       ...
       Overridable Sub Dispose() Implements System.IDisposable.Dispose
          connection.Close()
       End Sub
       ...

    J#

    public class PhotoManager implements IDisposable {
       ...
       public void Dispose() {
          connection.Close();
       }
       ...

    Jeff King
    Program Manager
    ASP.net
  • Re: Bug Fix: Closing DB Connections After Use

    04-25-2005, 10:36 AM
    • Participant
      1,236 point Participant
    • Rafa
    • Member since 04-22-2005, 3:52 PM
    • Ladera Ranch, CA
    • Posts 250
    Thank you!
    http://incendy.spaces.live.com
  • Re: Bug Fix: Closing DB Connections After Use

    05-07-2005, 8:59 AM
    • Member
      110 point Member
    • quiquito
    • Member since 04-26-2005, 12:30 AM
    • Posts 22
    I implemented the bug fix but it still not closing the connections after being used.  I hit the pool limit this morning and decided to check whats going on.  Well,  everytime I open the website it leaves the connection open.  Im sure I implemented the Disposable funtion correctly.
  • Re: Bug Fix: Closing DB Connections After Use

    05-07-2005, 3:35 PM
    • Participant
      1,412 point Participant
    • Jeff.aspx
    • Member since 09-12-2003, 2:16 AM
    • Redmond, WA
    • Posts 253
    • AspNetTeam
      Moderator
    Can you verify that that line of code is being run?  You can find this out by putting a breakpoint on it and running the site in debug mode via F5 in Visual Web Developer.  Thanks.
    Jeff King
    Program Manager
    ASP.net
  • Re: Bug Fix: Closing DB Connections After Use

    05-07-2005, 6:25 PM
    • Member
      20 point Member
    • sjmac
    • Member since 05-02-2005, 5:20 PM
    • Posts 4
    Jeff,

    Is that code right? I just used "Find all references" (in Visual Express) for the PhotoManager class, and none of the uses of PhotoManager look like they will call Dispose. (That is, none of them explicitely call it, and none of them are in a "using" block.) Has IDispose changed in .Net 2?

    Did you mean that we should add a finalizer ?
    ~PhotoManager() { connection.Close(); } //C#

    Finally, probably because you are just trying to put in a quick fix, your Dispose example code is a lot simpler than the example code in the MSDN doc:
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemidisposableclasstopic.asp

    === update ===

    Clearly I don't understand something, because the dispose methods are being called from somewhere, but apparently not from the .cs code! If I stick the breakpoints on the dispose methods, I do see them being called, but the call stack just says they are being called from "External Code" Confused [*-)]

    Thanks for any insight you can give,
    Steven


  • Re: Bug Fix: Closing DB Connections After Use

    05-08-2005, 9:34 AM
    • Member
      110 point Member
    • quiquito
    • Member since 04-26-2005, 12:30 AM
    • Posts 22
    I decided to implement my own fix to the bug.  There was something fishy with that fix.  Do I decided to hard code open and close connections everytime a SQL query was about to take place.  I know that is redundant but It worked for me.
  • Re: Bug Fix: Closing DB Connections After Use

    05-10-2005, 7:45 AM
    • Member
      57 point Member
    • web-crossing
    • Member since 07-18-2002, 5:29 AM
    • Posts 12

    This Dispose-Fix didn't work for me either. In my opinion it's better anyway to enclose each method with it's own connection open/close code, e.g.:

    using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
    {
       ...
    }

    Otherwise you have to rely on the calling code to invoke your Dispose method. "Open late, close early" is the motto here, and programming defensively is always a good idea.

  • Re: Bug Fix: Closing DB Connections After Use

    05-24-2005, 3:57 PM

    Hello everyone!

     

    First I would like to say that the Personal Web starter kit is just great. An app worth take a look at if you want to explore some of the new features in ASP.NET 2.0.

    First of all I would like to mention that there is used a specific design pattern throughout the .NET framework for implementing the IDisposable interface. I recommend that you use this when implementing the interface in the PhotoManager class. You find more information in the documentation http://msdn2.microsoft.com/library/fs2xkftw(en-us,vs.80).aspx .
     

    I also noticed that the GetAlbums method in the PhotoManager class didn’t called Close on the SqlDataReader object. I believe it’s good practice to so referring to the documentation for SqlDataReader ( http://msdn2.microsoft.com/library/w3dswsb6(en-us,vs.80).aspx ). Notice the remark section.


    When reading your posts I tried to reconstruct the connection pool error my self. I didn’t manage to reconstruct the error in the web application, probably because I didn’t test enoughJ. Instead I created a test project and wrote a unit test for the PhotoManager class.

    The test was pretty easy actually. I instantiated a generic list and tried to add 101 PhotoManager objects to the list. I knew that the limit in the Sql Server connection pool where 100 connections.  This way I did manage to reconstruct the error message you got. 
     

    [TestMethod]

    public void PhotoManagerTest()

    {

        List<PhotoManager> managers = new List<PhotoManager>();

        for (int i = 0; i < 101; i++)

        {

            PhotoManager photoManager = new PhotoManager();

            managers.Add(photoManager);

        }

    }


    While running and tweaking the unit test I discovered that if I sat the variable photoManager = null in the test, I didn’t manage to get the connection pool error. Probably because the garbage collector kicked inn so fast and cleared the objects from the heap. Quite nifty how fast the GC discovered “unused” objects. This is probably why I didn’t get the error message testing the web app.
     

    This caused me to test some more in the web app. I discovered when loading the Photos.aspx page the Dispose method in the PhotoManager class was called. Probably after the ObjectDataSource object had called the GetPhotos( int ) on the PhotoManager object, ObjectDataSource used reflection to call the Dispose method on the object to free resources. This is what I expected the ObjectDataSource controller to do.

     
    But there was another thing that happened that I didn't understand. When I loaded Photos.aspx and sat a breakpoint in the constructor (in the PhotoManager class) I noticed that the constructor was called first once (after the page was loaded, as expected) and for every bound item in the DataList. If I had 3 items in the DataList (3 pictures) the constructor was called 1 (after load) + 3 times. Then I added 5 more pictures to the album and got the same result: 1 (after load) + 8 times.

     
    My implementation of the IDisposable interface on the PhotoManager class:

     

    protected virtual void Dispose(bool disposing)

    {

        if (!disposed)

        {

            if (disposing)

            {

                //Release all managed and unmanaged resourced

                //Dispose() is called

                connection.Dispose();

            }

            //Release unmanaged resources

        }

    }

     

    public void Dispose()

    {

        Dispose(true);

        //Take your self of the finalization queue

        //Finalizer ~PhotoManager will not be called by

        //the GC

        GC.SuppressFinalize(this);

    }

     

    ~PhotoManager()

    {

        Dispose(false);

    }

     

  • Confused [8-)] Re: Bug Fix: Closing DB Connections After Use

    06-06-2005, 3:52 PM
    • Member
      55 point Member
    • devantev2005
    • Member since 12-01-2004, 5:02 PM
    • Posts 11
    Hi,

    I have been reading all the posts here carefully and being the rookie that I am, I am having a difficult time trying to resolve the "Timeout expired ...max pool size was reached" error.

    I have taken the examples from this message thread and implemented them into my photomanager.cs file but I'm still experiencing the same problem.

    I have the following in my photomanager.cs file:

    using System;

    using System.Collections;

    using System.Collections.Generic;

    using System.Configuration;

    using System.Data;

    using System.Data.SqlClient;

    using System.Drawing;

    using System.Drawing.Drawing2D;

    using System.Drawing.Imaging;

    using System.IO;

    using System.Web;

    public class PhotoManager : IDisposable {

    private SqlConnection connection;

    private SqlCommand command;

    private bool filter;

    public void Dispose() {

    connection.Close();

    }

    public PhotoManager() {

    connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString);

    command = new SqlCommand();

    command.Connection = connection;

    command.CommandType = CommandType.StoredProcedure;

    connection.Open();

    filter = true;

    if (HttpContext.Current.User.IsInRole("Friends") || HttpContext.Current.User.IsInRole("Administrators")) {

    filter = false;

    }

    }

    // Photo-Related Methods

    public Stream GetPhoto(int photoid, PhotoSize size) {

    command.CommandText = "GetPhoto";

    command.Parameters.Add(new SqlParameter("@PhotoID", photoid));

    command.Parameters.Add(new SqlParameter("@Size", (int) size));

    command.Parameters.Add(new SqlParameter("@IsPublic", filter));

    object result = command.ExecuteScalar();

    try {

    return new MemoryStream((byte[])result);

    } catch (ArgumentNullException e) {

    return null;

    }

    }

    public Stream GetPhoto(PhotoSize size) {

    string path = HttpContext.Current.Server.MapPath("~/Images/");

    switch (size) {

    case PhotoSize.Small:

    path += "placeholder-100.jpg";

    break;

    case PhotoSize.Medium:

    path += "placeholder-200.jpg";

    break;

    case PhotoSize.Large:

    path += "placeholder-600.jpg";

    break;

    default:

    path += "placeholder-600.jpg";

    break;

    }

    return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);

    }

    public Stream GetFirstPhoto(int albumid, PhotoSize size) {

    command.CommandText = "GetFirstPhoto";

    command.Parameters.Add(new SqlParameter("@AlbumID", albumid));

    command.Parameters.Add(new SqlParameter("@Size", (int)size));

    command.Parameters.Add(new SqlParameter("@IsPublic", filter));

    object result = command.ExecuteScalar();

    try {

    return new MemoryStream((byte[])result);

    } catch (ArgumentNullException e) {

    return null;

    }

    }

    public List<Photo> GetPhotos(int AlbumID) {

    command.CommandText = "GetPhotos";

    command.Parameters.Add(new SqlParameter("@AlbumID", AlbumID));

    command.Parameters.Add(new SqlParameter("@IsPublic", filter));

    SqlDataReader reader = command.ExecuteReader();

    List<Photo> list = new List<Photo>();

    while (reader.Read()) {

    Photo temp = new Photo(

    (int)reader["PhotoID"],

    (int)reader["AlbumID"],

    (string)reader["Caption"]);

    list.Add(temp);

    }

    return list;

    }

    public List<Photo> GetPhotos() {

    return GetPhotos(GetRandomAlbumID());

    }

    public void AddPhoto(int AlbumID, string Caption, byte[] BytesOriginal) {

    command.CommandText = "AddPhoto";

    command.Parameters.Add(new SqlParameter("@AlbumID", AlbumID));

    command.Parameters.Add(new SqlParameter("@Caption", Caption));

    command.Parameters.Add(new SqlParameter("@BytesOriginal", BytesOriginal));

    command.Parameters.Add(new SqlParameter("@BytesFull", ResizeImageFile(BytesOriginal, 400)));

    command.Parameters.Add(new SqlParameter("@BytesPoster", ResizeImageFile(BytesOriginal, 198)));

    command.Parameters.Add(new SqlParameter("@BytesThumb", ResizeImageFile(BytesOriginal, 100)));

    command.ExecuteNonQuery();

    }

    public void RemovePhoto(int original_PhotoID) {

    command.CommandText = "RemovePhoto";

    command.Parameters.Add(new SqlParameter("@PhotoID", original_PhotoID));

    command.ExecuteNonQuery();

    }

    public void EditPhoto(string Caption, int original_PhotoID) {

    command.CommandText = "EditPhoto";

    command.Parameters.Add(new SqlParameter("@Caption", Caption));

    command.Parameters.Add(new SqlParameter("@original_PhotoID", original_PhotoID));

    command.ExecuteNonQuery();

    }

    // Album-Related Methods

    public List<Album> GetAlbums() {

    command.CommandText = "GetAlbums";

    command.Parameters.Add(new SqlParameter("@IsPublic", filter));

    SqlDataReader reader = command.ExecuteReader();

    List<Album> list = new List<Album>();

    while (reader.Read()) {

    Album temp = new Album(

    (int)reader["AlbumID"],

    (int)reader["NumberOfPhotos"],

    (string)reader["Caption"],

    (bool)reader["IsPublic"]);

    list.Add(temp);

    }

    return list;

    }

    public void AddAlbum(string Caption, bool IsPublic) {

    command.CommandText = "AddAlbum";

    command.Parameters.Add(new SqlParameter("@Caption", Caption));

    command.Parameters.Add(new SqlParameter("@IsPublic", IsPublic));

    command.ExecuteNonQuery();

    }

    public void RemoveAlbum(int original_AlbumID) {

    command.CommandText = "RemoveAlbum";

    command.Parameters.Add(new SqlParameter("@original_AlbumID", original_AlbumID));

    command.ExecuteNonQuery();

    }

    public void EditAlbum(string Caption, bool IsPublic, int original_AlbumID) {

    command.CommandText = "EditAlbum";

    command.Parameters.Add(new SqlParameter("@Caption", Caption));

    command.Parameters.Add(new SqlParameter("@IsPublic", IsPublic));

    command.Parameters.Add(new SqlParameter("@original_AlbumID", original_AlbumID));

    command.ExecuteNonQuery();

    }

    public int GetRandomAlbumID() {

    command.CommandText = "GetNonEmptyAlbums";

    SqlDataReader reader = command.ExecuteReader();

    List<Album> list = new List<Album>();

    while (reader.Read()) {

    Album temp = new Album((int)reader["AlbumID"], 0, "", false);

    list.Add(temp);

    }

    reader.Close();

    try

    {

    Random r = new Random();

    return list[r.Next(list.Count)].AlbumID;

    }

    catch (ArgumentOutOfRangeException e)

    {

    return -1;

    }

    }

    // Auxiliary Functions

    private byte[] ResizeImageFile(byte[] imageFile, int targetSize) {

    System.Drawing.Image original = System.Drawing.Image.FromStream(new MemoryStream(imageFile));

    int targetH, targetW;

    if (original.Height > original.Width) {

    targetH = targetSize;

    targetW = (int)(original.Width * ((float)targetSize / (float)original.Height));

    } else {

    targetW = targetSize;

    targetH = (int)(original.Height * ((float)targetSize / (float)original.Width));

    }

    System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(new MemoryStream(imageFile));

    // Create a new blank canvas. The resized image will be drawn on this canvas.

    Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);

    bmPhoto.SetResolution(72, 72);

    Graphics grPhoto = Graphics.FromImage(bmPhoto);

    grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

    grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;

    grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);

    // Save out to memory and then to a file. We dispose of all objects to make sure the files don't stay locked.

    MemoryStream mm = new MemoryStream();

    bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);

    original.Dispose();

    imgPhoto.Dispose();

    bmPhoto.Dispose();

    grPhoto.Dispose();

    return mm.GetBuffer();

    }

    public ICollection ListUploadDirectory() {

    DirectoryInfo d = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/Upload"));

    return d.GetFileSystemInfos("*.jpg");

    }

    }

    What am I doing wrong and is there anyone out there that can help me please?

    Thank you,

    Dev

  • Re: Bug Fix: Closing DB Connections After Use

    06-07-2005, 3:44 AM
    • Member
      57 point Member
    • web-crossing
    • Member since 07-18-2002, 5:29 AM
    • Posts 12

    Here's my version of the code that works. What I've done is to remove the DB Open from the constructor and let each DB-related method open and close it's own connection:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Web;

    public class PhotoManager
    {
      private bool filter;

      public PhotoManager()
      {
        filter = true;
        if ( HttpContext.Current.User.IsInRole( "Friends" ) || HttpContext.Current.User.IsInRole( "Administrators" ) )
        {
          filter = false;
        }
      }

      // Photo-Related Methods

      public Stream GetPhoto( int photoid, PhotoSize size )
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "GetPhoto";
          command.Parameters.Add( new SqlParameter( "@PhotoID", photoid ) );
          command.Parameters.Add( new SqlParameter( "@Size", ( int )size ) );
          command.Parameters.Add( new SqlParameter( "@IsPublic", filter ) );
          object result = command.ExecuteScalar();
          try
          {
            return new MemoryStream( ( byte[] )result );
          }
          catch ( ArgumentNullException e )
          {
            return null;
          }
        }
      }

      public Stream GetPhoto( PhotoSize size )
      {
        string path = HttpContext.Current.Server.MapPath( "~/Images/" );
        switch ( size )
        {
          case PhotoSize.Small:
            path += "placeholder-100.jpg";
            break;
          case PhotoSize.Medium:
            path += "placeholder-200.jpg";
            break;
          case PhotoSize.Large:
            path += "placeholder-600.jpg";
            break;
          default:
            path += "placeholder-600.jpg";
            break;
        }
        return new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read );
      }

      public Stream GetFirstPhoto( int albumid, PhotoSize size )
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "GetFirstPhoto";
          command.Parameters.Add( new SqlParameter( "@AlbumID", albumid ) );
          command.Parameters.Add( new SqlParameter( "@Size", ( int )size ) );
          command.Parameters.Add( new SqlParameter( "@IsPublic", filter ) );
          object result = command.ExecuteScalar();
          try
          {
            return new MemoryStream( ( byte[] )result );
          }
          catch ( ArgumentNullException e )
          {
            return null;
          }
        }
      }

      public List<Photo> GetPhotos( int AlbumID )
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "GetPhotos";
          command.Parameters.Add( new SqlParameter( "@AlbumID", AlbumID ) );
          command.Parameters.Add( new SqlParameter( "@IsPublic", filter ) );
          SqlDataReader reader = command.ExecuteReader();
          List<Photo> list = new List<Photo>();
          while ( reader.Read() )
          {
            Photo temp = new Photo(
              ( int )reader[ "PhotoID" ],
              ( int )reader[ "AlbumID" ],
              ( string )reader[ "Caption" ] );
            list.Add( temp );
          }
          return list;
        }
      }

      public List<Photo> GetPhotos()
      {
        return GetPhotos( GetRandomAlbumID() );
      }

      public void AddPhoto( int AlbumID, string Caption, byte[] BytesOriginal )
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "AddPhoto";
          command.Parameters.Add( new SqlParameter( "@AlbumID", AlbumID ) );
          command.Parameters.Add( new SqlParameter( "@Caption", Caption ) );
          command.Parameters.Add( new SqlParameter( "@BytesOriginal", BytesOriginal ) );
          command.Parameters.Add( new SqlParameter( "@BytesFull", ResizeImageFile( BytesOriginal, 600 ) ) );
          command.Parameters.Add( new SqlParameter( "@BytesPoster", ResizeImageFile( BytesOriginal, 198 ) ) );
          command.Parameters.Add( new SqlParameter( "@BytesThumb", ResizeImageFile( BytesOriginal, 100 ) ) );
          command.ExecuteNonQuery();
        }
      }

      public void RemovePhoto( int original_PhotoID )
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "RemovePhoto";
          command.Parameters.Add( new SqlParameter( "@PhotoID", original_PhotoID ) );
          command.ExecuteNonQuery();
        }
      }

      public void EditPhoto( string Caption, int original_PhotoID )
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "EditPhoto";
          command.Parameters.Add( new SqlParameter( "@Caption", Caption ) );
          command.Parameters.Add( new SqlParameter( "@original_PhotoID", original_PhotoID ) );
          command.ExecuteNonQuery();
        }
      }

      // Album-Related Methods

      public List<Album> GetAlbums()
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "GetAlbums";
          command.Parameters.Add( new SqlParameter( "@IsPublic", filter ) );
          SqlDataReader reader = command.ExecuteReader();
          List<Album> list = new List<Album>();
          while ( reader.Read() )
          {
            Album temp = new Album(
              ( int )reader[ "AlbumID" ],
              ( int )reader[ "NumberOfPhotos" ],
              ( string )reader[ "Caption" ],
              ( bool )reader[ "IsPublic" ] );
            list.Add( temp );
          }
          return list;
        }
      }

      public void AddAlbum( string Caption, bool IsPublic )
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "AddAlbum";
          command.Parameters.Add( new SqlParameter( "@Caption", Caption ) );
          command.Parameters.Add( new SqlParameter( "@IsPublic", IsPublic ) );
          command.ExecuteNonQuery();
        }
      }

      public void RemoveAlbum( int original_AlbumID )
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "RemoveAlbum";
          command.Parameters.Add( new SqlParameter( "@original_AlbumID", original_AlbumID ) );
          command.ExecuteNonQuery();
        }
      }

      public void EditAlbum( string Caption, bool IsPublic, int original_AlbumID )
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "EditAlbum";
          command.Parameters.Add( new SqlParameter( "@Caption", Caption ) );
          command.Parameters.Add( new SqlParameter( "@IsPublic", IsPublic ) );
          command.Parameters.Add( new SqlParameter( "@original_AlbumID", original_AlbumID ) );
          command.ExecuteNonQuery();
        }
      }

      public int GetRandomAlbumID()
      {
        using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings[ "Personal" ].ConnectionString ) )
        {
          connection.Open();
          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandType = CommandType.StoredProcedure;

          command.CommandText = "GetNonEmptyAlbums";
          SqlDataReader reader = command.ExecuteReader();
          List<Album> list = new List<Album>();
          while ( reader.Read() )
          {
            Album temp = new Album( ( int )reader[ "AlbumID" ], 0, "", false );
            list.Add( temp );
          }
          reader.Close();
          try
          {
            Random r = new Random();
            return list[ r.Next( list.Count ) ].AlbumID;
          }
          catch ( ArgumentOutOfRangeException e )
          {
            return -1;
          }
        }
      }

      // Auxiliary Functions

      private byte[] ResizeImageFile( byte[] imageFile, int targetSize )
      {
        System.Drawing.Image original = System.Drawing.Image.FromStream( new MemoryStream( imageFile ) );
        int targetH, targetW;
        if ( original.Height > original.Width )
        {
          targetH = targetSize;
          targetW = ( int )( original.Width * ( ( float )targetSize / ( float )original.Height ) );
        }
        else
        {
          targetW = targetSize;
          targetH = ( int )( original.Height * ( ( float )targetSize / ( float )original.Width ) );
        }
        System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream( new MemoryStream( imageFile ) );
        // Create a new blank canvas.  The resized image will be drawn on this canvas.
        Bitmap bmPhoto = new Bitmap( targetW, targetH, PixelFormat.Format24bppRgb );
        bmPhoto.SetResolution( 72, 72 );
        Graphics grPhoto = Graphics.FromImage( bmPhoto );
        grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
        grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
        grPhoto.DrawImage( imgPhoto, new Rectangle( 0, 0, targetW, targetH ), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel );
        // Save out to memory and then to a file.  We dispose of all objects to make sure the files don't stay locked.
        MemoryStream mm = new MemoryStream();
        bmPhoto.Save( mm, System.Drawing.Imaging.ImageFormat.Jpeg );
        original.Dispose();
        imgPhoto.Dispose();
        bmPhoto.Dispose();
        grPhoto.Dispose();
        return mm.GetBuffer();
      }

      public ICollection ListUploadDirectory()
      {
        DirectoryInfo d = new DirectoryInfo( System.Web.HttpContext.Current.Server.MapPath( "~/Upload" ) );
        return d.GetFileSystemInfos( "*.jpg" );
      }
    }

  • Re: Bug Fix: Closing DB Connections After Use

    06-07-2005, 9:45 AM
    • Member
      55 point Member
    • devantev2005
    • Member since 12-01-2004, 5:02 PM
    • Posts 11
    Thank you very much I just tried that code and tested it and didnt encounter one error!!. Thank you very much.
    I owe you a beer!

    Dev
  • Re: Bug Fix: Closing DB Connections After Use

    06-14-2005, 10:45 AM
    • Member
      5 point Member
    • newbie27
    • Member since 06-14-2005, 2:40 PM
    • Posts 1

     web-crossing is there a version of this class for vb that you could post? thanks in advance for your help.

  • Re: Bug Fix: Closing DB Connections After Use

    06-14-2005, 10:51 AM
    • Member
      57 point Member
    • web-crossing
    • Member since 07-18-2002, 5:29 AM
    • Posts 12
    Sorry, I'm a C# guy. But it shouldn't be too difficult to translate this to VB.NET.

    Cheers,
    Martin
Page 1 of 2 (23 items) 1 2 Next >