Consuming a C++ DLL in C#
July 10, 2009
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
- 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.
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
July 6, 2009
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.
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.
You can check this via command prompt, using “Net Share”, you will get an output like this.
Using Filestream in the Database.
For using Filestream in your database you have to add file group in New Database screen.
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
- filestream.hdr – This is the FILESTREAM metadata for the data container.
- 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
July 4, 2009
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
If some one know a better implementation please let me know.
More details from MSDN :Performing Drag-and-Drop Operations in Windows Forms
Debugging Windows Services
June 18, 2009
In the current project, I have to develop some windows services to sending out notification mails.
The first challenge I faced is I can’t directly run and debug the Windows service.
For that I need to install the service (using installutil –I ServiceName) and attach the process to Visual studio, and then only I can debug it.
It works fine for me.
Then the next challenge was, debugging the code in the onStart event. Because once the service started, then only we can able to attach it to Visual Studio. So I put some code to write to text file, and/or event log. But I feel like it’s not a good method. After searching in the net I got a nice workaround.
protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Launch();
//Rest of the code
}
While starting the Service, it will display a dialog like this
After selecting Yes, Visual Studio will open up and you can start debugging. You can get more information from these links
A Simple Splash screen in C#
June 12, 2009
I started my .net career in VB.Net. While developing a windows application in VB.Net it is pretty easy to put a Splash screen. There is Project property called Splash screen and you can put any form there, after that the specified form will act as a Splash screen. But when I started an windows application in C#, there is no project property called Splash screen. While doing some searching, I found lot of ways, like putting a timer and closing the splash etc. But I feel like it is not the right way of doing a splash screen, then I started my own implementation and found one. I am not sure it is good one or not, but it is working for me.
Here is the steps:
- Added one Form with an Image, as Splashscreen.cs, and my main UI is Welcome.cs
- In the Program.cs I modified the code like the following
- And in the Welcome.cs, added one parameterized constructor, with SplashScreen as the Parameter
- And in the Form_Load() event I added code to close the splash screen if exists.
- Run the application, see the splash is coming and after that Main UI is coming
static void Main()
{
Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SplashScreen s = new SplashScreen();
s.Show();
Welcome welcome = new Welcome(s);
Application.Run(welcome);
}
SplashScreen _s = null;
public Welcome(SplashScreen s)
{
InitializeComponent();
this._s = s;
}
if (this._s != null) { this._s.Close(); }





