.Net

Convert SQL Server Database to a SQLite Database

Recently, I wanted to resurrect an old project of mine I worked on in my spare time originally designed to work on .Net technologies. Naturally, I backed it against a SQL Server 2005 Database which turned out to be a bad idea because it made portability of that data a bit of a nightmare.

So it was with great happiness that I found this tool (mirrored here) by liron.levi who posted an article on CodeProject on how to accomplish this task. You still need a Windows machine and an install of SQL Server (Express Edition with Advanced Tools is alright) but it got the job done just fine for me.

If you want a no-fuss easy way to convert your databases into a format easier to deal with and a lot more portable to-boot.

Download Microsoft .NET Framework 3.5 SP1 Standalone Full Redistributable Setup Installer

Many applications uses Microsoft .NET Framework 3.5 as development platform, and viagra for sale in uk thus requires .NET Framework to be installed beforehand, else the installation will request to download and install .NET Framework from Internet. On offline system without Internet access or online server with slow downloading speed, the requirement to download setup files through web may hit the wall – a no go.

kamagra shipping

Microsoft initially just provides a minimal size dotnetfx35setup.exe download which is a bootstrapper that will still need to download more files via Internet. For users who prefer to perform offline installation or install .NET Framework 3.5 SP1 without waiting for download to complete will have to download and save a copy of full complete standalone or redistributable Microsoft .NET Framework 3.5 SP1 setup installer, which is finally published by Microsoft.

Microsoft .NET Framework 3.5 SP1 (Service Pack 1) is a full cumulative update that contains many new features building incrementally upon .NET Framework 2.0, 3.0, 3.5, and includes cumulative servicing updates to the .NET Framework 2.0 and .NET Framework 3.0 subcomponents. See KB951847 for list of changes and fixed issues in the .NET Framework 3.5 Service Pack 1.

Download full package of Microsoft .NET Framework 3.5 SP1: dotnetfx35.exe (231 MB)

For known issues and release notes, refer to Microsoft .NET Framework 3.5 SP1 Readme.

WebGAC Takes the Pain Out of .Net Dependencies

My good friend Paul Jones, has released a great tool called WebGAC to github.  WebGAC is a great way to manage .net assemblies and adding them to .Net projects from a centralised repository of binaries.  As someone who has used this tool on literally dozens of projects for nearly 2 years now, Its a must have tool for all Visual Studio developers.

Managing binary dependencies in .NET can be a complicated task. For small projects, checking the dependencies into source control tends to work just fine. So does requesting that all developers have various binaries available in their GAC. Grow much bigger, or add more projects, and managing that starts to get very difficult. The Java world has had a solution to this problem for a long time, in the form of Maven and Ivy. Remote servers store the binaries, and the build tool automatically downloads them on demand.

WebGAC adds the core of this functionality to .NET, but without requiring you to switch build tools, or maintain a separate configuration file. Dependencies are specified just the same way as normal, but if you don’t have them when building your project, WebGAC will fetch them for you automatically.

WebGAC is available at http://github.com/paulj/webgac. Browse over there for more information and installation instructions, or continue reading here for more details.

Better way to get the Scheme, Host and Port from Uri Object in .Net

Recently I was working on a project where I needed to strip the scheme, host and port (if it wasn't 80) from a Uri object. Obviously I could have used string concatenation to get the value I needed, but it just seemed so ghastly and inelegant. In frustration and annoyance that it wasn't part of the standard Uri object definition, I asked a friend who gave me this little gem:

side effect of clomid

  1. Uri uri = new Uri("http://localhost:6767/h/ello.php");
  2. string url = new Uri(uri.AbsoluteUri).GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);

The string, 'url', will (in this example) hold the value "http://localhost:6767". This works in .Net 2.0 and up, and with .Net 3.0, you could even create a static method extension to make it even easier.

Sometimes, Microsoft Gets it Right (The .NET Framework 4)

