Azure Service Bus timeout exception with NancyFX - c#

I have a NancyFX API, and when one of the endpoints is hit, I need to kick of a longer running asynchonous task that's decoupled from the endpoint itself. So I'm trying to use a Azure Service Bus queue.
I'm successfully writing a message to the queue when the NancyFX endpoint is hit. I can also successfully subscribe and read from the queue from something other than NancyFX (I tested from Linqpad).
However, if I try to subscribe from the NancyFX app, I get a timeout exception within a second or two from starting the app. I'm doing this in another thread which is kicked off from the NancyFX Bootstrapper.ApplicationStartup override.
I'm unsure why this would be different than doing it not in the NancyFX app. I can't see anything of relevance in the web.config file.
Below is the code I'm using to subscribe to the queue ...
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider("Main", AccessKey);
var factory = await MessagingFactory.CreateAsync("sb://myapp.servicebus.windows.net", tokenProvider);
var receiver = await factory.CreateMessageReceiverAsync("MyQueue");
receiver.OnMessage(bm =>
{
// Do something here
}, new OnMessageOptions
{
MaxConcurrentCalls = 1,
});
Below is the exception ...
System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: A timeout has occurred during the operation. b6b8e25a-714f-4f55-8a79-91e390f47a96_G25 (Fault Detail is equal to An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.TimeoutException: A timeout has occurred during the operation.
).
And here is the callstack when I caught it in the debugger ...
Microsoft.ServiceBus.dll!Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.ThrowIfFaultMessage(System.ServiceModel.Channels.Message wcfMessage) Line 463 C#
Microsoft.ServiceBus.dll!Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.HandleMessageReceived(System.IAsyncResult result) Line 313 C#
Microsoft.ServiceBus.dll!Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.OnMessageReceived(System.IAsyncResult result) Line 381 C#
System.ServiceModel.Internals.dll!System.Runtime.AsyncResult.Complete(bool completedSynchronously) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.TransportDuplexSessionChannel.TryReceiveAsyncResult.OnReceive(System.IAsyncResult result) Unknown
System.ServiceModel.Internals.dll!System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(System.IAsyncResult result) Unknown
System.ServiceModel.Internals.dll!System.Runtime.AsyncResult.Complete(bool completedSynchronously) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult.OnReceiveComplete(object state) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(object state) Unknown
System.ServiceModel.Internals.dll!System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(System.IAsyncResult result) Unknown
System.dll!System.Net.LazyAsyncResult.Complete(System.IntPtr userToken) Unknown
System.dll!System.Net.LazyAsyncResult.ProtectedInvokeCallback(object result, System.IntPtr userToken) Unknown
System.dll!System.Net.Security._SslStream.ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, System.Net.AsyncProtocolRequest asyncRequest) Unknown
System.dll!System.Net.Security._SslStream.ReadFrameCallback(System.Net.AsyncProtocolRequest asyncRequest) Unknown
System.dll!System.Net.AsyncProtocolRequest.CompleteRequest(int result) Unknown
System.dll!System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(int bytes) Unknown
System.dll!System.Net.FixedSizeReader.ReadCallback(System.IAsyncResult transportResult) Unknown
System.ServiceModel.Internals.dll!System.Runtime.AsyncResult.Complete(bool completedSynchronously) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.ConnectionStream.IOAsyncResult.OnAsyncIOComplete(object state) Unknown
System.dll!System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) Unknown
System.dll!System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(System.Net.Sockets.SocketError socketError, int bytesTransferred, System.Net.Sockets.SocketFlags flags) Unknown
System.dll!System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* nativeOverlapped) Unknown
mscorlib.dll!System.Threading._IOCompletionCallback.PerformIOCompletionCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* pOVERLAP) Unknown
[Native to Managed Transition]

The exception you got is an indication of the client not being able to go past ASB gateway to talk to the backend. You could use the provided tracking ID (b6b8e25a-714f-4f55-8a79-91e390f47a96_G25) to open a support case. In case that exception persists, try a different namespace to see if that rules it out.

Related

ReportExecutionService not honoring timeout

