C#.net Console Application SQLCommand.CommandTimeOut property not working - sql-server

I have a console application written in C# 4.0. I am running a SQL stored procedure that sometimes takes too long and and a connection timeout exception gets thrown.
To handle it, I first set Timeout to 360 in the connection string in the web.config file but no luck.
Then i tried:
SQLCommand cmd = new SQLCommand();
cmd.CommandTimeout = 360;
but this is also not working.
Any help would be greatly appreciated. I tried to do same with the Entity Framework 4.0 but had the same issue. The timeout value i am providing is not being applied!
<add name="ConnectionString" connectionString="SERVER=db.mydomain.com;DATABASE=DatabaseName;UID=userID;PWD=Password;Connect Timeout=360;Packet Size=8192;Pooling=True;Min Pool Size=1;Max Pool Size=1000;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
Exception:
Timeout expired: The timeout period elapsed prior to completion of the operation or the server is not responding.

Set the CommandTimeout = 0 in your code and remove it from the config file.
Setting the Timeout = 0 means, it will complete the job in case of long operation also.

Do you have context connection=true in the connection string in your Web.config file? According to MSDN:
CommandTimeout has no effect when the command is executed against a context connection

Related

How to Dapper & AseClient

Unable to connect to Sybase, not getting error.
I have referenced Sybase.AdoNet4.AseClient.dll from C:\Sybase\DataAccess\ADONET\dll to my MVC 5 project, running in .NET 4.5
Web.Config Connections string
<add name="MyASEServer" connectionString="Data Source=127.0.0.20:12000;Initial Catalog=MyDB;User Id=USer1;Password=Password1;"
providerName="Sybase.Data.AseClient"/>
My code
string constr = ConfigurationManager.ConnectionStrings["MyASEServer"].ConnectionString;
IDbConnection aseDB = new AseConnection(constr );
var myCustomer = aseDB.Query<Customer>("select * fromdbo.customer");
When the debugger reaches aseDB.Query...., it never return and not receiving any error.
What am I missing.
In this case, Application Insights is on in visual studio and all the exceptions are captured in it. So the application screen is not showing the exception.

.NET application fails to run from Network Share and RDP Shell

I'm trying to run my .NET application, that resides in a network share from our domain, using a RDP Client.
When starting a "full" RDP session (that is, opening the whole desktop) and then running my application from the .exe file, everything works fine.
But when I set this same .exe as the Startup Application Path from the RDP Client , I get the following error:
(PS: I clipped the stack trace to the calls I found myself more important)
System.TypeInitializationException: The type initializer for 'NHibernate.Cfg.Environment' threw an exception. ---> System.ArgumentException: Incorrect Parameter. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
at System.Security.Policy.PEFileEvidenceFactory.GetLocationEvidence(SafePEFileHandle peFile, SecurityZone& zone, StringHandleOnStack retUrl)
(...)
at System.AppDomain.get_Evidence()
(...)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at NHibernate.Cfg.Environment.LoadGlobalPropertiesFromAppConfig() in p:\nhibernate-core\src\NHibernate\Cfg\Environment.cs:line 212
at NHibernate.Cfg.Environment..cctor() in p:\nhibernate-core\src\NHibernate\Cfg\Environment.cs:line 198
As I work with shadow-copied files, I set a new AppDomain when the application has just begun (the .exe entry point):
<STAThread()>
Public Sub Main()
Try
Dim currentDirectory As DirectoryInfo = New DirectoryInfo(Directory.GetCurrentDirectory)
Dim runtimeDirectory As DirectoryInfo = New FileInfo(Assembly.GetExecutingAssembly.Location).Directory
Dim appDomainStartupSetup As New AppDomainSetup
appDomainStartupSetup.ApplicationBase = currentDirectory.FullName
appDomainStartupSetup.ShadowCopyFiles = "true"
Dim appDomainStartup As AppDomain = AppDomain.CreateDomain("StartupAppDomain", Nothing, appDomainStartupSetup)
Dim entrypointLoader As LoadBaseFiles = appDomainStartup.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly.CodeBase, "MyClass.LoadBaseFiles")
entrypointLoader.RuntimeDir = runtimeDirectory.FullName ' Setup the 'entry-point' object
entrypointLoader.StartupEntryPoint() ' Starts the Application
Catch ex As Exception
' Error Handling Here
End Try
End Sub
Public Class LoadBaseFiles
Inherits MarshalByRefObject
' Startup stuff here...
End Class
More Info
Content of my ApplicationEntryPoint.exe.config file;
I had set the CAS Policy to Full Machine Trust, but I'm not sure this still applies to .NET 4.0;
The Remote Desktop (Terminal Services) Server runs Windows Server 2003;
EDIT:
If I copy all the assemblies to a local drive (C:) and run my application from there, it will work fine.
Any advices?
It looks like you're missing an argument or pointing to an unavailable resource.
a) Is the Working Directory set for the application?
b) Is the Working Directory available to the user on login?

SQL server Data Tools- can not browse the deployed cube

I'm trying to browse the deployed cube, but it doesn't work. I have this error: "Element "return" was not found. Line 5, position 2". I've made the connection with database and it worked (I saw that when I created dimensions and cubes). Also the deployment completed successfully. How can I fix this problem?
Advanced Information:
Program Location: at System.Xml.XmlReader.ReadStartElement(String
name) at
Microsoft.AnalysisServices.AdomdClient.XmlaReader.ReadStartElement(String
name) at
Microsoft.AnalysisServices.AdomdClient.XmlaClient.SupportsProperty(String
propName) at
Microsoft.AnalysisServices.AdomdClient.XmlaClient.Connect(ConnectionInfo
connectionInfo, Boolean beginSession) at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Connect(Boolean
toIXMLA) at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Microsoft.AnalysisServices.AdomdClient.AdomdConnection.IXmlaClientProviderEx.ConnectIXmla()
at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection.ConnectToIXMLA(Boolean
createSession) at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection.Open() at
Microsoft.AnalysisServices.Browse.ConnectionsManagerBase.Connect()
at
Microsoft.AnalysisServices.Browse.DimensionBrowser.ConnectionManager.Connect()
at
Microsoft.AnalysisServices.Browse.DimensionBrowser.EstablishConnection()
at Microsoft.AnalysisServices.Browse.DimensionBrowser..ctor(String
nameOfDimension, Object dimensionObject, IServiceProvider
iserviceProvider, DesignerPageRelevantData designerPageRelevantData,
UserContextData securityContextData) at
Microsoft.AnalysisServices.Browse.DimensionBrowserHostControl.CreateBrowser()
at Microsoft.AnalysisServices.Browse.BrowserHostControl.LoadBrowser()
Thanks in advance
I also ran into this issue - it seems to have something to do with the connection timing out. Changing the connection time-out value in the connection options to a higher value (30, 60, etc) fixed the issue.

Occasional, unpredictable exceptions with multi-threaded solrj queries

I have a multi-threaded application using solrj 4. There are a maximum of 25 threads. Each thread creates a connection using HttpSolrServer, and runs one query. Most of the time this works just fine. But occasionally I get the following exception:
Jan 10, 2013 9:29:07 AM org.apache.http.impl.client.DefaultRequestDirector tryConnect
INFO: I/O exception (java.net.NoRouteToHostException) caught when connecting to the target host: Cannot assign requested address
Jan 10, 2013 9:29:07 AM org.apache.http.impl.client.DefaultRequestDirector tryConnect
INFO: Retrying connect
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
at java.util.concurrent.FutureTask.get(FutureTask.java:111)
I wrote some code to retry the query, if it fails:
while(!querySuccess && queryAttempts<m_MaxQueryAttempts ){
try{
queryAttempts++;
rsp = m_Server.query( query );
querySuccess = true;
}catch(SolrServerException e){
querySuccess = false;
}
}
After one or more retries the query usually works. But sometimes it fails even after 100 retries. Either way, I'd like to understand what the cause of the problem is. Why does it work some of the time? Is it an issue with concurrent access to solr? Apart from this process, I only have one other process that it continually writing to the index using a single connection. The default server settings are below - so I don't think it's because of too many simultaneous connections.
INFO: Creating new http client, config:maxConnections=128&maxConnectionsPerHost=32&followRedirects=false
Any suggestions on how to diagnose this would be much appreciated.

Silverlight RIA Services - How To Best Handle Client Auth Session Timeout?