Parallel Programming are two words which are not nearly used enough by programmers today. I think this is partially due to the fact that most developers are answerable to management types who simply "want to get the job done". It's also highly susceptible to deadlocks, race conditions and other problems, which are somewhat more avoidable in traditional single-threaded-apartment model applications. The problem is, that we've reached a precipice in CPU architecture where CPUs are scaling out instead of up. In other words, instead of simply working harder and faster, they're working smarter - executing many simultaneous operations.

side effects of prednisone 40 mg

The only problem with this is that applications need to be programmed to capitalize on this architecture - and making Multi-threaded applications easier is obviously on Microsoft's mind with the announcements of features in the upcoming The .NET Framework 4.0.

One of the main the main features I am looking forward to is the Parallel class to easily thread simple loops. This Parallel class represents a significant advancement in simplistically managing loops.  The .Net 4.0 team assures us that "for many common scenarios, it just works, resulting in terrific speedups".  A similar technique can be used to write parallel loops over iteration spaces of non-integral objects.

  1. Parallel.For(0, N, i=>
  2. {
  3. DoWork(i);
  4. });

There are also overhauls to the ThreadPool class (which was in dire need of serious attention) and the inclusion of "Tasks" - simple generic types which assist developers in creating native IAsyncResult objects: this means that Task can be used as the core of a Begin/End implementation.  They've also really thought about these improvments, with easy and clear ways to cancel parallel operations, as well as a number of great ways to handle Exceptions within parallel blocks.

There are of course other advantages to the 4.0 Framework, but it's the big emphasis on easing MTA (Multi-Threaded Apartment) model application development that's got me excited.

Enjoy!

.Net Remoting Error – Win32Exception: The logon attempt failed

Quite a while ago, in the absence of any alternatives, we built a remote deployment utility so we could push updates to our staging and production servers without manual intervention.

Recently however, while deploying the latest code for an internal project to a new production server, the .Net 2.0 automatic deployment  I had created threw the following, rather unfriendly error:

cialis tadalafil 100mg

Exception Details: System.ComponentModel.Win32Exception: The logon attempt failed
[Win32Exception (0x80004005): The logon attempt failed]
[InvalidCredentialException: The server has rejected the client credentials.]

In order to protect the server from attack we have a system service which we communicate to using .Net remoting, which requires authentication.

Apparently the bug occurred, because I created the user account which we authenticate against on the new server, after I have installed the system service.

I uninstalled the system service, reinstalled it and it magically worked like it should.

What’s the best Way for 2 Processes to Communicate in .Net?

While trawling the internet the other day, I came across this question, and thought it might be something that others might like to know.  The question was:

What's the best (or maybe not the best -- just good) way for two processes in the same machine to communicate, using .NET?

Actually the two processes in the app I'm working on aren't even two different programs; they're just two instances of the same EXE. I wanted to do something like a singleton app, but have it per user (meaning a Terminal Server or Citrix or App-V server with multiple users should be able to launch their own single copy of the app). If another instance is run by the same user, it should just delegate the task to the already running instance, then exit. Only one instance per user of the program should be running. So far I've done (thanks to StackOverflow) the part that detects whether an instance of the app is already running, using Mutex. But I need the second app instance to be able to send data to the first app instance.

I'm leaning towards using named pipes and WCF's NetNamedPipeBinding for this, but if you have better ideas I'll really appreciate it. Thanks :)

IPC is what I've used in the past for this. And it is supprisingly easy. .Net remoting is a good option but unfortunately it is a restricted option becasue you can't for example use it on the CF.

Below is a copy of the class I use to perform Inter-process Communication, you can use it in conjuction with a MutEx if you wish, but it isnt necessary. As long as the "pMappedMemoryName" and "pNamedEventName" are the same in both processes, it should work just fine. I tried to make it as event driven as possible.