I am using .NET ReportExecutionService to render SSRS reports. We are rendering many reports in rapid fire and we are randomly getting reports that timeout. Somewhere around 1 out of 1400 reports will hang.
When I check the hanging report in ExecutionLog3, I see the report with a status of rsSuccess, and a total time of around 3s. So it looks like the report finishes but the response never gets seen by the render call, and times out after 5 minutes with the following exception:
System.InvalidOperationException: There is an error in XML document (1, 2655). ---> System.Net.WebException: The operation has timed out.
at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer(Char[] userBuffer, Int32 userOffset, Int32 desiredChars, Boolean& readToUserBuffer)
at System.IO.StreamReader.Read(Char[] buffer, Int32 index, Int32 count)
at System.Xml.XmlTextReaderImpl.ReadData()
at System.Xml.XmlTextReaderImpl.ParseText(Int32& startPos, Int32& endPos, Int32& outOrChars)
at System.Xml.XmlTextReaderImpl.ParseText()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Xml.XmlReader.ReadElementString()
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read12_ReportParameter(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read17_ExecutionInfo(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read111_SetExecutionParametersResponse()
at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer25.Deserialize(XmlSerializationReader reader)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
--- End of inner exception stack trace ---
If anyone has any suggestions on how to prevent these timeouts I would be glad to try, but I think the easier solution for now is if I can figure out how to set a shorter timeout on the render call. If I can time out and retry the report after 30s that will still give us the performance we need.
Here is my render call. What timeout option do I need to change to make this call fail after 30s?
//tried setting the timeout in the constructor
var rsExec = new rsExecService.ReportExecutionService
{
Url = string.Format("{0}{1}", url, executionServiceUrl), Timeout = 30000
};
//tried setting the timeout before calling render
rsExec.Timeout = 30 * 1000;
results = rsExec.Render(format, deviceInfo, out extension, out mimeType, out encoding, out warnings, out streamIDs);

Entity Framework Model With Children in WCF Service works only once

To start off explaining, I have a model called VitalSign and one called VitalSignValues.
In my VitalSign model I have this code:
[ForeignKey("IdVitalSign")]
public virtual ICollection<VitalSignValue> VitalSignValues { get; set; }
In my VitalSignValue model:
public Guid IdVitalSign { get; set; }
And I got a default manager with basic functions like getAll(), ...
The project contains multiple web services and they all work fine, except for this one (VitalSignService). When I run the service, even with the WCF Test Client and I test the getAll function, it works.
The problem is that the getAll function only works like once, when I try to call the function again I suddenly get this error:
An error occurred while receiving the HTTP response to http://localhost/webservice/VitalSignService.svc. 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.
I tried to check the trace logs, but for some reason the only information it gives me is:
ASP.Net hosted compilation
AppDomain unloading
Here is the error log (although it doesn't really contain good information for me)
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at IVitalSignService.GetAllVitalSigns()
at VitalSignServiceClient.GetAllVitalSigns()
Inner Exception:
The underlying connection was closed: An unexpected error occurred on a receive.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
Inner Exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
Inner Exception:
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)
EDIT:
Here is some more information:
In my application, I call this function:
var client = new VitalSignServiceClient();
_vitalSigns = client.GetAllVitalSignsWithValues().ToList();
client.Close();
Inside of my service, I got this function:
public ICollection<VitalSign> GetAllVitalSignsWithValues()
{
return _vitalSignManager.GetAll("VitalSignValues");
}
In my generic manager, this happens:
public ICollection<TObject> GetAll(params string[] navigationProperties)
{
var query = Context.Set<TObject>().AsQueryable();
foreach (string navigationProperty in navigationProperties)
query = query.Include(navigationProperty);
var list = query.ToList<TObject>();
return list;
}
When I try to find the problem through debugging, it does go into the service, into the generic manager and it does get the VitalSigns, it's just the moment where the client retrieves the data from the web service that the error occurs and everything fails.
Also remember that all of this actually works (but only 1 out of 10 times, so probably only when the server refreshed it or something)
SOLVED: Removed the "virtual" in front of the IList
I don't like the way you're closing/disposing your WCF proxies and EF contexts. Looking for trouble there. Look into "using" like below. I would also recommend you don't use a static EF context. Again looking for trouble by doing this. (LinqToSql declare and instantiate DataContext best practice?). Third, I know it's tempting to make a generic repository that does everything but this ends up being more work than it's worth. For testing, performance and maintainability purposes, make your API calls specific.
Try:
using(var client = new VitalSignServiceClient()
{
_vitalSigns = client.GetAllVitalSignsWithValues().ToList();
}
public ICollection<VitalSign> GetAllVitalSigns()
{
using(ctx = new YourContext())
{
// do stuff
}
}

Error when reading data from SQL Server database

I have a filestream enabled database
I am able to write to the database but when I try to read the data back i get this error
An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.Data.dll
Additional information: The user name or password is incorrect
The code I am trying to execute is this
public void ReadFromDatabase()
{
using (SqlConnection connection = new SqlConnection(sql_ConnectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT TOP(1) Video.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM Library", connection);
SqlTransaction sqlTrans = connection.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = sqlTrans;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string path = reader.GetString(0);
byte[] transContext = reader.GetSqlBytes(1).Buffer;
using (Stream fileStream = new SqlFileStream(path, transContext, FileAccess.Read, FileOptions.SequentialScan, allocationSize: 0))
{
byte[] data = new byte[fileStream.Length];
fileStream.Read(data, 0, (int)fileStream.Length);
File.WriteAllBytes(#"C:\Users\Georgi\AppData\Local\VideoPresenter\temp.mp4", data);
}
}
}
}
}
I am using integrated security so the user and password are unchanged and hard coded into the application.
Here is the connection string code
//Create a string builder object
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
//Set the properties of the builder
builder.AsynchronousProcessing = false;
builder.DataSource = "xxx.xxx.xxx.xxx";
builder.IntegratedSecurity = true;
builder.InitialCatalog = "VideoLibrary";
//Set the connection string and connection objects' data
sql_ConnectionString = builder.ToString();
//try to connect to the server
And then I just use the string to open connections
The connection string passed is
"Data Source=xxx.xxx.xxx.xxx;Initial Catalog=VideoLibrary;Integrated Security=True"
Here is the stack trace
System.Data.dll!System.Data.SqlTypes.SqlFileStream.OpenSqlFileStream(string path, byte[] transactionContext, System.IO.FileAccess access, System.IO.FileOptions options, long allocationSize) Unknown
System.Data.dll!System.Data.SqlTypes.SqlFileStream.SqlFileStream(string path, byte[] transactionContext, System.IO.FileAccess access, System.IO.FileOptions options, long allocationSize) Unknown
SQL FILESTREAM TEST CLIENT.exe!SQL_FILESTREAM_TEST_CLIENT.SQLOperations.ReadFromDatabase() Line 158 C#
SQL FILESTREAM TEST CLIENT.exe!SQL_FILESTREAM_TEST_CLIENT.MainWindow.GetButton_Click(object sender, System.Windows.RoutedEventArgs e) Line 47 C#
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs e) Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnClick() Unknown
PresentationFramework.dll!System.Windows.Controls.Button.OnClick() Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) Unknown
PresentationCore.dll!System.Windows.UIElement.OnMouseLeftButtonUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e) Unknown
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args, System.Windows.RoutedEvent newEvent) Unknown
PresentationCore.dll!System.Windows.UIElement.OnMouseUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e) Unknown
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs args, bool trusted) Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input) Unknown
PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport) Unknown
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel) Unknown
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd, MS.Internal.Interop.WindowMessage msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) Unknown
WindowsBase.dll!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object source, System.Delegate method, object args, int numArgs, System.Delegate catchHandler) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs) Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) Unknown
[Native to Managed Transition]
[Managed to Native Transition]
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() Unknown
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) Unknown
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) Unknown
PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) Unknown
PresentationFramework.dll!System.Windows.Application.Run() Unknown
SQL FILESTREAM TEST CLIENT.exe!SQL_FILESTREAM_TEST_CLIENT.App.Main() C#
[Native to Managed Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) Unknown
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() Unknown
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) Unknown
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() Unknown
When I open Management Studio I see the row that is filled with the data but I am not able to read it from the application
NOTE: There is the default SQL Server user 'sa' only. And I did try using it too but the result is the same. I create the database with the the Windows User and not with the 'sa' one
NOTE: If I am to run the code with a DataSource=(local) in the connection string it works.
NOTE: Database is in READ_WRITE mode
What I have tried:
I tried recreating the table and the whole database
I tried reinstalling SQL Server Express
I tried add features to Windows, particularly Internet Information Services -> World Wide Web Services -> Security -> Windows Authentication/Basic Authentication
I tried manipulating the rights of the user I am using but it is a dbo so there should be no problem.
I tried running the same code on a different machine (With the same Microsoft account)*
I tried setting tried to set FILESTREAM( NON_TRANSACTED_ACCESS = FULL )
** I know that FileStream is working only with Windows Authentication and I am using windows 8 so everything is the same (or at least should be) in terms of accounts**
Am I missing something?
The fact that you get a Win32Exception, not a SqlException, indicates that the issue occurs when you open the FILESTREAM. There are a number of steps you need to take to ensure remote FILESTREAM access via Win32 API (which is what you try to do). the important changes are to enable the Firewall on the server for port 445 (see Configure a Firewall for FILESTREAM Access) and (most importantly) configure the server to Allow remote clients to have streaming access to FILESTREAM data. SQL configuration filestream access level must be set to 2.
I also recommend going through the Filestream Storage whitepaper, if you still have problems. I've seen cases of mysterious FILESTREAM access denied errors ultimately being diagnosed as administrators messing with the filestream shared folders storage permissions.
I hope you already understand that FILESTREAM can only be accessed using integrated security. Integrated security must be used to obtain the handle path/context (your SELECT statement) and also will be used behind the scenes when using the Win32 API access (ie. when you try to open the SqlFileStream object).
If I am to run the code with a DataSource=(local) in the connection string it works.
Because this works and using the IP Address does not, I suspect SQL Server is treating your connection as a remote connection instead of local.
Open SQL Server Configuration Manager. Select SQL Server Services. Locate the SQL Server instance you are using, right click and select Properties. On the FILESTREAM tab, select Allow remote clients access to FILESTREAM data.
If I am correct, that will solve your issue.
Try using reader.GetSqlBytes(1).Value instead of reader.GetSqlBytes(1).Buffer. The buffer size isn't always the same as the value size. The buffer may contain garbage after the real data. By using the buffer, you may specify an invalid context.
You might have a delegation problem.
Assuming the following machine layout:
clientPC - the machine running your software
sqlSrv - your SQL-Server
fStream - the machine with the filestream-share
You are working with integrated security, so clientPC is using Kerberos for authentication against sqlSrv. Then sqlSrv tries to authenticate the user for access to fStream, but fails.
This might be a Kerberos delegation scenario and you have to meet some requirements to allow that.
The service account, which runs your SQL Server process must be trusted for delegation (or constraint delegation). The delegation has probably to be allowed to the CIFS/fStream ServicePrincipalName.
Kerberos Constraint Delegation: http://technet.microsoft.com/en-us/library/jj553400.aspx
Some screens about Delegation: http://blogs.msdn.com/b/autz_auth_stuff/archive/2011/05/03/kerberos-delegation.aspx
Infos about ServicePrincipalNames: http://blogs.iis.net/brian-murphy-booth/archive/2007/03/09/the-biggest-mistake-serviceprincipalname-s.aspx
I imagine this Win32Exception was raised and handled within the WPF application stack?
You can experience this many times when debugging WPF applications, because it makes API calls and it could fail or handle the exception and continue the processing.

