Rails 3: Can’t connect to MySQL server on ‘localhost’ (10061)

I’ve just faced up with some funny problem with Rails and setting up a connection to MySQL-database.
I am using the command prompt to export the schema of some database:

rake db:schema:dump

I am getting the output:

** Execute db:schema:dump
rake aborted!
Can’t connect to MySQL server on ‘localhost’ (10061)

I’ve found the solution for the problem: it is necessary to edit the config/database.yml file and changing the host property: use 127.0.0.1 instead of localhost.

WPF: Specify your DataContext type

Using WPF with MVVM approach it is hard to keep in memory all types of the ViewModels you’re working with for databinding.
There is a quite useful feature which allows you to specify type of DataContext explicitly for each View (UI element).

Assume you have BookViewModel class with Author, Title properties. Also, you have a StackPanel in your XAML to display information about some book.

  1. Add the XML-namespaces to your root View: xmlns:d="http://schemas.microsoft.com/expression/blend/2008", xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006".
  2. Add the attribute mc:Ignorable="d" to your root View.
  3. Add the following StackPanel:
<StackPanel Orientation="Vertical" d:DataContext="{d:DesignInstance vm:BookViewModel}">
    <TextBlock Text="{Binding Path=Author, Mode=OneWay}" />
    <TextBlock Text="{Binding Path=Title, Mode=OneWay}" />
</StackPanel>

Also, JetBrains ReSharper will show you the warning if DataContext type is unknown:

Cannot resolve symbol ‘…’ due to unknown DataContext.

But when the DataContext type is specified and you try using the property which does not exist in the ViewModel, ReSharper will warn you:

Cannot resolve symbol ‘…’.

This makes data binding implementation less error-prone! 😀
Additional information: Walkthrough: Using a DesignInstance to Bind to Data in the Designer.

C#: Auto-implemented property debugging.

Here is how it can be done using Visual Studio 2010:

  1. Go to the Breakpoint window.
  2. New -> Break at Function…
  3. For the get, type: ClassName.get_PropertyName()

    For the set, type: ClassName.set_PropertyName(PropertyType)

There is a “No Source Available” message when the breakpoint is hit, but you’ll get the calling location in the call stack.

NuGet add-in update

I could not update NuGet using Visual Studio Extension Manager.
Furthermore, there is no easy way to remove NuGet from Visual Studio.

There is another way to remove NuGet from Visual Studio:
Remove the NuGet directory, it is located somewhere in “C:Program Files (x86)Microsoft Visual Studio 10.0Common7IDEExtensions” directory and then the latest version can be installed successfully.

NuGet package manager update failed

I could not update NuGet using Visual Studio Extension Manager.
Furthermore, there is no easy way to remove NuGet from Visual Studio.

There is another way to remove NuGet from Visual Studio:
Remove the NuGet directory, it is located somewhere in “C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions” directory and then the latest version can be installed successfully.

C#: Asynchronous method call

Just to store it! 😀

[code language=”csharp”]
public static IAsyncResult RunAsync(
Func<AsyncCallback, object, IAsyncResult> begin,
Action<IAsyncResult> end,
Action<Action> callback)
{
return begin(ar =>
{
try
{
end(ar);
callback(delegate { });
}
catch (Exception ex)
{
callback(() => { throw ex; });
}
}, null);
}

public static IAsyncResult RunAsync<T>(
Func<AsyncCallback, object, IAsyncResult> begin,
Func<IAsyncResult, T> end,
Action<Func<T>> callback)
{
return begin(ar =>
{
try
{
T result = end(ar);
callback(() => result);
}
catch (Exception ex)
{
callback(() => { throw ex; });
}
}, null);
}
[/code]

Client example:
[code language=”csharp”]
Action printAction = () =>
{
Console.WriteLine("Hello, World!");
Thread.Sleep(10000);
// throw new InvalidOperationException();
Console.WriteLine("Bye!");
};

IAsyncResult asyncResult = RunAsync(printAction.BeginInvoke, printAction.EndInvoke,
(func) =>
{
func();
});

asyncResult.AsyncWaitHandle.WaitOne();
[/code]

.NET SOAP web service: transfer objects

Currently I am developing a .NET web service.

I have got the exception:

System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to http://localhost:1062/MyApp.asmx. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. —> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. —> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. —> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
— End of inner exception stack trace —
at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.HttpWebRequest.MakeMemoryStream(Stream stream)
— End of inner exception stack trace —
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
— End of inner exception stack trace —

I could not find the root cause of the problem for a four hours!
Then I tried the WCFStorm utility to test the web service.
Tried to call some service method, here is the log:

System.Web.Services.Protocols.SoapException: Server was unable to process request. —> System.InvalidOperationException: Unable to generate a temporary class (result=1).
error CS0200: Property or indexer ‘MyApp.DataAccess.Data.MediaInfo.ID’ cannot be assigned to — it is read only
// OTHER READONLY PROPERTIES HERE!

at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Type type)
at System.Web.Services.Protocols.SoapServerType..ctor(Type type, WebServiceProtocols protocolsSupported)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
— End of inner exception stack trace —

So, to solve the problem it is necessary to use Data Transfer Objects (DTOs) with public accessors/modifiers (XML serializer requires them).

SQL Network Interfaces, error: 26 – Error Locating Server/Instance Specified

I have spent too much time to deploy the ASP.NET MVC site (it uses Entity Framework Code First).

Error message (from Windows System Log):

Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 10/20/2011 12:21:16 PM
Event time (UTC): 10/20/2011 8:21:16 AM
Event ID: 58ae882058464c29a1b9ed78cf2e26b1
Event sequence: 4
Event occurrence: 1
Event detail code: 0

Application information:
Application domain: /LM/W3SVC/2/ROOT/some_name-2-129635724418750313
Trust level: Full
Application Virtual Path: /some_url
Application Path: C:inetpubsome_path
Machine name: IM

Process information:
Process ID: 1720
Process name: w3wp.exe
Account name: NT AUTHORITYNETWORK SERVICE

Exception information:
Exception type: SqlException
Exception message: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 – Error Locating Server/Instance Specified)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action1 act)
at System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action
1 act)
at System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
at System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)

Request information:
Request URL: http://some_site/some_url
Request path: /some_url
User host address: host_address
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITYNETWORK SERVICE

Thread information:
Thread ID: 11
Thread account name: NT AUTHORITYNETWORK SERVICE
Is impersonating: False
Stack trace: at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action1 act)
at System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action
1 act)
at System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
at System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)

Custom event details:

Solution:

In my case, in Web.config file the name of connection string was not equal to the name of Entity Framework DbContext-derived class name.
Just put the name of your DbContext to connection string name.

I hope this will save plenty time for someone! 😀

IIS: Unknown attribute “targetFramework”.

I have got another IIS error message: “Unknown attribute ‘targetFramework'”.

<system.web>
  <compilation debug="true" targetFramework="4.0">
    <assemblies>
      <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

It seems to indicate that the site is configured to run under .NET 4 while IIS has been set up to run under an earlier version. To target .NET 4 in IIS, open the IIS Manager and expand the Application Pools node. Then find the application pool used by your web site, call the context menu and choose “Basic Settings” and then switch the target framework from 2.0 to 4.0.