The class looks a little like this:

  1. public class IpcService {
  2. private IServiceContext mContext;
  3. const int maxLength = 1024;
  4. private Thread listenerThread;
  5. private readonly string mMappedMemoryName;
  6. private readonly string mNamedEventName;
  7. public event EventHandler IpcEvent;
  8. private readonly bool mPersistantListener;
  9.  
  10. public IpcService(bool pPersistantListener)
  11. : this(pPersistantListener, "IpcData", "IpcSystemEvent") {
  12. ;
  13. }
  14.  
  15. public IpcService(bool pPersistantListener, string pMappedMemoryName, string pNamedEventName) {
  16. mPersistantListener = pPersistantListener;
  17. mMappedMemoryName = pMappedMemoryName;
  18. mNamedEventName = pNamedEventName;
  19. }
  20.  
  21. public void Init(IServiceContext pContext) {
  22. mContext = pContext;
  23. listenerThread = new Thread(new ThreadStart(listenUsingNamedEventsAndMemoryMappedFiles));
  24. listenerThread.IsBackground = !mPersistantListener;
  25. listenerThread.Start();
  26. }
  27.  
  28. private void listenUsingNamedEventsAndMemoryMappedFiles() {
  29. IntPtr hWnd = EventsManagement.CreateEvent(true, false, mNamedEventName);
  30. while (listenerThread != null) {
  31. if (Event.WAITOBJECT == EventsManagement.WaitForSingleObject(hWnd, 1000)) {
  32. string data = Peek();
  33. EventsManagement.ResetEvent(hWnd);
  34. EventHandler handler = IpcEvent;
  35. if (handler != null) handler(this, new TextualEventArgs(data));
  36. }
  37. }
  38. EventsManagement.SetEvent(hWnd);
  39. Thread.Sleep(500);
  40. HandleManagement.CloseHandle(hWnd);
  41. }
  42.  
  43. public void Poke(string format, params object[] args) {
  44. Poke(string.Format(format, args));
  45. }
  46.  
  47. public void Poke(string somedata) {
  48. using (MemoryMappedFileStream fs = new MemoryMappedFileStream(mMappedMemoryName, maxLength, MemoryProtection.PageReadWrite)) {
  49. fs.MapViewToProcessMemory(0, maxLength);
  50. fs.Write(Encoding.ASCII.GetBytes(somedata + "\0"), 0, somedata.Length + 1);
  51. }
  52. IntPtr hWnd = EventsManagement.CreateEvent(true, false, mNamedEventName);
  53. EventsManagement.SetEvent(hWnd);
  54. Thread.Sleep(500);
  55. HandleManagement.CloseHandle(hWnd);
  56. }
  57.  
  58. public string Peek() {
  59. byte[] buffer;
  60. using (MemoryMappedFileStream fs = new MemoryMappedFileStream(mMappedMemoryName, maxLength, MemoryProtection.PageReadWrite)) {
  61. fs.MapViewToProcessMemory(0, maxLength);
  62. buffer = new byte[maxLength];
  63. fs.Read(buffer, 0, buffer.Length);
  64. }
  65. string readdata = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
  66. return readdata.Substring(0, readdata.IndexOf('\0'));
  67. }
  68.  
  69. private bool mDisposed = false;
  70.  
  71. public void Dispose() {
  72. if (!mDisposed) {
  73. mDisposed = true;
  74. if (listenerThread != null) {
  75. listenerThread.Abort();
  76. listenerThread = null;
  77. }
  78. }
  79. }
  80.  
  81. ~IpcService() {
  82. Dispose();
  83. }
  84.  
  85. }

Simply use the Poke method to write data, and the Peek method to read it, although I designed it to automatically fire an event when new data is available. In this way you can simply subscribe to the IpcEvent event and not have to worry about expensive and constant polls.  Enjoy.

Simple Solution to Illegal Cross-thread Calls in C#

If the thread call is "illegal" (i.e. the call affects controls that were not created in the thread it is being called from) then you need to create a delegate so that even if the decision / preparation for the change is not done in the control-creating thread, any resultant modification of them will be. Basically, this is a long winded way of saying you can't (and shouldn't) access controls on a form from a thread that didn't create the control in the first place.