Unhandled exception of type System.Exception occurred in FM.dll

I'm using WebSync in a .NET application where a client is making calls to connect, subscribe, etc to WebSync. Somewhere along the execution of the code (It's a big app), I get the gray box popup saying the above error message. Because this is a big app, how can I find where in the application this is occurring? The problem is that this application has a lot of threads.
Does this message mean there is a problem in FM.dll (WebSync) or does it mean that I'm missing something in my code that should catch this exception. If the latter, how do I find where in my code this may occur?
Thanks!
Here is the Call Stack to my error. How can I tell if this is an error on my part or if the problem is inside FM.dll (WebSync)?
FM.dll!FM.AsyncException.AsyncThrow.AnonymousMethod__0(object unused) + 0x47 bytes
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x285 bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x9 bytes
mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() + 0x6f bytes
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() + 0x1ea bytes
[Native to Managed Transition]
[Appdomain Transition]
[Native to Managed Transition]
If you have 'Break on All Exceptions' turned on then once you start the debugger, when the exception is thrown, you'll be able to see and navigate the stack trace. This should give you an idea of the path the code is on leading up to the exception. You can also interrogate the exception to check to see if the InnerException property has been set. From that information you should be able to determine what is causing the issue. If not post more details from the information you gather and you can get more help.
Instruction for setting up Visual Studio to break on all exceptions: http://msdn.microsoft.com/en-us/library/d14azbfh.aspx
In FM libraries, AsyncException.AsyncThrow is used when an exception is thrown in an async callback. Try wrapping your FM callback code in try/catch blocks to catch exceptions, e.g.:
client.Connect(new ConnectArgs
{
OnSuccess = (e) =>
{
try
{
// your code
}
catch (Exception ex)
{
// handle exception
}
}
});
If you don't wrap your callback code in a try/catch block, then the FM library will push the exception to a thread where it will be fail loudly rather than swallow/hide it.

