Thursday, August 30, 2012

Using .NET / C# to Save and Retrieve files to/from SQL Server

Hi All,

Welcome again.. I always wanted to use SQL Server as a storage area to save the files using .NET. Below is a simple example using Windows forms and SQL Server express. Do let me know what you think in the comments section.

Step 1 Create the tables in SQL Server

I have created a small file with as few columns as possible:


CREATE TABLE [dbo].[Test_FileTable](
      [ID] [int] IDENTITY(1,1) NOT NULL,
      [Name] [varchar](max) NULL,
      [Data] [varbinary](max) NULL,
      [Size] [int] NULL,
      [Description] [varchar](max) NULL,
PRIMARY KEY CLUSTERED
(
      [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Step 2 Create the windows project with two forms. In my example, I have used three forms. One as a menu, one for uploading files and other for downloading. Here is the settings file:

xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ConnectionString" value="Data Source=LocalHost\SQLExpress;Initial Catalog=SampleDB;Integrated Security=SSPI"/>
    <add key="InsertQuery" value="Insert into Test_FileTable (Name,Size,Data,Description)  values(@strName,@intSize,@binData,@strDescription)"/>
    <add key="SelectQuery" value="Select ID,Name as FileName,Size,Description from Test_FileTable"/>
    <add key="DataQuery" value="Select Data from Test_FileTable where ID=@i_ID"/>
    <add key="FileNameQuery" value="Select Name as FileName from Test_FileTable where ID=@i_ID" />
    <add key="TableName" value="Test_FileTable"/>
    <add key="TempPath" value="D:\Temp\"/>
  </appSettings>
</configuration>



Step 3 :  Do the actual code for saving/retrieving the files.

Saving to DB:

private static void UploadFile(string FilePath, string FileDescription)
{
    SqlConnection oConn ;
    SqlCommand oCmd;
    string ConnectionString,CommandString;
    byte[] BytBuffer;
    try
    {
        if (File.Exists(FilePath))
        {
            ConnectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString();
            CommandString = System.Configuration.ConfigurationManager.AppSettings["InsertQuery"].ToString();
            oConn = new SqlConnection(ConnectionString);
            oConn.Open();
            /* Parameters(@strName,@intSize,@binData,@strDescription)
                *
                */
            oCmd = new SqlCommand(CommandString, oConn);
            oCmd.CommandText = CommandString;
            oCmd.CommandType = System.Data.CommandType.Text;
            oCmd.Parameters.Add("@strName", System.Data.SqlDbType.VarChar );
            oCmd.Parameters.Add("@intSize", System.Data.SqlDbType.Int);
            oCmd.Parameters.Add("@binData", System.Data.SqlDbType.VarBinary);
            oCmd.Parameters.Add("@strDescription", System.Data.SqlDbType.VarChar);
                   

            oCmd.Parameters["@strName"].Value = FilePath.Substring(FilePath.LastIndexOf(@"\")+1);
            BytBuffer = File.ReadAllBytes(FilePath);
            oCmd.Parameters["@intSize"].Value = BytBuffer.Length;
            oCmd.Parameters["@binData"].Value = BytBuffer;
            oCmd.Parameters["@strDescription"].Value = FileDescription;

            oCmd.ExecuteNonQuery();

            MessageBox.Show("File uploaded to DB", "Sucess!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        /*
        * Warning: This code might fail if you attempt to store
 * very large files in to the database.
        * For that, just modify the buffer variable such that it reads a
 * block of approx. few megabytes
        * from the database at once.
        * On Most modern computers, this code should work just fine
        */
        }
    }
    catch (Exception ex)
    {
        System.Console.WriteLine(ex.Message);
    }
}




Retrieving from DB:

private byte[] GetFileFromDB(int id)
{
    byte[] Return = null;
    SqlConnection oConn;
    SqlCommand oCMD;

    DataTable oDT;

    try {

        oConn = new SqlConnection();
        //Get the connection string from DB
        oConn.ConnectionString =
System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString();
        oConn.Open();
        oCMD = new SqlCommand();
        oCMD.Connection = oConn;
        oCMD.CommandType = System.Data.CommandType.Text;
        oCMD.CommandText = System.Configuration.ConfigurationManager.AppSettings["DataQuery"].ToString();//
        oCMD.Parameters.Add(new SqlParameter("@i_ID", id));


        //I have structured this query such that you it will just return the file data
        oDT = new DataTable();
        Return = (byte[]) oCMD.ExecuteScalar();

        /*
        * Warning: This code might fail if you attempt to store
 * very large files in to the database.
        * For that, just modify the buffer variable such that it reads a
 * block of approx. few megabytes
        * from the database at once.
        * On Most modern computers, this code should work just fine
        */
           
    }
    catch (Exception ex)
    {
        System.Console.WriteLine(ex.Message);
    }

    return Return;
}


Screen shots:

Menu Form:

 




Uploading a file:
Downloading a file:




Tuesday, August 28, 2012

C# Code to change the encoding of a text file to the desired encoding

Note: I started writing this blog a few months ago, and forgot to publish this. Anyway, better late than never, enjoy.

This code lets you convert multiple files in a directory to the desired encoding. The reason for this utility is the source control which is being used by my client doesn't support anything other than ASCII (7 bit). This function I have below should be sufficient for the most needs, but I have shared the entire code as well.

Function to change the encoding:


        private static void ChangeEncoding(string FolderPath, string TargetEncoding)
        {
            try
            {
                DirectoryInfo info = new DirectoryInfo(FolderPath);
                FileInfo[] Fi = info.GetFiles();
                StreamWriter swriter;
                StreamReader sreader;
                string FileName;
                foreach (FileInfo obj in Fi)
                {
                    FileName = obj.FullName;
                    File.SetAttributes(FileName, FileAttributes.Normal);
                    File.Move(FileName, FileName + ".proback");
                    sreader = new StreamReader(FileName + ".proback");
                    if (TargetEncoding.Equals("BigEndianUnicode"))
                    {

                        swriter = new
StreamWriter(FileName, false, Encoding.BigEndianUnicode);
                    }
                    else if (TargetEncoding.Equals("Unicode"))
                    {
                        swriter = new StreamWriter(FileName, false, Encoding.Unicode);
                    }
                    else if (TargetEncoding.Equals("UTF32"))
                    {
                        swriter = new StreamWriter(FileName, false, Encoding.UTF32);
                    }
                    else if (TargetEncoding.Equals("UTF7"))
                    {
                        swriter = new StreamWriter(FileName, false, Encoding.UTF7);
                    }
                    else if (TargetEncoding.Equals("UTF8"))
                    {
                        swriter = new StreamWriter(FileName, false, Encoding.UTF8);
                    }
                    else if (TargetEncoding.Equals("ASCII"))
                    {
                        swriter = new StreamWriter(FileName, false, Encoding.ASCII);
                    }
                    else
                    {
                        swriter = new StreamWriter(FileName, false, Encoding.Default);
                    }

                    while (!sreader.EndOfStream)
                    {
                        swriter.WriteLine(sreader.ReadLine());
                    }

                    sreader.Close();
                    swriter.Close();
                    sreader.Dispose();
                    swriter.Dispose();
                    File.Delete(FileName + ".proback");
                   
                }
            }
            catch (Exception ex)
            {
                throw ex;  
            }
        }


 Downloads:  


Note: You need .NET framework 4

Complete Source - https://docs.google.com/open?id=0B1z9Rc2ld5VPSExPSE9sUEh1SkE


(Once the link opens, press Ctrl+S to download)

Monday, August 27, 2012

"Ferb" Latin encoder :) [In .NET/C#]

In the previous post, I had mentioned about the "Pig" latin, which offers some sort of "Perceived" privacy. This morning when I was watching Phineas and Ferb, they invent a new language called "Ferb" latin, so I thought since very less people know about that, we can very well use those rules instead. Here is the program to encode:


public static string GetFerbLatinFromText(string strText)
{
    string strRetVal = string.Empty;
    int i, j;
    try
    {

        StringBuilder sb = new StringBuilder();
        char[] chrLetters;
        string[] strWord = strText.Split(' ', '\n');

        for (i = 0; i < strWord.Length; i++)
        {
            chrLetters = strWord[i].ToCharArray();
            if (chrLetters.Length > 2)
            {

                for (j = 1; j < chrLetters.Length; j++)
                {
                    sb.Append(Char.ToLower(chrLetters[j]));
                }

                sb.Append(Char.ToLower(chrLetters[0]));
                sb.Append("erb ");

            }
            else
            {
                sb.Append(strWord[i]);
                sb.Append(" ");
            }
        }

        strRetVal = sb.ToString();
    }
    catch (Exception exp)
    {
        throw exp;
    }

    return strRetVal;
}


Code to decode the text :

public static string GetTextFromFerbLatin(string strText)
{
    string strRetVal = string.Empty;
    int i, j;
    try
    {
        StringBuilder sb = new StringBuilder();
        char[] chrLetters;
        string[] strWord = strText.Split(' ', '\n');

        for (i = 0; i < strWord.Length; i++)
        {
            chrLetters = strWord[i].ToCharArray();
            if (chrLetters.Length > 2)
            {

                if(chrLetters.Length >4)
                    sb.Append(Char.ToLower(chrLetters[chrLetters.Length - 4]));

                for (j = 0; j < chrLetters.Length-4; j++)
                {
                    sb.Append(Char.ToLower(chrLetters[j]));
                }

                sb.Append(' ');

            }
            else
            {
                sb.Append(strWord[i]);
                sb.Append(" ");
            }
        }

        strRetVal = sb.ToString();
    }
    catch (Exception exp)
    {
        throw exp;
    }

    return strRetVal;
}


Source code for this program can be downloaded from here : Link

Executable can be found here : Link 

.NET (C#) based PigLatin generator

Hi All,

I was watching a tv show this morning about piglatin, so I thought I will write this during my coffee break. Enjoy. This is not a complete implementation, well don't expect too much for a coffee break project. :)


  public static string GetPigLatinFromText(string strText)
        {
            string strRetVal = string.Empty;
            int i,j;
            try
            {
                 
                StringBuilder sb = new StringBuilder();
                char[] chrLetters ;
                string[] strWord = strText.Split(' ', '\n');

                for ( i= 0; i < strWord.Length; i++)
                {
                    chrLetters = strWord[i].ToCharArray();
                    if (chrLetters.Length > 2)
                    {
                        if (chrLetters[0] == 'a' || chrLetters[0] == 'e' || 
                            chrLetters[0] == 'i' || chrLetters[0] == 'o' || 
                            chrLetters[0] == 'u' ||
                            chrLetters[0] == 'A' || chrLetters[0] == 'E' || 
                            chrLetters[0] == 'I' || chrLetters[0] == 'O' || 
                            chrLetters[0] == 'U')
                        {
                            //Starts with a vowel
                            sb.Append(strWord[i]);
                            sb.Append("ay ");


                        }
                        else if (chrLetters[0] == 'g' || chrLetters[0] == 'G')
                        {

                            for (j = 1; j < chrLetters.Length; j++)
                            {
                                sb.Append(Char.ToLower(chrLetters[j]));
                            }

                            sb.Append('g');
                            sb.Append("way ");
                        }
                        else
                        {
                            for (j = 1; j < chrLetters.Length; j++)
                            {
                                sb.Append(Char.ToLower(chrLetters[j]));
                            }

                            sb.Append(Char.ToLower(chrLetters[0]));
                            sb.Append("ay ");

                        }

                    }
                    else
                    {
                        sb.Append(strWord[i]);
                        sb.Append(" ");
                    }
                }

                strRetVal = sb.ToString();
            }
            catch (Exception exp)
            {
                throw exp;
            }

            return strRetVal;
        }