.Net version older than 2.0 (1.0 and 1.1) would actually allow this to happen, but cross-threaded operations should always be dealt with cautiously and properly. The technical solution to the problem is to create a delegate function, and pass the delegate function to the Invoke() method on the control, which allows code to execute as if it was being executed from the control's parent thread, but if you need to do this a lot, all the extra functions and delegates can make the code unreadable, if a lot of it is going on. Fortunately there are 2 "cheats" to the problem. The first is to use the ThreadStart delegate (System.Threading namespace), since its already setup as a simple delegate with one parameter. The second, is to use anonymous delegates, which is something I have covered in the past.

  1.  
  2. if (label1.InvokeRequired) {
  3. label1.Invoke(
  4. new ThreadStart(delegate {
  5. label1.Text = "some text changed from some thread";
  6. }));
  7. } else {
  8. label1.Text = "some text changed from the form's thread";
  9. }
  10.  

Now, the more curious and perceptive of you are asking, why not just use control.Invoke() everytime you change a value? Well, the truth is you could. But calling control.Invoke() has a great deal more overhead than not calling it. However, when you avoid calling control.Invoke() and access UI objects directly from the UI thread, you're writing incorrect code that could cause stability problems in your application.

The problem is that a "window" object in the underlying Windowing API in Win32, as represented by the HWND handle, has thread-affinity. It must be directly accessed only from the thread that created it. If it's not, the results are unpredictable and can cause subtle, intermittent bugs.

By all means skip control.Invoke() if you've only got one thread. However, if you need to affect a UI object from a worker thread, you absolutely must use control.Invoke() to transition back to the UI thread before making that call or you're in for a world of pain.

WorkingSet vrs WorkingSet64

Recently I've been doing a lot of work with the Process.GetCurrentProcess() method and since the application I am building is being developed on the 2.0 64bit framework, I was worried that if I used Process.GetCurrentProcess().WorkingSet64, that the application wouldnt work with 32bit OS's, since WorkingSet was deprecated, but not enforced.

After some thought though, I realised that the WorkingSet returns the amount of memory being used by the process as an integer (32 bit signed integer). OK, so the maximum value of an integer is 2,147,483,647 -- which is remarkably close to the total amount of memory that a process can have in its working set.  Except, there is actually a switch in Windows that will allow a process to use 3 gig of memory instead of 2 gig.  So what would happen when you poll the WorkingSet you will get a negative number, a really big small negative number. Usually, in the realm of -2,147,482,342.  As the more perceptive of you have guessed the problem already.  The overflow bit.

So you ask, why didn't Microsoft just change the API so WorkingSet returned an Int64 instead of an Int32.  Well they could, except that they would break applications built against version 1.0 and 1.1 frameworks, as this post explains.

But after all this pondering, it turns out that WorkingSet64 des exactly what WorkingSet does, except returns an Int64 instead - and as such is less prone to breaks.  Works with both 32bit and 64bit Windows and Frameworks and all is good with the world.

Install A .Net Service Via Command Line

I've been working with .Net services for the last few years or so and it is often convenient for debugging to be able to install your debug version. Since it is a major pain to build an installer every time we want to test, we used the command line utility InstallUtil.exe that comes with the .Net Framework to install and uninstall our services in batch files.

If you've installed .Net in the default location InstallUtil.exe lives in C:\Windows\Microsoft.Net\Framework\v2.0.50727\InstallUtil.exe
in the respective framework version directory.

Below is an example batch file.

C:\Windows\Microsoft.Net\Framework\v2.0.50727\InstallUtil.exe [your-service.exe]

and to uninstall, use the /u flag

C:\Windows\Microsoft.Net\Framework\v2.0.50727\InstallUtil.exe /u [your-service.exe]

Using these batch files we just create short cuts to them and can double click the short cut to install or uninstall. Of course you can install/uninstall more than one service in the batch file.

Be sure to also check out the other flags available for InstallUtil.