IClientChannel antipattern

I've just spend 4 hours (it's 3am in the UK) trying to debug ASP.NET application which caused an exception in a thread managed by Framework (i.e. not my thread). I've just found out that a result from the static method ChannelFactory.CreateChannel can be cast to IClientChannel and explicitly Disposed. I mean that's all fine and nice but why:
1) ChannelFactory.CreateChannel does not return IClientChannel as an out parameter?
2) .Net documentation for CreateChannel does not mention it?
3) .Net documentation does not show a proper usage pattern in examples (no dispose code)?
Don't get me wrong - I love .Net framework. Microsoft (and Krzysztof Cwalina: see Designing Framework Guidelines) has done a really great job. That's why I didn't expect a such disaster. I mean how the hell I should know that my IMyService variable also supports IClientChannel and I should explicitly dispose it?
Here is an ASP.NET log if someone is interested.
Event Type: Error
Event Source: ASP.NET 2.0.50727.0
Event Category: None
Event ID: 1334
Date: 12/08/2009
Time: 01:55:47
User: N/A
Computer: WLGH3GIS
Description:
An unhandled exception occurred and the process was terminated.
Application ID: /LM/W3SVC/1/Root/Maps
Process ID: 3044
Exception: System.NullReferenceException
Message: Object reference not set to an instance of an object.
StackTrace: at System.Threading.Overlapped.Free(NativeOverlapped* nativeOverlappedPtr)
at System.ServiceModel.Channels.OverlappedContext.Free()
at System.ServiceModel.Channels.PipeConnection.CloseHandle(Boolean abort, String timeoutErrorString, TransferOperation transferOperation)
at System.ServiceModel.Channels.PipeConnection.Close(TimeSpan timeout)
at System.ServiceModel.Channels.BufferedConnection.Close(TimeSpan timeout)
at System.ServiceModel.Channels.ConnectionPool.CloseItem(IConnection item, TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationPool`2.EndpointConnectionPool.CloseItem(TItem item, TimeSpan timeout)
at System.ServiceModel.Channels.IdlingCommunicationPool`2.IdleTimeoutEndpointConnectionPool.CloseItem(TItem item, TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationPool`2.EndpointConnectionPool.CloseIdleConnection(TItem connection, TimeSpan timeout)
at System.ServiceModel.Channels.IdlingCommunicationPool`2.IdleTimeoutEndpointConnectionPool.IdleTimeoutIdleConnectionPool.OnIdle()
at System.ServiceModel.Channels.IdlingCommunicationPool`2.IdleTimeoutEndpointConnectionPool.IdleTimeoutIdleConnectionPool.OnIdle(Object state)
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
at System.Security.SecurityContext.Run(SecurityContext securityContext, ContextCallback callback, Object state)
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)
at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Karol, I know this is a bit old, but I wanted to say thank you. Your post really helped me out.
The symptom I had was that when I tried to Close a ChannelFactory on the Server, it would always give a Timeout, regardless of the length of timespan I set for OpenTimeout, ReceiveTimeout, SendTimeout, InactivityTimeout, or CloseTimeout.
The solution was actually on the client, to cast the IMyServiceInterface that was returned by ChannelFactory.CreateChannel to ICommunicationObject. Then, it can be passed nicely to the Util.SafeCloseAndDispose(ICommunicationObject) method that you see copy and pasted all over the web.
After I did that on my client, then the Server's ChannelFactory can be closed in only a second or two, with no more timeout.
As far as I know, this insight from Karol's post is one of the only places online where this problem is spelled out.
Thanks again, Karol! :)

Categories

Resources