dotnet thoughts 

a dotnet developer's technical blog

Consuming a C++ DLL in C#

While working on my current project, I had to use some low level I/O operations, but it was difficult using C#, and I got some C++ implementations. Then I thought of creating a DLL in C++ and use it in C#, but I didn’t get any code for the implementation. So I done some searching and I found a solution. It is not a complete solution, but it works :)

Creating a DLL using C++
For creating a DLL in C++, I was used cl.exe, which comes with .net framework. For the implementation I just wrote simple C++ file.(Simple.cpp)

#include <iostream>

extern "C" __declspec(dllexport) char* Hello();
char* Hello()
{
	return "Hello world";
}

I think this is pretty much clear.The extern “C” __declspec(dllexport) allows generate export names automatically. For more details :Exporting from a DLL Using __declspec(dllexport)(MSDN)

After creating this Simple.cpp file, go to Visual Studio Tools > Visual Studio 2008 Command Prompt. Go to the location where you have stored the Simple.cpp file and for compiling and linking C++ file you can use “cl.exe /LD Simple.cpp”.(For more details about cl.exe options checkout : Compiler Options Listed Alphabetically(MSDN) It will compile and Link, and gives a DLL as output.

Consuming a C++ library in C#
When I try to add the DLL by Add Reference, Visual Studio will not allows to add C++ library as Reference. So I tried it with Interop option, by using DLLImportAttribute.

[DllImport(@"D:\Simple.dll", EntryPoint = "Hello")]
public extern static string Hello();

Then you can call this function in C# like the following

private void button1_Click(object sender, EventArgs e)
{
            MessageBox.Show(Hello());
}

It will display a Messagebox with “Hello World”. Thats it you consumed a C++ DLL in C#.

Issue in the implementation

  1. I can’t use the DllImport function without the full location. To avoid this I tried to Register the DLL using RegSvr32.But I got some error from RegSvr like this.
  2. The module “D:\Simple.dll” was loaded but the entry-point DllRegisterServer was not found.

    Make sure that “D:\Simple.dll” is a valid DLL or OCX file and then try again.

I still exploring the things, I will update once I got the solution for this. Happy Coding :)

FILESTREAM in SQL Server 2008

SQL Server 2008 comes with lots of new features compared to the previous versions of SQL Server. One of the new feature is FileStream, which allows storage of and efficient access to BLOB data using a combination of SQL Server 2008 and the NTFS file system.

You can get more details about this in MSDN : FILESTREAM Storage in SQL Server 2008

Enable Filestream in SQL Server

By default the Filestream feature will be disabled. You can enable the filestream using SQL Server Configuration Manager under SQL Server 2008 > Configuration Tools. In this you will get all the SQL Server services. Select the Properties of the instance and select the Tab “FileStream”, from that you can enable the FileStream, you can also specifiy the instance name also.

How to enable FileStream

How to enable FileStream

You can also do it via T-SQL statement also

EXEC sys.sp_configure N'filestream access level', N'2'
RECONFIGURE

After doing this SQL Server will create a shared folder in your machine(or in Server) with the instance name specified. (Or it will create the Windows Share name we are specifying in the textbox) Only SQL Server can access the contents.

Network

Network

You can check this via command prompt, using “Net Share”, you will get an output like this.

Net share command output

Net share command output

Using Filestream in the Database.

For using Filestream in your database you have to add file group in New Database screen.

Enable filestream for new Database

Enable filestream for new Database

Or you can do this via TSQL like this

CREATE DATABASE FileStreamDemo
ON PRIMARY
   (NAME = FileStreamDemo,
      FILENAME = N'D:\DB\FileStreamDemo_data.mdf'),
FILEGROUP FileStreamFileGroup CONTAINS FILESTREAM
   (NAME = FileStreamDemo,
      FILENAME = N'D:\DB\FileStreamDemo')
LOG ON
   (NAME = 'FileStreamDemo_log',
      FILENAME = N'D:\DB\FileStreamDemo_log.ldf');
go

After doing this, SQL Server will create Folder in “D” drive, with name FileStreamDemo under DB directory. This FileStreamDemo folder will contains two files

  1. filestream.hdr – This is the FILESTREAM metadata for the data container.
  2. The directory $FSLOG. This is the FILESTREAM equivalent of a database’s transaction log.

Creating a Table with FILESTREAM Data
You can create a Table for consuming FileStream like this.

CREATE TABLE SQLFileSystem
(
FileId UNIQUEIDENTIFIER  ROWGUIDCOL UNIQUE DEFAULT NEWID() PRIMARY KEY,
FileName VARCHAR(255),
FileContents VARBINARY(MAX) FILESTREAM  NULL default (0x)
)

Thats it, you have created SQL Server Database and Table with Filestream.

Drag and Drop files from Windows to your application

While working around an Script Editor application, I found that in almost all the editors we can drag and drop files from Windows.(Even MS Notepad supports it.) Then I searched for an implementation, but unfortunately I can’t find a perfect one. Then I thought of implementing the same. I am not sure this one is a perfect implementation or not, but it works fine for me. :)

Here is the code. Seems like it is self explanatory

Imports System.IO
Public Class frmMain

    Private Sub txtEditor_MouseDown(ByVal sender As System.Object, _
                                    ByVal e As System.Windows.Forms.MouseEventArgs) _
                                    Handles txtEditor.MouseDown
        'Initiating the Drag and Drop
        txtEditor.DoDragDrop("", DragDropEffects.Copy)
    End Sub

    Private Sub txtEditor_DragEnter(ByVal sender As System.Object, _
                                    ByVal e As System.Windows.Forms.DragEventArgs) _
                                    Handles txtEditor.DragEnter
        'Ensures the dragging data is valid type.
        'Then only setting the drop effect.
        'Otherwise you will see no drop cursor, instead of Copy
        If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
            e.Effect = DragDropEffects.Copy
        Else
            e.Effect = DragDropEffects.None
        End If

    End Sub

    Private Sub txtEditor_DragDrop(ByVal sender As System.Object, _
                                   ByVal e As System.Windows.Forms.DragEventArgs) _
                                   Handles txtEditor.DragDrop
        'Getting the filename.
        'The length of files array will be based on the number of files dragging.
        Dim files As String() = e.Data.GetData(DataFormats.FileDrop)
        'Checking the files(0) is Sql File.
        If Path.GetExtension(files(0)).Equals(".sql", _
                                              StringComparison.CurrentCultureIgnoreCase) Then
            'Reading it using Stream reader
            Me.Text = String.Format("Drag Drop demo - {0}", _
                                    Path.GetFileNameWithoutExtension(files(0)))
            Using sr As New StreamReader(files(0))
                Me.txtEditor.Text = sr.ReadToEnd
            End Using
        Else
            'Otherwise displaying message box
            MessageBox.Show("Only supports SQL files")
        End If
    End Sub
End Class

Here is the screen shot

Drag and Drop Demo - Screenshot

Drag and Drop Demo - Screenshot

If some one know a better implementation please let me know.

More details from MSDN :Performing Drag-and-Drop Operations in Windows Forms

« Newer Posts