Archive

Posts Tagged ‘C#’

5 Traps to Avoid in C#

5 Traps to Avoid in C#

Trap #1: Mistaking “var” as Late-bound
Trap #2: Be careful with optional parameters
Trap #3: Deferred Execution in LINQ
Trap #4: Overloading Methods in a base class
Trap #5: Forgetting to unsubscribe from events

Advertisements
Categories: Uncategorized Tags: , ,

ASP.NET MVC2 Basics and Introduction

September 30, 2011 Leave a comment

A very nice video on ASP.NET MVC2 by “Scott Hanselman”, covers the introduction and basics and gives a very clear understanding about this pattern.

Categories: ASP.NET, C# Tags: , , ,

What is the difference between Uri and UriBuilder?

July 12, 2011 5 comments

The answer for this question would be similar to the question below:

What is the difference between String and StringBuilder?

Why? because they are similar in concept. A Uri/String is immutable (read-only, if you will). A UriBuilder/StringBuilder provides a mechanish to modify the contents of a Uri/String without having to destroy and recreate a Uri/String each time (which, if done often enough, could hurt performance).

String scheme = "http";
String target = "balaji.com";
int port = 8080;
String path = sample/page1.aspx";
String query = "?query=search text";
UriBuilder u = new UriBuilder(scheme, target, port, path, query);
Categories: C# Tags: , , , , ,

Playing MP3 from C#

March 1, 2011 9 comments

After handling a huge collections of MP3 files, one in my back-up drive and another in my hard-disk’s library, It meant huge gobbling up so much space, which of course you realize when your external hard-drive shows up “Drive Full” message. And an idea bloomed to create this mp3 player which plays files stored in my database!

I have named it “Byte Player” and according to the name the application would be playing the music when data is fed into as byte arrays. The database is designed using the same strategy that’s designed to store normal files.

Add the following DLL reference: “irrKlang.NET4” and put the following DLLs to your bin folder:
~ ikpFlac.dll
~ ikpMP3.dll
~ irrKlang.NET4.dll

Use the following reference:

using IrrKlang;

Generated Database Script to Create Table:

CREATE TABLE [dbo].[MusicLibrary](
	[FileID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[FileName] [nvarchar](50) NOT NULL,
	[FileContent] [varbinary](max) NOT NULL,
	[FileType] [nvarchar](50) NOT NULL,
	[CreateBy] [nvarchar](128) NULL,
	[CreatedOn] [datetime] NULL,
	[ModifiedBy] [nvarchar](128) NULL,
	[ModifiedOn] [datetime] NULL,
 CONSTRAINT [PK_MusicLibrary] PRIMARY KEY CLUSTERED 
(
	[FileID] 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

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[MusicLibrary] ADD  CONSTRAINT [DF_MusicLibrary_FileID]  DEFAULT (newid()) FOR [FileID]
GO

ALTER TABLE [dbo].[MusicLibrary] ADD  CONSTRAINT [DF_MusicLibrary_CreateBy]  DEFAULT (user_name(user_id(user_name()))) FOR [CreateBy]
GO

ALTER TABLE [dbo].[MusicLibrary] ADD  CONSTRAINT [DF_MusicLibrary_CreatedOn]  DEFAULT (getdate()) FOR [CreatedOn]
GO

ALTER TABLE [dbo].[MusicLibrary] ADD  CONSTRAINT [DF_MusicLibrary_ModifiedBy]  DEFAULT (user_name(user_id(user_name()))) FOR [ModifiedBy]
GO

ALTER TABLE [dbo].[MusicLibrary] ADD  CONSTRAINT [DF_MusicLibrary_ModifiedOn]  DEFAULT (getdate()) FOR [ModifiedOn]
GO

The C# application will hold the following methods to interact with the database.

const string connectionString = @"Server=KRISHNA\SQLEXPRESS;Database=music;Trusted_Connection=True;";

/// <summary>
/// Function to select files from the computer to be saved in the database.
/// </summary>
private void OpenMP3Files()
{
    OpenFileDialog dialog = new OpenFileDialog();
    dialog.Filter = "MP3 files|*.mp3";
    dialog.FilterIndex = 1;
    dialog.InitialDirectory = @"C:\\";
    dialog.RestoreDirectory = true;
    dialog.CheckFileExists = true;
    dialog.CheckPathExists = true;
    dialog.Multiselect = true;
    if (dialog.ShowDialog() == DialogResult.OK)
    {
        Cursor.Current = Cursors.WaitCursor;
        foreach (string filename in dialog.FileNames)
        {
            FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
            using (BinaryReader reader = new BinaryReader(stream))
            {
                long length = new FileInfo(filename).Length;
                InsertMP3File(Path.GetFileName(filename), reader.ReadBytes((int)length));
            }
        }
        GetAllMP3();
    }
}

/// <summary>
/// Retrieves entire MP3 list from database (excludes the file content)
/// </summary>
private void GetAllMP3()
{
    string queryString = "SELECT [FileID], [FileName] FROM [MusicLibrary]";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = new SqlCommand(queryString, connection);
        DataSet dataset = new DataSet();
        adapter.Fill(dataset);
        if (dataset.Tables.Count > 0)
        {
            gridMusic.DataSource = dataset.Tables[0];
            gridMusic.Columns[0].Visible = false;
            gridMusic.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
    }
}

/// <summary>
/// Individual files are stored in the database.
/// </summary>
/// <param name="filename"></param>
/// <param name="data"></param>
private void InsertMP3File(string filename, byte[] data)
{
    string filetype = @"audio / mpeg";
    string queryString = "INSERT INTO [MusicLibrary] ([FileName] ,[FileContent] ,[FileType]) VALUES (@FileName, @FileContent, @FileType)";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Parameters.Add(new SqlParameter("@FileName", (object)filename));
        command.Parameters.Add(new SqlParameter("@FileContent", (object)data));
        command.Parameters.Add(new SqlParameter("@FileType", (object)filetype));
        command.Connection.Open();
        command.ExecuteNonQuery();
        command.Connection.Close();
    }
}

Inorder to play the MP3 file I had some initial consideration and based on some strong reviews started of with the “NAudio” library [Ref: http://naudio.codeplex.com] but i faced some issues while trying to play the file from stream and upon searching through discussion forums I discovered that these issues are currently being worked upon and would have a fix in future releases; Therefore i was forced to consider my second choice “irrKlang” sound library [Ref: http://www.ambiera.com/irrklang/] and it worked out to be more simple and brilliant! The code illustrated below shows the fine integration between this library api and the database.

const string sound = "static.mp3";
ISoundEngine engine = new ISoundEngine();

/// <summary>
/// Retrieve individual file content from database
/// </summary>
/// <param name="fileID"></param>
private void GetMP3Data(string fileID)
{
    string queryString = "SELECT [FileContent] FROM [MusicLibrary] WHERE [FileID] = @FileID";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new System.Data.SqlClient.SqlCommand(queryString, connection);
        command.Parameters.Add(new SqlParameter("@FileID", (object)fileID));
        command.Connection.Open();
        byte[] buffer = (byte[])command.ExecuteScalar();
        if (engine.IsCurrentlyPlaying(sound))
        {
            engine.RemoveAllSoundSources();
        }
        PlayMP3(buffer, sound);
        command.Connection.Close();
    }
}

/// <summary>
/// Play a single MP3 file
/// </summary>
/// <param name="data"></param>
/// <param name="filename"></param>
private void PlayMP3(byte[] data, string filename)
{
    ISoundSource source = engine.AddSoundSourceFromMemory(data, filename);
    engine.Play2D(filename);
}

I am so much interested in improving this and building a full-fledged player that would support right from ripping CD’s and expanding the database to include more information about the music albums and MP3 tags.

Categories: C#, Database Tags: , , , ,

DataSet.ReadXmlSchema Method Limitations

February 23, 2011 2 comments

We basically use the DataSet.ReadXmlSchema Method to create the schema which includes table, relation, and constraint definitions for the Dataset. Having said this here is something that’s worth sharing to all of my fellow developers who happen to stumble upon this post in search of a situation to find that their dataset is loading incorrect tables when your xml schema is being read!

Case 1: Sample1.xsd

<?xml version="1.0" encoding="ISO-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:simpleType name="PropertyNames">
    <xs:restriction base="xs:string">
      <xs:enumeration value="prop1"></xs:enumeration>
      <xs:enumeration value="prop2"></xs:enumeration>
    </xs:restriction>
  </xs:simpleType>
  <xs:element name="Items">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Item" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="name" type="xs:string"/>
              <xs:element name="properties" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

When you use the dataset’s “ReadXmlSchema” method you will find that the dataset will contain 2 tables!

// Create the DataSet to read the schema into.
DataSet ds = new DataSet();
// Invoke the ReadXmlSchema method with the file name.
ds.ReadXmlSchema(@"C:\\test\\Sample1.xsd");

A XML instance representation for this schema will be:

<Items>
  <Item> [1..*]
    <name> xs:string </name> [1]
    <properties> xs:string </properties> [0..*]
  </Item>
</Items>

Case 2: Sample2.xsd

<?xml version="1.0" encoding="iso-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:simpleType name="PropertyNames">
    <xs:restriction base="xs:string">
      <xs:enumeration value="prop1"></xs:enumeration>
      <xs:enumeration value="prop2"></xs:enumeration>
    </xs:restriction>
  </xs:simpleType>
  <xs:element name="Items">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Item" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="name" type="xs:string"/>
              <xs:element name="properties" type="PropertyNames" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

This time when you execute the following code you will find that the dataset will contain 1 table!

// Create the DataSet to read the schema into.
DataSet ds = new DataSet();
// Invoke the ReadXmlSchema method with the file name.
ds.ReadXmlSchema(@"C:\\test\\Sample1.xsd");

Whereas the XML instance representation for this schema will be:

<Items>
  <Item> [1..*]
    <name> xs:string </name> [1]
    <properties> PropertyNames </properties> [0..*]
  </Item>
</Items>

Actually, you should have noted that thou the XML instance representation for this schema (Case 2) is similar to the one in (Case 1), the dataset had only one table instead of two; After several hours of investigation and read through, I happen to discover (atleast lucky) thats there is a “Microsoft Support Article” which explains the “Limitations for DataSet Schema Files (XSD)”.

Please find the references to the file at the following location: http://support.microsoft.com/kb/319372

Question: How does this article applies to my scenario?
Answer: Use of Restriction Element Is Mostly Ignored
You can derive a new simple type by restricting an existing simple type with the restriction element. When you use the restriction element in simple types, the restriction element is ignored. Therefore, all the sub-elements of that restriction element are ignored also.

All restriction elements are ignored except the XSD simple type “string”, and its facets as follows:
> length
> minlength
> maxlength

How to create a ZIP file using C#

February 8, 2011 14 comments

In my previous blog post we saw how to create CAB files using Windows Installer XML (WiX) toolset; In this post we will see how to create ZIP files using WiX toolset.

In your .NET project add references to the following DLLs:
Microsoft.Deployment.Compression.dll
Microsoft.Deployment.Compression.Zip.dll

And we will be using this library (Microsoft.Deployment.Compression.Zip) for creating CAB (cabinet) files.

using Microsoft.Deployment.Compression.Zip;

In our example we will see how to add individual files to the ZIP file and how to add a folder (directory) to the ZIP file and finally how to extract (unpack) the ZIP file.

// CREATING ZIP FILE BY ADDING LIST OF FILES
ZipInfo zip = new ZipInfo(@"C:\testarchive1.zip");
List<string> files = new List<string>();
files.Add(@"C:\test1.txt");
files.Add(@"C:\test2.txt");
files.Add(@"C:\test3.txt");
zip.PackFiles(null, files, null);

// CREATING ZIP FILE BY ADDING FOLDER (WITH SUB-FOLDERS) USING MAXIMUM COMPRESSION
zip = new ZipInfo(@"C:\testarchive2.zip");
zip.Pack(@"C:\Balaji", true, Microsoft.Deployment.Compression.CompressionLevel.Max, null);

// EXTRACTING (UNPACKING) FILES FROM ZIP FILE
zip = new ZipInfo(@"C:\testarchive2.zip");
zip.Unpack(@"C:\ArchiveDir");

How to create a CAB (cabinet) file using C#

February 8, 2011 14 comments

At present we do not have classes in .NET that enable us to create CAB (cabinet) files, hence we has other third party libraries and toolsets that provide their custom classes, one such is Windows Installer XML (WiX) toolset (http://wix.sourceforge.net) which is distributed with a collection of dlls as part of its SDK and best of all is that this is developed by Microsoft and we have good support for WiX users.

In your .NET project add references to the following DLLs:
Microsoft.Deployment.Compression.dll
Microsoft.Deployment.Compression.Cab.dll

And we will be using this library (Microsoft.Deployment.Compression.Cab) for creating CAB (cabinet) files.

using Microsoft.Deployment.Compression.Cab;

In our example we will see how to add individual files to the CAB file and how to add a folder (directory) to the CAB file and finally how to extract (unpack) the CAB file.

// CREATING CAB FILE BY ADDING LIST OF FILES
CabInfo cab = new CabInfo(@"C:\testarchive1.cab");
List files = new List();
files.Add(@"C:\test1.txt");
files.Add(@"C:\test2.txt");
files.Add(@"C:\test3.txt");
cab.PackFiles(null,files,null);

// CREATING CAB FILE BY ADDING FOLDER (WITH SUB-FOLDERS) USING MINIMUM COMPRESSION
cab = new CabInfo(@"C:\testarchive2.cab");
cab.Pack(@"C:\Balaji", true, Microsoft.Deployment.Compression.CompressionLevel.Min, null);

// EXTRACTING (UNPACKING) FILES FROM CAB FILE
cab = new CabInfo(@"C:\testarchive1.cab");
cab.Unpack(@"C:\ArchieveDir");
%d bloggers like this: