calling new SqlConnection() hangs program - c#

This one has me stumped. I'm not even trying to connect to a database. When this code gets to the line where I instantiate a new SqlConnection object, it just hangs there, not throwing an exception or anything. I've tried compiling it for 2.0. 3.5 and 4.0, and they all hang. Of course it works on my machine and yours, too. But I'm trying to run this code on a Windows Server 2008 x64 server, and it won't budge.
// example.cs
using System;
using System.Data;
using System.Data.SqlClient;
public class MainClass {
public static void Main(string[] args) {
Console.WriteLine("start");
SqlConnection conn = new SqlConnection(); // hangs here
Console.WriteLine("finish"); // never makes it here.
}
}
compilation (2.0):
c:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe example.cs

It's probably a broken performance counter which is the issue. I had this problem and I used Procmon to detect what happened. My .NET application hanged when it came to loading the registry keys for the performance monitor ".NET Data Provider for SqlServer"
I unloaded the counter with the following command to get it working:
unlodctr ".NET Data Provider for SqlServer"

Your installation have to be broken. The code doesn't really do anything vital at all, so there is no reason to hang there.
The SqlConnection constructor does this:
public SqlConnection() {
this.ObjectID = Interlocked.Increment(ref SqlConnection._objectTypeCount);
base();
GC.SuppressFinalize(this);
this._innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}
So, it increases a variable, copies it into a property, calls the base constructor, removes the object from the finaliser queue, and copies a reference. That's all.
The base (DbConnection) constructor does this:
protected DbConnection() {
}
So, there is nothing in here that actually does anything at all related to an actual database connection. All that is done when you actually open a connection.
Your program might just as well be hanging after the first Console.WriteLine call, and not even get as far as creating the SqlConnection object.

Suggest 2 steps:
reset IIS to clear any connection pools. (Perhaps restart Windows?)
change the code to have a using statement:
public static void Main(string[] args) {
Console.WriteLine("start");
using (SqlConnection conn = new SqlConnection())
{
Console.WriteLine("middle");
}
Console.WriteLine("finish");
}
Can any other app from that machine make any other SqlConnection objects?
It's obviously an environmental problem, as your posted code will work on any other machine. Suspect that it's gone beyond some tipping point, and the using will help defend against this in the future.

I had the same problem and it began to work after I 1. Changed the target framework from 4.0 to 3.5, and 2. changed the debug settings to x64 in visual studio.

I had the exact same issue after upgrading a number of nuget packages. For me, the solution was:
In Visual Studio go to "Tools" --> "Options"
Search for "Web Projects" (under Projects and Solutions)
Check the "Use the 64 bit version of IIS Express for web sites and projects

I tried to unload the performance counter by executing the following command.
unlodctr ".NET Data Provider for SqlServer"
However, I got a message that the performance counter was not installed.
Therefore, I ran the following command to reinstall the performance counter.
lodctr "C:\Windows\INF\.NET Data Provider for SqlServer\_dataperfcounters_shared12_neutral.ini"
This resolved the application hang-up.

Solution found! I had the same problem on many PCs. Framework 4.5.2
Run this command as admin in CMD:
unlodctr ".NET Data Provider for SqlServer"
You may need to type it by hand as copy pasta doesn't work well with quotes.
Source:
http://askproblem.com/question/calling-new-sqlconnection-hangs-program/
I know this thread is old, but maybe someone else will get this error. It’s
probably a broken performance counter which is the issue. I had this problem
and I used Procmon to detect what happened. My .NET application hanged when it >came to loading the registry keys for the performance monitor “.NET Data
Provider for SqlServer” I unloaded the counter with the following command to
get it working: C: Windowsinf>unlodctr “.NET Data Provider for SqlServer”

Related

License error using Benchmark.NET + DevArt dotConnect for PostgreSQL

I'm working on an application consisting of several projects and using EntityFramework with dotConnect to run against PostgreSQL. I also have a license for dotConnect which successfully works in the main application.
In parallel, I'm crafting a console application(a different solution) using Benchmark.Net to measure the performance of the logic of one of the projects. But every time I run the benchmark I'm getting the error below:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> Devart.Data.PostgreSql.PgSqlException: Assembly that contains embedded dotConnect for PostgreSQL license cannot be used with this application: 0f238e83-669a-46b8-876f-40331880ee79.exe.exe.
Following this instruction, I have already generated licenses.licx through Visual Studio and <exe file>.licenses via lc.exe. But it is still producing the same error.
I'm suspecting that the fact that Benchmark.NET generates its own exe to run the benchmark causing this error but I'm not 100% sure. So I'm looking for a solution if anybody has one?
Thank you
I'm not sure it's a good idea to create a benchmark for code that does database calls etc. You're benchmarking not the code then, but your whole system instead: the file system, the database drivers, possible interop stuff, and so on.
This is not the idea of BenchmarkDotNet. It's actually created for benchmarking of relatively small CPU-bound tasks to find bottlenecks and perform optimizations based on measurements.
However, if you still want to do that, a solution might be to run the benchmark in-process of the console app you've created, without producing special benchmarking assemblies.
To do so, use the [InProcess] attribute. Just apply it to your benchmark class instead of usual job attributes:
[InProcess]
public class TypeWithBenchmarks
{
[Benchmark]
public void BenchmarkedMethod()
{
}
}

Restart SQL service instance using C# 3.5

I have a C# application that has a restore database utility. The restore process consumes a lot of RAM at about 400MB and doesn't give it back to the operating system which is a bit problematic for machines with low memory. For now I'm not limiting my server instance's memory consumption, I'm giving it whatever it wants.
I'd like to restart my server instance using C# code, it frees up the memory used by the restore process. I have looked at the ServiceController which is not available on .NET 3.5 so I'm looking for other options. Currently I would like to go one of the following paths:
SMO
Process
Can you give me the advantages and disadvantages of the two? Also, are there other options to do this?
You can use following VB code
I guess you can convert it to C# automatically by using a code converter
Dim managedComputer As New ManagedComputer()
Dim sqlService As Service
sqlService = managedComputer.Services("MSSQLSERVER")
If sqlService.ServiceState = ServiceState.Stopped Then
sqlService.Start()
End If
You need to add following references to your project
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SqlWmiManagement
Microsoft.SqlServer.WmiEnum

object reference not set to an instance of an object - different behaviour on different systems

ive got a problem that threw my knowlegde in programming a few years back :)
How is it possible that everything works fine on my developping machine and on other testing machines but on the slight different target system it just wont run properly.
I'm trying to open a database connection to a MSSQLSERVER. However it is not going to happen. The exception is threwing a "object reference not set to an instance of an object..." (like i mentioned only on the target system, everywhere else there is no problem)
The exceptions is pointing on the connection.Open() line in the following code.
private void openConnection()
{
string connectionString = getConnectionString();
try
{
connection = new SqlConnection(connectionString);
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I compared the systems. They are nearly the same except of some security policies.
Both are win7 64bit with the same .net version
I hope somebody can help me with this mistery.
Thanks in advance
edit: ive added the connection string an the stacktrace.... maybe it can help anyone to help me.
Check if "connection" is null after the "new Connection" line and throw an exception if it is.
You probably have some variation in the connection string in your environments, which you have failed to address. Test the connection string using a command line database client from the server where this should run; it will likely not connect.
I've got it! I just had to update the .NET version to 4.5.2 and everything works just fine.
After running some other tests i found out that the real exception was accessviolationexception and somehow it seems that it was covered by the nullreferenceexception. however i still dont know why other system didnt had these problems with .NET version 4.5.1 but after days of debugging i just dont care. thanks a lot for all your advices
greets

Tunneling all connections of an application through a proxy

Similar to freecap.
I am looking to develop a solution that works just on certain software and runs invisibly to the end-user. I would like to bundle the tunneler with a software package (of which I don't have access to the source code).
I have heard the only way to do this is similar to what freecap does. Using DLL injection and then hook onto WinSock API. I am just wondering if there was an easier method besides DLL injection via .NET or C++. I can convert most C++ into C#, so that's why I am open to that set.
If not, I would appreciate any advice or links you can provide about going about DLL injection and hooking into the WinSock API. Perhaps an opensource project similar to freecap.
Or, if you know of an application that I can launch via command line say freecap.exe --start myprogram.exe This way freecap would run invisibly to the end user.
API hooking is basically the only way to do this. There are a variety of approaches you could use to hook into WinSock and get your code running and DLL injection (via replacing entries in a process' Import Address Table) is the most straightforward of these.
A dynamically-linked process' IAT stores the memory locations of libraries which contain functions it needs during it's execution. This technique works by modifying entries in this table to point to another library (one containing your code). There are other ways to insert your code into another process, but this is the most stable if you just want to affect the behaviour of a single process on your system.
If you want to avoid doing most of the implementation work yourself and just concentrate on getting something running, I would suggest using EasyHook.
EasyHook is licensed under the GNU Lesser General Public License or LGPL.
From the website:
EasyHook starts where Microsoft Detours ends.
This project supports extending (hooking) unmanaged code (APIs) with pure managed ones, from within
a fully managed environment like C# using Windows 2000 SP4 and later, including Windows XP x64,
Windows Vista x64 and Windows Server 2008 x64. Also 32- and 64-bit kernel mode hooking is supported
as well as an unmanaged user-mode API which allows you to hook targets without requiring a NET
Framework on the customers PC. An experimental stealth injection hides hooking from most of the
current AV software.
As the above says, this project should allow you to greatly simplify the hooking process, and allows you to do so while working in C#.
From the documentation, here's the authors example of injecting a simple Filemon (now Process Monitor)-type utility into a target process:
// Copyright © 2008 Christoph Husse
using System;
using System.Collections.Generic;
using System.Runtime.Remoting;
using System.Text;
using EasyHook;
namespace FileMon
{
public class FileMonInterface : MarshalByRefObject
{
public void IsInstalled(Int32 InClientPID)
{
Console.WriteLine("FileMon has been installed in target {0}.\r\n", InClientPID);
}
public void OnCreateFile(Int32 InClientPID, String[] InFileNames)
{
for (int i = 0; i < InFileNames.Length; i++)
{
Console.WriteLine(InFileNames[i]);
}
}
public void ReportException(Exception InInfo)
{
Console.WriteLine("The target process has reported an error:\r\n"+ InInfo.ToString());
}
}
class Program
{
static String ChannelName = null;
static void Main(string[] args)
{
try
{
Config.Register(
"A FileMon like demo application.",
"FileMon.exe",
"FileMonInject.dll");
RemoteHooking.IpcCreateServer<FileMonInterface>(ref ChannelName, WellKnownObjectMode.SingleCall);
RemoteHooking.Inject(
Int32.Parse(args[0]),
"FileMonInject.dll",
"FileMonInject.dll",
ChannelName);
Console.ReadLine();
}
catch (Exception ExtInfo)
{
Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString());
}
}
}
}
I hope this is helpful. Good luck!

C# Hashtable "object reference not set"

I have an interesting problem that I am trying to solve. I have the following code below which is basically a function for merging values with an html file and giving me the result set. I am using a hashtable for those purposes.
The function is as follows (Please bear in mind that I inherited this functionality and cannot be changed at present)
public static string ParseTemplate(string _FileName, int _NumberofSomething)
{
Hashtable templateVars = new Hashtable();
templateVars.Add("NameOfFile", _FileName);
templateVars.Add("NumberOfSomething", _NumberofSomething);
TemplateParser.Parser parser =
new TemplateParser.Parser(
System.Web.HttpContext
.Current.Server.MapPath("~/docs/Templatenr.htm"), templateVars);
return parser.Parse();
}
On our dev and live servers it is working perfectly. However I am trying to deploy the app to another production server and get an "object reference not set to an instance of object". It breaks exactly on the "Hashtable templateVars = new Hashtable();" line. So I am a bit puzzled. If it was a coding problem it should not work everywhere surely?
The only differences between the different production servers are the OS and IIS that is running. ie. Server 2005 and IIS7 vs Server2003 and IIS6 (which is the environment that it breaks on). Both have .net framework up to 3.5 installed. Could the older OS and ISS be the problem? Is it a maybe permission/memory thing? though that sounds a bit implausible since all the other .net functionality I am using on the new production server is working perfectly.
All the issues regarding the hashtable that I found, relates to it not being instantiated. However my error happens on the line that is trying to instantiate a Hashtable.
Has anyone had an error like this before and if so how did you solve it? I'd even appreciate suggestions on what to look for and I'll give it a try. I'll post back the outcome too, if anyone else is experiencing this error in future.
I never really got to the bottom of this error. Suggestions for using remote debugging with Reflector Pro did not work either, pointing to some issues with the virtual server the website was running in. Checking log files showed other errors that the .net framework threw out.
The website was moved to a new virtual server using IIS7 and windows server 2008. It worked as is on the new environment.
This is maybe not the ideal solution for everybody and maybe a framework re-install could have solved our problem, but since we were in the process of changing over to a new environment (for other reasons) this solution suited us.

Categories