Monday, April 23, 2012

Monday, April 9, 2012

Load Images From Database To The Web Page Without Saving In File System Using New Image Generator control in ASP.Net 3.5

Introduction

Storing images in database BLOB field and displaying it on aspx page is one of the common tasks we do in asp.net projects. Asp.Net itself does not have an in build control to bind the image stored in database. To display an image stored in database, we will write an HttpHandler which will fetch the image from database and do a binary write. We all know that doing a binary write will become cumbersome when the number of images increases and the number of users becomes high. This week Microsoft have released a new control called ASP.NET Generated Image control to display image in ASP.Net page. This article will give you a kick start on this control and some of its features.

Pre-Requisites

Ø Download the control (Microsoft.Web.GeneratedImage.dll) from here.

Ø It Requires Visual Studio 2008 and .NetFramework 3.5 Sp1 to work. You can download .NetFramework 3.5 Sp1 it here.

GeneratedImage control in ASP.Net 3.5

This control can be used to display image faster, we can cache the generated image and we can do transformation on the generated image. To display the image, this control uses an Image HttpHandler which can accept parameters using NameValueCollection object. This Image HttpHandler is similar to normal HttpHandler which inherits an abstract class called ImageHandler. This ImageHandler abstract class internally inherits IHttpHandler.

public class ImageHandler1 : ImageHandler {

public ImageHandler1() {

// Set caching settings and add image transformations here

}

public override ImageInfo GenerateImage(NameValueCollection parameters) {

return new ImageInfo();

}

}

The implementation is really simple. Read the image from database as a byte array and convert the byte array to Microsoft.Web.ImageInfo object for the image to display. This object will come as a part of the control dll we are downloading. ImageInfo object has 2 overloaded constructors, one will take Image object and the other will take a byte array as an argument. We can pass the parameters to this handler by a collection called Parameters in GeneratedImage control. With this information, we will see how we can use this control to display images.

Using GeneratedImage control

Once you have downloaded the control, you can add it to the toolbox of Visual Studio 2008 by right clicking and selecting “Choose Items” option on the toolbar.

Displaying Image from Database

1. Drag a GeneratedImage control from the toolbox. This will add a new GeneratedImage control and @Register directive in the aspx page to register the control.

2. To add an HttpHandler, you can either click “Create Image Handler” option we get when we click the smart tag or by adding a generic handler through “Add New Items” option we get when we right click the visual studio solution.

In GenerateImage() method, read the image from database and pass the image byte array to the ImageInfo constructor.

Refer the below code.

public class ImageFromDB : ImageHandler {

public ImageFromDB() {

// Set caching settings and add image transformations here

}

public override ImageInfo GenerateImage(NameValueCollection parameters) {

// Add image generation logic here and return an instance of ImageInfo

string imageid = parameters["ImID"].ToString();

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

connection.Open();

SqlCommand command = new SqlCommand("select Image from Image where ImageID=" + imageid, connection);

SqlDataReader dr = command.ExecuteReader();

dr.Read();

return new ImageInfo((Byte[])dr[0]);

}

}

The parameter “ImID” in the above code can be passed from the Parameters collection of the control from the aspx page.

For More Information Visit here.

Monday, February 28, 2011

Disable Logging i shrepoint 2007

http://blogs.msdn.com/b/fooshen/archive/2007/01/31/throttling-moss-2007-logs.aspx

Wednesday, August 25, 2010

How to use Jquery in Update panels

I you have this Jquery method to be used

$(function () {

// initialize scrollable
$(".scrollable").scrollable();

});

Then use it inside a function as shown

function BindEvents() {

$(function () {

// initialize scrollable
$(".scrollable").scrollable();

});
}

Then add this script inside the update panel as shown below


<asp:UpdatePanel ID="UpdatePanel9" runat="server">
<ContentTemplate>

<script type="text/javascript">
Sys.Application.add_load(BindEvents);
</script>

//Ur Code Here

</ContentTemplate>
</asp:UpdatePanel>

Sunday, July 25, 2010

Project cannot be opened because its project type (.csproj) is not supported by this version of the application.

