I'm following this tutorial, and I keep getting an exception calling QueueClient.Send().
First off, here's my connection string setting in the App.Config (with {computername} replaced by the actual machine name):
<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://{computername}/ServiceBusDefaultNamespace;StsEndpoint=https://{computername}:9355/ServiceBusDefaultNamespace;RuntimePort=9354;ManagementPort=9355" />
Here's the code I'm running:
NamespaceManager namespaceManager = NamespaceManager.Create();
TokenProvider nameSpaceManagerTokenProvider = TokenProvider.CreateWindowsTokenProvider(
new List<Uri>() { namespaceManager.Address }, new NetworkCredential(user, password));
TokenProvider messagingToken = TokenProvider.CreateWindowsTokenProvider(
new List<Uri>() { namespaceManager.Address }, new NetworkCredential(user, password));
namespaceManager.Settings.TokenProvider = nameSpaceManagerTokenProvider;
MessagingFactorySettings messageFactorySettings = new MessagingFactorySettings {TokenProvider = messagingToken};
MessagingFactory messagingFactory = MessagingFactory.Create(namespaceManager.Address, messageFactorySettings);
if (namespaceManager.QueueExists(QueueName))
{
namespaceManager.DeleteQueue(QueueName);
}
QueueDescription qd = new QueueDescription(QueueName);
namespaceManager.CreateQueue(qd);
QueueClient myQueueClient = messagingFactory.CreateQueueClient(QueueName);
BrokeredMessage sendMessage = new BrokeredMessage("Hello, World!");
myQueueClient.Send(sendMessage); // <---- This is where I'm getting the exception
The queue is deleted/created without a problem. Calling the .Send() method gives me the following error:
Microsoft.ServiceBus.Messaging.MessagingCommunicationException
"The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9579976'."
The inner exception is simply "An existing connection was forcibly closed by the remote host"
Here's the stack trace:
at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.EndSendCommand(IAsyncResult result)
at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.OnEndSend(IAsyncResult result)
at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.OnSend(TrackingContext trackingContext, IEnumerable`1 messages, TimeSpan timeout)
at Microsoft.ServiceBus.Messaging.MessageSender.Send(TrackingContext trackingContext, IEnumerable`1 messages, TimeSpan timeout)
at Microsoft.ServiceBus.Messaging.MessageSender.Send(BrokeredMessage message)
at Microsoft.ServiceBus.Messaging.QueueClient.Send(BrokeredMessage message)
at SBDemo.Program.Main(String[] args) in c:\Users\hartez\Documents\bitbucket\SBDemo\SBDemo\Program.cs:line 51
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
I'm currently running both the client code and the Service Bus on a Windows 7 64-bit dev box. I originally ran Service Bus on a 2012 Server machine and had the same problem.
The problem occurs with both the WindowsTokenProvider and the OauthTokenProvider. The user account is an administrator (in hopes that this was just a permissions issue); that doesn't seem to help. I've also tried this with the Windows Firewall deactivated, but that didn't help, either.
I enabled the Analytic and Debug logs in the Event Viewer, but I'm not seeing an anything in those logs to suggest what the problem might be.
If anyone has any suggestions on what might be wrong, or on other ways to debug this, I'd very much appreciate it.
Glad you have figured this out.
MessagingFactory messagingFactory = MessagingFactory.Create(namespaceManager.Address, messageFactorySettings);
The issue you had in your original code is that it is using the NamespaceManager address for the MessagingFactory. The MessagingFactory uses a different port than the NamespaceManager.
NamespaceManager is used for management (CRUD) operations and SB has a management endpoint for it.
MessagingFactory is used for runtime operations (Send/Receive/..) and SB has a runtime endoiunt for it.
QueueClient.Create(QueueName) internally creates a messaging factory and uses the default address and port for runtime operations.
Finally figured this out, putting this here so anyone else in the same boat can avoid wrestling with this problem:
Apparently, the problem is somewhere in the use of MessagingFactory in the examples. I'm not really sure what it's even for (maybe handling things like AMQP, which isn't really supported by Service Bus yet?), but you don't need it. You can create the client using QueueClient.Create(). I revised the code to look like this, and now it works just fine:
NamespaceManager namespaceManager = NamespaceManager.Create();
TokenProvider nameSpaceManagerTokenProvider = TokenProvider.CreateWindowsTokenProvider(
new List<Uri>() { namespaceManager.Address }, new NetworkCredential(user, password));
namespaceManager.Settings.TokenProvider = nameSpaceManagerTokenProvider;
if (namespaceManager.QueueExists(QueueName))
{
namespaceManager.DeleteQueue(QueueName);
}
QueueDescription qd = new QueueDescription(QueueName);
namespaceManager.CreateQueue(qd);
QueueClient myQueueClient = QueueClient.Create(QueueName);
BrokeredMessage sendMessage = new BrokeredMessage("Hello, World!");
myQueueClient.Send(sendMessage);
Related
I'm trying to do messaging between programs on separate computers on a local network. The design is basically one "server," multiple "clients," with the server sending messages to the clients and receiving messages from the clients, and the clients receiving messages from the server, and sending/receiving client messages between each other.
I'm trying to use NetMQ for this, but I'm having trouble getting it working on a network. I can run the server and client programs perfectly fine on a single machine, but I'm not sure how to get it to work on a network, and I can't find any NetMQ examples that show this--to be clear, every example I can find uses "localhost" or some other IP address for both the "publisher" and "subscriber" (I'm using a Pub-Sub pattern, but I've seen the same regardless of the pattern used in the example).
Some example code using the client-client framework (this requires an XPub-XSub framework because there are multiple publishers and subscribers):
NetMQPoller poller = new NetMQPoller();
PublisherSocket clientPub = new PublisherSocket("tcp://*:4444");
XPublisherSocket xPub = new XPublisherSocket("tcp://*:5555");
XSubscriberSocket xSub = new XSubscriberSocket("tcp://*:4444");
Proxy proxy = new proxy(xSub, xPub, poller: poller);
proxy.Start();
SubscriberSocket clientSub = new SubscriberSocket("tcp://*:5555");
poller.Add(clientSub);
poller.Add(clientPub);
poller.RunAsync();
If I run this, I get "the application is in break mode" with the following error:
NetMQ.NetMQException HResult=0x80131500 Source=NetMQ StackTrace:
at NetMQ.Core.Transports.Tcp.TcpConnector.OutCompleted(SocketError
socketError, Int32 bytesTransferred) at
NetMQ.Core.IOObject.OutCompleted(SocketError socketError, Int32
bytesTransferred) at NetMQ.Core.Utils.Proactor.Loop() at
System.Threading.ThreadHelper.ThreadStart_Context(Object state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
If I change the clientSub's address to "tcp://127.0.0.1:5555" it starts fine. However, that won't work because the subscriber needs to receive messages from any machine on the network.
How do I do this with NetMQ? Can anyone provide a working example of this?
By default when you use the constructor of a socket is either bind or connect, depends on the socket type. publisher bind (listen)and subscriber connects. So it does make sense to use * for the subscriber.
You are using tcp transport, so you have to specify an ip address of the remote peer when connecting. If you want to connect to multiple publishers you can either call connect or provide s string with multiple addresses separated by comma.
Bottom line instead of *, localhost or 127.0.0.1 use the ip address of the publisher machine.
You can use the # or > prefixes to override the defaults of the constructor. # to bind and > to connect.
NetMQPoller poller = new NetMQPoller();
PublisherSocket clientPub = new PublisherSocket(">tcp://192.168.0.15:4444");
XPublisherSocket xPub = new XPublisherSocket("#tcp://*:5555");
XSubscriberSocket xSub = new XSubscriberSocket("#tcp://*:4444");
Proxy proxy = new proxy(xSub, xPub, poller: poller);
proxy.Start();
SubscriberSocket clientSub = new SubscriberSocket(">tcp://192.168.0.15:5555");
poller.Add(clientSub);
poller.Add(clientPub);
poller.RunAsync();
192.168.0.15 is my ip address. You need to change it to your ip.
I have a simple example. My "server" code runs on a Amazon EC2 instance. It listens on port 11000 and responds to a single message.
using System;
using NetMQ;
using NetMQ.Sockets;
class Program
{
private static void Main()
{
using (var server = new ResponseSocket("#tcp://*:11000"))
{
// the server receives, then sends
Console.WriteLine("From Client: {0}", server.ReceiveFrameString());
server.SendFrame("Hi Back");
Console.ReadKey();
}
}
}
My Client code runs on my PC:
using System;
using NetMQ;
using NetMQ.Sockets;
class Program
{
private static void Main()
{
using (var client = new RequestSocket(">tcp://3.13.186.250:11000"))
{
client.SendFrame("Hello");
Console.WriteLine("From Server: {0}", client.ReceiveFrameString());
Console.ReadKey();
}
}
}
I'm encountering a very strange bug which appears only when compiling in Release mode, while in Debug mode the code runs perfectly. Moreover, the bug is encountered only in one machine (a user reported this).
This is the stack trace:
System.IO.FileNotFoundException: Unable to find file 'C:\Users...\FileName.txt'.
File name: 'C:\Users...\FileName.txt'
in System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
in System.IO.FileInfo.get_Length()
in PatcherNET4.FileHandler.LocalFile.get_Size()
in PatcherNET4.FileHandler.CachedFile.IsLocalValid(LocalFile file)
in PatcherNET4.FileHandler.FileManager.<>c__DisplayClassd.b__9(CachedFile file)
in System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source, Func2 predicate)
in PatcherNET4.FileHandler.FileManager.RemoveLocalFiles()
in PatcherNET4.FileHandler.FileManager.DownloadMissingFiles()
in System.Threading.ThreadHelper.ThreadStart_Context(Object state)
in System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
in System.Threading.ThreadHelper.ThreadStart()
And this is the code:
// CachedFile
...
public bool IsLocalValid(LocalFile file)
{
var checkName = file.Name == Name;
var checkSize = file.Size == Size;
var checkLastWrite = file.LastWriteTime == LastWriteTime;
return checkName && checkSize && checkLastWrite;
}
...
//LocalFile
...
public uint Size
{
get
{
_info.Refresh();
return (uint)_info.Length;
}
}
...
How is this possible? I can assure you that there is no difference in the interested pieces of code between the release and debug mode. I don't really know what to do, this is probably the strangest bug I've ever seen.
put FileName.txt in the Unable to find file 'C:\Users...\(here) directory
The first thing I'd try is to verify the file exists at runtime and go from there.
if (!File.Exists(fileName))
{
// do something
}
If the file doesn't exist (I believe you when you say it's missing) then consider the alternatives. Has the file been deleted already? I notice in the stacktrace there's RemoveLocalFiles, so perhaps it's already been run. Maybe a user pressed a button twice? race condition. Separate thread? User is logged in on two machines and has roaming profiles. Or something like that.
Regardless of whether it's a bug or not, it's better to be defensive and include a check to make sure the file exists (or catch the exception if that's your preference).
I'm following this post and trying to run the code (copied below), and I'm having a slightly different problem. I can remote connect to the server and view the event log through the Event Viewer program, but I can't iterate through the events in the code. I get an InvalidOperationException saying "Cannot open log EventLogName on machine . Windows has not provided an error code." There is also an inner exception of type System.ComponentModel.Win32Exception that says "Access is denied."
private static bool GetEventLogData(DateTime start)
{
var log = new EventLog("EventLogName", "SERVER.domain.net");
bool errorFound = false;
foreach (EventLogEntry entry in log.Entries)
{
if ((entry.EntryType == EventLogEntryType.Error) &&
(entry.TimeGenerated >= start))
{
Console.WriteLine("Error in Event Log:\n" + entry.Message + "\n");
errorFound = true;
}
}
return errorFound;
}
Any ideas?
EDIT:
The exception data is as follows. I can't post the server name as it is company information. I receive the error when trying to read the event log. I am absolutely sure I can read the log because I can remote connect with my account and read the log using the Event Viewer.
System.InvalidOperationException was unhandled
Message=Cannot open log EventLogName on machine SERVER.domain.net. Windows has not provided an error code.
Source=System
StackTrace:
at System.Diagnostics.EventLogInternal.OpenForRead(String currentMachineName)
at System.Diagnostics.EventLogInternal.GetEntryAtNoThrow(Int32 index)
at System.Diagnostics.EventLogEntryCollection.EntriesEnumerator.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)
at MyApp.Program.GetEventLogData(String machineName, DateTime start) in c:\users\me\documents\visual studio 2010\Projects\MyApp\MyApp\Program.cs:line 45
at MyApp.Program.Main(String[] args) in c:\users\me\documents\visual studio 2010\Projects\MyApp\MyApp\Program.cs:line 28
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.ComponentModel.Win32Exception
Message=Access is denied
ErrorCode=-2147467259
NativeErrorCode=5
InnerException:
This is most likely a policy permission issue. See the Giving Non Administrators permission to read Event Logs Windows 2003 and Windows 2008 blog entry on TechNet. I was able to make your code work once I did this. In the case of Windows 2008 Server and higher, it's simply a matter of adding the user to the Event Log Readers local security group. Until I did that I was getting the same error.
I have a thread named fetchImage that runs startFetch() method, which is
for (int i = 0; !stopFetching && i < 2000; i++) {
control.fetchImage().Save("Fetch_Image\\fetchedFile" + fileName + ".JPG", System.Drawing.Imaging.ImageFormat.Jpeg);
fileName++;
//Thread.Sleep(800);
Console.WriteLine("Filename :" + fileName);
control is another class that has fetchImage() method:
return (System.Drawing.Bitmap)mainForm.imageTemp.Clone();
mainForm is a form that has Image variable named imageTemp. Now startFetch() runs fine when I have Thread.Sleep(800) but it gives me that error without the sleep. Here is the stack trace of the error
System.InvalidOperationException was unhandled
Message=Object is currently in use elsewhere.
Source=System.Drawing
StackTrace:
at System.Drawing.Image.Clone()
at KiPNi.Control.fetchImage() in F:\CMPS285\285-fall10-5\Final working code\WindowsFormsApplication7\Control.cs:line 65
at KiPNi.Form4.startFetch() in F:\CMPS285\285-fall10-5\Final working code\WindowsFormsApplication7\Form4.cs:line 80
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
I do not know much about threads (although I tried after encountering this problem).
How do I get access to the image from the fetchImage thread?
Instead of pulling data from the processing thread, see if it's possible to push data from the UI thread when there's a frame update - that way, you can possibly avoid locking; if you can create a clone of the image data, you avoid sharing the object between threads.
You really only should be invoking methods on UI controls from the main thread anyway (Control.BeginInvoke() exists, but it's better trying to modify your design to avoid it, if possible).
I have a vs2010 c# solution that was working fine yesterday.
When I try and run a debug instance today I keep getting an SEHException was unhandled.
This error is being thrown in the InitializeComponent method of the startup form.
Any Ideas?
Here's the stacktrace:
System.Runtime.InteropServices.SEHException was unhandled
Message=External component has thrown an exception.
Source=System.Drawing
ErrorCode=-2147467259
StackTrace:
at System.Drawing.SafeNativeMethods.Gdip.GdipCreateFontFromLogfontW(HandleRef hdc, Object lf, IntPtr& font)
at System.Drawing.Font.FromLogFont(Object lf, IntPtr hdc)
at System.Drawing.Font.FromHfont(IntPtr hfont)
at System.Drawing.SystemFonts.get_DefaultFont()
at System.Windows.Forms.Control.get_DefaultFont()
at System.Windows.Forms.Control.GetDefaultFontHandleWrapper()
at System.Windows.Forms.Control.get_FontHandle()
at System.Windows.Forms.ContainerControl.GetFontAutoScaleDimensions()
at System.Windows.Forms.ContainerControl.get_CurrentAutoScaleDimensions()
at System.Windows.Forms.ContainerControl.get_AutoScaleFactor()
at System.Windows.Forms.ContainerControl.PerformAutoScale(Boolean includedBounds, Boolean excludedBounds)
at System.Windows.Forms.ContainerControl.PerformNeededAutoScaleOnLayout()
at System.Windows.Forms.Form.OnLayout(LayoutEventArgs levent)
at System.Windows.Forms.Control.PerformLayout(LayoutEventArgs args)
at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.PerformLayout(IArrangedElement affectedElement, String affectedProperty)
at System.Windows.Forms.ContainerControl.LayoutScalingNeeded()
at System.Windows.Forms.ContainerControl.set_AutoScaleMode(AutoScaleMode value)
at FirstWindow.Form1.InitializeComponent() in C:\Users\Ash\Documents\Visual Studio 2010\Projects\FrameworkClientV2 - No Security\FirstWindow\Form1.designer.cs:line 32
at FirstWindow.Form1..ctor() in C:\Users\Ash\Documents\Visual Studio 2010\Projects\FrameworkClientV2 - No Security\FirstWindow\Form1.cs:line 27
at FirstWindow.Program.Main() in C:\Users\Ash\Documents\Visual Studio 2010\Projects\FrameworkClientV2 - No Security\FirstWindow\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
On a random note my gf broke my laptop screen last night so Im running on an external monitor... could this have anything to do with it?
Here's the code and the erroneous line..
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
///////////////////The line below throws the exception
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
///////////////////////////////
this.Text = "Form1";
}
This might be the same as the widely reported issue that started occurring yesterday. See
http://forums.asp.net/t/1704958.aspx/9/10?Re+SEHException+thrown+when+I+run+the+application
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0f78401b-77b2-4052-a26a-e98d2ec0afa9
Try uninstalling "Trusteer Rapport" if you have it on your machine
To be honest, the answer by zeroid did not fix my problem. So for the sake of completeness, I'd like to add that avira also caused such problems
http://forum.avira.com/wbb/index.php?page=Thread&threadID=123791
This problem can occurs when you load unmanaged functions (from DLL) in the main thread.
I fixed this problem by loading these unmanaged functions in a different thread than the main thread, you can for example use a BackgroundWorker.
I stumbled on this because I suddenly experienced the same problem. It's years after the OP and I'm using VS2015. My solution worked fine at work yesterday, with my laptop hooked up to an an external monitor. Today I'm working from home, and there is no extra monitor. I wouldn't have thought it relevant except for OP's comment about switching screen setup.