I built an app with Silverlight4, RIA Services, and I'm using ASP.NET Membership for authentication/authorization.
My web.config has this:
<system.web>
<sessionState timeout="20"/>
<authentication mode="Forms">
<forms name="_ASPXAUTH" timeout="20"/>
</authentication>
I have read a number of different strategies on how to deal with auth/session timeout on the client side. That is: if the client is idle for x minutes (20 here), and then they do something with the UI that triggers a RIA/WCF call, I want to trap on that event and deal with appropriately (e.g. take them back to the login screen) -- in a nutshell: I need a way to differentiate from a bona-fide server side DomainException vs. an auth failure because the session timed out.
AFAIK: there is no typed exception or property that can determine this. The only way I've been able to determine this -- which seems like a hack: is to inspect the Error's Message string and look for something like "Access denied" or "denied". For example: something like this:
if (ex.Message.Contains("denied"))
// this is probably an auth failure b/c of a session timeout
So, this is what I'm currently doing, and it works if I run and debug either with the built-in server from VS2010, or if I run in localhost IIS. If I set the timeout to 1 minute, login, wait more than a minute and trigger another call, I breakpoint on the exception and enter the if code block above and all is well.
Then I deploy the app to a remote IIS7 server and I try the same test and it doesn't work. So, I added log tracing, and here's the event where the exception happened:
<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
<EventID>131076</EventID>
<Type>3</Type>
<SubType Name="Error">0</SubType>
<Level>2</Level>
<TimeCreated SystemTime="2011-10-30T22:13:54.6425781Z" />
<Source Name="System.ServiceModel" />
<Correlation ActivityID="{20c26991-372f-430f-913b-1b72a261863d}" />
<Execution ProcessName="w3wp" ProcessID="4316" ThreadID="24" />
<Channel />
<Computer>TESTPROD-HOST</Computer>
</System>
<ApplicationData>
<TraceData>
<DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
<TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.TraceHandledException.aspx</TraceIdentifier>
<Description>Handling an exception.</Description>
<AppDomain>/LM/W3SVC/1/ROOT/sla-2-129644844652558594</AppDomain>
<Exception>
<ExceptionType>System.ServiceModel.FaultException`1[[System.ServiceModel.DomainServices.Hosting.DomainServiceFault, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message></Message>
<StackTrace>
at System.ServiceModel.DomainServices.Hosting.QueryOperationBehavior`1.QueryOperationInvoker.InvokeCore(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.DomainServices.Hosting.DomainOperationInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
</StackTrace>
<ExceptionString>System.ServiceModel.FaultException`1[System.ServiceModel.DomainServices.Hosting.DomainServiceFault]: (Fault Detail is equal to System.ServiceModel.DomainServices.Hosting.DomainServiceFault).</ExceptionString>
</Exception>
</TraceRecord>
</DataItem>
</TraceData>
</ApplicationData>
</E2ETraceEvent>
The problem is that I don't have the string in the error message that indicates "denied" or "Access denied" - and I am unsure as to why this solution works in localhost IIS or VS2010 host but not in a remote IIS7 server. Is there some obscure configuration setting that I'm missing here? Is there a better way to do this in general?
You've probably gotten by this by now, but this article describes using the DomainOperationException and checking the error codes.
dex.ErrorCode == ErrorCodes.NotAuthenticated || dex.ErrorCode == ErrorCodes.Unauthorized
For convenient access (and in case the we loose access to the blog) here's the blog article by Josh Eastburn:
A question that comes up often from developers who are working with Silverlight and WCF RIA Services: why does my Silverlight application throw an exception when it has been idle for a period of time? As you might expect, it is due to the authenticated session timing out. But it isn’t quite that straightforward. Because Silverlight uses a client/server architecture, the client can operate independent of the server for an indefinite period of time. It is only when the Silverlight client makes a call to the server that the server-side timeout is realized. There are a few options to handle the client-server timeout issue (and you may be able to come up with a few more): If you aren’t concerned with the security implications of removing a session timeout, you can either increase the timeout setting in web.config, or create a DispatcherTimer in the Silverlight client that calls a simple method on the server to act as a "Keep Alive." Add a DispatcherTimer to the Silverlight client that stays in sync with the server-side timeout and warn/prompt the user keep the session active before the time expires or have them re-authenticate if it has already expired. However, this requires extra effort to keep the timers in sync when new server requests are made. Allow the server to handle the timeout as it normally would and handle the timeout gracefully on the Silverlight client. This means that the timeout is determined by server call activity, NOT activity confined the Silverlight client (i.e. accessing client-side data in the context). Of these three options, I find the third to be the best balance of security and usability while at the same time not adding unnecessary complexity to the application. In order to handle these server-side timeouts globally, you can add the following logic in either the Application_UnhandledException method in App.xaml.cs or in your global ViewModel loading construct if you have one:
// Check for Server-Side Session Timeout Exception
var dex = e.ExceptionObject as DomainOperationException;
if ((dex != null) && (dex.ErrorCode == ErrorCodes.NotAuthenticated || dex.ErrorCode == ErrorCodes.Unauthorized) && WebContext.Current.User.IsAuthenticated)
{
// A server-side timeout has occurred. Call LoadUser which will automatically
// authenticate if "Remember Me" was checked, or prompt for the user to log on again
WebContext.Current.Authentication.LoadUser(Application_UserLoaded, null);
e.Handled = true;
}
The following constants are defined within the ErrorCodes class:
public static class ErrorCodes
{
public const int NotAuthenticated = 0xA01;
public const int Unauthorized = 401;
}
When the server-side session times out, any subsequent calls will return a DomainOperationException. By inspecting the returned ErrorCode, you can determine if it is an authentication error and handle it accordingly. In my example, I am calling WebContext.Current.Authentication.LoadUser() which will attempt to re-authenticate the user if possible. Even if the user can not be automatically re-authenticated, it will call back to my Application_UserLoaded method. There I can check WebContext.Current.User.IsAuthenticated to determine whether to proceed with the previous operation or if I need to redirect back to the home page and reprompt for login. Here is an example of some code in the Appliation_UserLoaded callback that shows a login dialog if the user is not authenticated:
// Determine if the user is authenticated
if (!WebContext.Current.User.IsAuthenticated)
{
// Show login dialog automatically
LoginRegistrationWindow loginWindow = new LoginRegistrationWindow();
loginWindow.Show();
}
To test your code, you can set your timeout value in web.config to a
small value so timeouts occur quickly:
<authentication mode="Forms">
<forms name=".Falafel_ASPXAUTH" timeout="1" />
</authentication>
If you’d like to see all of this code in a working solution, check out our Silverlight RIA Template on CodePlex.

Resources