To open this project, please use a version that supports this type of project.

Follow the below steps to resolve the above error.
Click Start> All Programs > Visual Studio 2008 > Visual Studio Tools > Click Visual Studio 2008 Command Prompt. Type the below command and press enter.
"devenv.exe /resetskippkgs"
Executing this command should solve your problem.

Thursday, July 22, 2010

How to zip & extract files

 You can use this ZipManager class for zipping files & unzipping.


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace WebApplication1.Compress
{
    public class ZipManager
    {
        private static void ZipFiles(string inputFolderPath, string outputPathAndFile, string password)
        {
            ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
            int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
            // find number of chars to remove     // from orginal file path
            TrimLength += 1; //remove '\'
            FileStream ostream;
            byte[] obuffer;
            string outPath = inputFolderPath + @"\" + outputPathAndFile;
            ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
            if (password != null && password != String.Empty)
                oZipStream.Password = password;
            oZipStream.SetLevel(9); // maximum compression
            ZipEntry oZipEntry;
            foreach (string Fil in ar) // for each file, generate a zipentry
            {
                oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
                oZipStream.PutNextEntry(oZipEntry);

                if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
                {
                    ostream = File.OpenRead(Fil);
                    obuffer = new byte[ostream.Length];
                    ostream.Read(obuffer, 0, obuffer.Length);
                    oZipStream.Write(obuffer, 0, obuffer.Length);
                }
            }
            oZipStream.Finish();
            oZipStream.Close();
        }//code for zipping files


        private static ArrayList GenerateFileList(string Dir)
        {
            ArrayList fils = new ArrayList();
            bool Empty = true;
            foreach (string file in Directory.GetFiles(Dir)) // add each file in directory
            {
                fils.Add(file);
                Empty = false;
            }

            if (Empty)
            {
                if (Directory.GetDirectories(Dir).Length == 0)
                // if directory is completely empty, add it
                {
                    fils.Add(Dir + @"/");
                }
            }

            foreach (string dirs in Directory.GetDirectories(Dir)) // recursive
            {
                foreach (object obj in GenerateFileList(dirs))
                {
                    fils.Add(obj);
                }
            }
            return fils; // return file list
        }//to get folder files

        private void UnZipFiles(Stream stream, string outputFolder)
        {
            //ZipInputStream s = new ZipInputStream(File.OpenRead(zipPathAndFile));
            ZipInputStream s = new ZipInputStream(stream);

            ZipEntry theEntry;
            string tmpEntry = String.Empty;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = outputFolder;
                string fileName = Path.GetFileName(theEntry.Name);
                // create directory
                if (directoryName != "")
                {
                    Directory.CreateDirectory(directoryName);
                }
                if (fileName != String.Empty)
                {
                    if (theEntry.Name.IndexOf(".ini") < 0)
                    {
                        string fullPath = directoryName + "\\" + theEntry.Name;
                        fullPath = fullPath.Replace("\\ ", "\\");
                        string fullDirPath = Path.GetDirectoryName(fullPath);
                        if (!Directory.Exists(fullDirPath)) Directory.CreateDirectory(fullDirPath);
                        FileStream streamWriter = File.Create(fullPath);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        streamWriter.Close();
                    }
                }
            }
            s.Close();
        }

        public static void ZipFiles(string inputFolderPath, string outputFolderPath,string filenameWithExtension, string password)
        {
            if (Directory.Exists(outputFolderPath))//if folder exists delete and recreate it
            {
                DirectoryInfo ifo = new DirectoryInfo(outputFolderPath);
                ifo.Delete(true);
            }

            Directory.CreateDirectory(outputFolderPath);// create folder for lecturer
            ZipFiles(outputFolderPath, filenameWithExtension, password);//zip the crearted folder
        }

        public static void UnZipFiles(string zipPathAndFile, string outputFolder, string password, bool deleteZipFile)
        {
            ZipInputStream s = new ZipInputStream(File.OpenRead(zipPathAndFile));
            if (password != null && password != String.Empty)
                s.Password = password;
            ZipEntry theEntry;
            string tmpEntry = String.Empty;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = outputFolder;
                string fileName = Path.GetFileName(theEntry.Name);
                // create directory
                if (directoryName != "")
                {
                    Directory.CreateDirectory(directoryName);
                }
                if (fileName != String.Empty)
                {
                    if (theEntry.Name.IndexOf(".ini") < 0)
                    {
                        string fullPath = directoryName + "\\" + theEntry.Name;
                        fullPath = fullPath.Replace("\\ ", "\\");
                        string fullDirPath = Path.GetDirectoryName(fullPath);
                        if (!Directory.Exists(fullDirPath)) Directory.CreateDirectory(fullDirPath);
                        FileStream streamWriter = File.Create(fullPath);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        streamWriter.Close();
                    }
                }
            }
            s.Close();
            if (deleteZipFile)
                File.Delete(zipPathAndFile);
        }

       
    }
}


For Zipping you can call as shown below.
 Compress.ZipManager.ZipFiles("D:/TestFiles/", "D:/TestBackup/", "Backup1.zip", "");

For unzipping
/*unzipping files*/
Compress.ZipManager.UnZipFiles("D:/TestBackup/Control_demo.zip", "D:/TestBackup/", "sahan", false);

You have to download
ICSharpCode.SharpZipLib

How to uplaod a file to a ftp server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net;

namespace WebApplication1.FTP
{
    public class FTPManager
    {
        public string FtpFilePath { get; set; }
        public string FtpInputFilePath { get; set; }
        public string FtpHost { get; set; }
        public string FtpUserName { get; set; }
        public string FtpPAssword { get; set; }

        public void UploadFile(FTPManager fm)
        {
            //try
            //{
            //string ftphost = "203.143.11.98";
            //here correct hostname or IP of the ftp server to be given 

            string ftpfullpath = "ftp://" + fm.FtpHost + fm.FtpFilePath;
            FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
            ftp.Credentials = new NetworkCredential(fm.FtpUserName, fm.FtpPAssword);
            //userid and password for the ftp server to given 

            ftp.KeepAlive = true;
            ftp.UseBinary = true;
            ftp.Method = WebRequestMethods.Ftp.UploadFile;


            FileStream fs = File.OpenRead(fm.FtpInputFilePath);

            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;



            try
            {
                // Stream to which the file to be upload is written
                Stream strm = ftp.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload
                    // Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();


            }
            catch
            {
                throw new WebException();
            }
        }

        public void UploadFile(FTPManager fm,byte[] buffer)
        {
            try
            {
                //string ftphost = "203.143.11.98";
                //here correct hostname or IP of the ftp server to be given 

                string ftpfullpath = "ftp://" + fm.FtpHost + fm.FtpFilePath;
                FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
                ftp.Credentials = new NetworkCredential(fm.FtpUserName, fm.FtpPAssword);
                //userid and password for the ftp server to given 

                ftp.KeepAlive = true;
                ftp.UseBinary = true;
                ftp.Method = WebRequestMethods.Ftp.UploadFile;
                //FileStream fs = File.OpenRead(fm.FtpInputFilePath);
                //byte[] buffer = new byte[fs.Length];
                //fs.Read(buffer, 0, buffer.Length);
                //fs.Close();
                Stream ftpstream = ftp.GetRequestStream();
                ftpstream.Write(buffer, 0, buffer.Length);
                ftpstream.Close();
            }
            catch
            {
                throw new InvalidDataException();
            }
        }
    }
}


This is the way to use this class

 FTP.FTPManager fm = new FTP.FTPManager();
            fm.FtpUserName = "com";
            fm.FtpPAssword = "Com123$";
            fm.FtpInputFilePath = @"D:/from desktop 2010-06-08.zip";
            fm.FtpFilePath = @"/TestFtp/from desktop 2010-06-08.zip";
            fm.FtpHost = "203.143.11.98";

            if (FileUpload1.HasFile)
            {
                fm.FtpFilePath = @"/TestFtp/"+FileUpload1.PostedFile.FileName;
                fm.UploadFile(fm, FileUpload1.FileBytes);             
            }
            else
                fm.UploadFile(fm);