I'm trying to repeat following Autodesk Example:
http://help.autodesk.com/view/RVT/2016/ENU/?guid=GUID-CEF0F9C9-046E-46E2-9535-3B9620D8A170
I am getting a complete crash of revit when i start the addin. In debugging mode visual studio point this line: "TaskDialogResult result = taskDialog.Show();" - An unhandled exception of type 'System.StackOverflowException' occurred in RevitAPIUI.dll
public class Application_DialogBoxShowing : IExternalApplication
{
// Implement the OnStartup method to register events when Revit starts.
public Result OnStartup(UIControlledApplication application)
{
// Register related events
application.DialogBoxShowing +=
new EventHandler<Autodesk.Revit.UI.Events.DialogBoxShowingEventArgs>(AppDialogShowing);
return Result.Succeeded;
}
// Implement this method to unregister the subscribed events when Revit exits.
public Result OnShutdown(UIControlledApplication application)
{
// unregister events
application.DialogBoxShowing -=
new EventHandler<Autodesk.Revit.UI.Events.DialogBoxShowingEventArgs>(AppDialogShowing);
return Result.Succeeded;
}
// The DialogBoxShowing event handler, which allow you to
// do some work before the dialog shows
void AppDialogShowing(object sender, DialogBoxShowingEventArgs args)
{
// Get the help id of the showing dialog
int dialogId = args.HelpId;
// Format the prompt information string
String promptInfo = "A Revit dialog will be opened.\n";
promptInfo += "The help id of this dialog is " + dialogId.ToString() + "\n";
promptInfo += "If you don't want the dialog to open, please press cancel button";
// Show the prompt message, and allow the user to close the dialog directly.
TaskDialog taskDialog = new TaskDialog("Revit");
taskDialog.MainContent = promptInfo;
TaskDialogCommonButtons buttons = TaskDialogCommonButtons.Ok |
TaskDialogCommonButtons.Cancel;
taskDialog.CommonButtons = buttons;
TaskDialogResult result = taskDialog.Show();
if (TaskDialogResult.Cancel == result)
{
// Do not show the Revit dialog
args.OverrideResult(1);
}
else
{
// Continue to show the Revit dialog
args.OverrideResult(0);
}
}
}
Use "MessageBox" instead of "TaskDialog".
Calling "TaskDialog" inside AppDialogShowing leads to overflow.
Related
I am new to Server Sent Events but not to Spring.
Have made a controller which gets triggered from a button on the UI which initiates SSEEmitter and passed that to another thread which in loop sends message to UI after each 4 seconds.
SO far i am running a loop of 10 which sleeps for 4 seconds each but suddenly around iteration of 6 or 7th loop, I get exception "Exception in thread "Thread-4" java.lang.IllegalStateException: ResponseBodyEmitter is already set complete"..
Hence, event source again re-establishes the connection i.e. calls the controller method again which certainly i do not want.
I am here trying a simple thing.. User subscribes by clicking on the button..
Server send response 10 or 20 whatever times to the browser. And as far as I think this is what SSE created for.
Code below.:
#RequestMapping("/subscribe")
public SseEmitter subscribe() {
SseEmitter sseEmitter = new SseEmitter();
try {
sseEmitter.send("Dapinder");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Runnable r = new AnotherThread(sseEmitter);
new Thread(r).start();
return sseEmitter;
}
public class AnotherThread implements Runnable {
private SseEmitter sseEmitter;
public AnotherThread(SseEmitter sseEmitter) {
super();
this.sseEmitter = sseEmitter;
}
#Override
public void run() {
SseEventBuilder builder = SseEmitter.event();
builder.name("dapEvent");
for (int i = 0; i < 10; i++) {
builder.data("This is the data: " + i +" time.");
try {
//sseEmitter.send(builder);
sseEmitter.send("Data: "+i);
//sseEmitters.get(1L).send("Hello");
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sseEmitter.complete();
}
public SseEmitter getSseEmitter() {
return sseEmitter;
}
public void setSseEmitter(SseEmitter sseEmitter) {
this.sseEmitter = sseEmitter;
}
}
function start() {
var eventSource = new EventSource("http://localhost:8080/HTML5SSE/springSSE/subscribe"); // /springSSE/connect
eventSource.onmessage = function(event) {
document.getElementById('foo').innerHTML = event.data;
};
}
<button onclick="start()">Subscribe</button>
Your builder is not being used; you create and configure a builder, but then you send a plain message with 'sseEmitter.send' directly. Try this:
sseEmitter.send(SseEmitter.event().name("dapEvent").data("This " + i +" time.");
One more thing: Why do you call the send method already in the subscribe method? At this point in time, the SseEmitter has not been returned. Is this message coming through to the client?
Here is an excellent article explaining SSE from the JavaScript perspective (not Spring). You will see here that you can cancel the event stream from the client by calling close on the stream. Combine this with an event listener, and you should have what you need:
var source = new EventSource('...');
source.addEventListener('error', function(e) {
if (e.currentTarget.readyState == EventSource.CLOSED) {
// Connection was closed.
} else {
// Close it yourself
source.close();
}
});
source.addEventListener('message', function(e) {
console.log(e.data);
});
Note: The article says e.readyState, however I think this is wrong. The received object e is an Event. You need to get the EventSource object from it like this: e.currentTarget.
You need to use the second constructor of SseEmitter which takes a Long timeout argument. Please refer the code below -
#RequestMapping("/subscribe")
public SseEmitter subscribe() {
SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE) // for maximum timeout
Below is the copy of Java-doc of this constructor -
/**
* Create a SseEmitter with a custom timeout value.
* <p>By default not set in which case the default configured in the MVC
* Java Config or the MVC namespace is used, or if that's not set, then the
* timeout depends on the default of the underlying server.
* #param timeout timeout value in milliseconds
* #since 4.2.2
*/
I think the default timeout of SSE connection in Tomcat is 40 seconds. Not sure though.
I develop an Universal App that uses MVVM-Light. I call WebServices from the ViewModels, and I throw the exceptions encountered by the calls at the WebServices to the ViewModels: TimeOut, Wrong URL, Server Exception, ...
I have created a class "ExceptionsMsgHelper.cs" which centralizes the messages displayed for each of these exceptions through MessageDialog.
My HomePage is based on a Pivot that containing several datas: some WebServices are called asynchronously. I so meet a crash if I show an Exception in a MessageDialog through the class "ExceptionsMsgHelper.cs", whereas a previous Exception is also showed in another MessageDialog.
Here is a part of my original class:
public class ExceptionsMsgHelper
{
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
await msgbox.ShowAsync();
}
}
=> If I call twice the "msgbox.ShowAsync()", I get the "System.UnauthorizedAccessException" Exception: with message "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
I've so looked for solutions in order to fix it:
use a "Dispatcter", like it is recommended here (WinRT - MessageDialog.ShowAsync will throw UnauthorizedAccessException in my custom class)
The code is:
public class ExceptionsMsgHelper
{
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await msgbox.ShowAsync();
});
}
}
=> But I always meet the same exception.
use a "IAsyncOperation" command to close the previous MessageDialog, like recommended here (MessageDialog ShowAsync throws accessdenied exception on second dialog)
With this code:
public class ExceptionsMsgHelper
{
private static IAsyncOperation<IUICommand> messageDialogCommand = null;
public async static Task<bool> ShowDialog(MessageDialog dlg)
{
// Close the previous one out
if (messageDialogCommand != null)
{
messageDialogCommand.Cancel();
messageDialogCommand = null;
}
messageDialogCommand = dlg.ShowAsync();
await messageDialogCommand;
return true;
}
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await ShowDialog(msgbox);
});
}
}
=> But in this case too, I always get the same exception.
use an extension to queue up messagedialogs, like describing here (Multiple MessageDialog app crash)
The code is now:
public class ExceptionsMsgHelper
{
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
await MessageDialogExtensions.ShowAsyncQueue(msgbox);
}
}
public static class MessageDialogExtensions
{
private static TaskCompletionSource<MessageDialog> _currentDialogShowRequest;
public static async Task<IUICommand> ShowAsyncQueue(this MessageDialog dialog)
{
if (!Window.Current.Dispatcher.HasThreadAccess)
{
throw new InvalidOperationException("This method can only be invoked from UI thread.");
}
while (_currentDialogShowRequest != null)
{
await _currentDialogShowRequest.Task;
}
var request = _currentDialogShowRequest = new TaskCompletionSource<MessageDialog>();
var result = await dialog.ShowAsync();
_currentDialogShowRequest = null;
request.SetResult(dialog);
return result;
}
private static IAsyncOperation<IUICommand> messageDialogCommand = null;
public async static Task<bool> ShowDialog(this MessageDialog dlg)
{
// Close the previous one out
if (messageDialogCommand != null)
{
messageDialogCommand.Cancel();
messageDialogCommand = null;
}
messageDialogCommand = dlg.ShowAsync();
await messageDialogCommand;
return true;
}
#endregion
}
=> And this works for me.
But like says it's author, it's probably not the best solution:
Close existing dialog when you need to open a new one. This is the simplest option and possibly the best, although you risk cancelling a dialog that might be somehow important depending on what your dialogs are about.
Queue up dialogs so the old ones don't get dismissed, but the new ones show up after the old ones were dismissed. This one will make sure all dialogs are closed by the user, but that could be a problem if your app can somehow start showing hundreds of dialogs.
Only open a new one if there isn't one already displayed. Now this risks that a newer message is not shown, which sounds more problematic than the first option.
=> I would like to understand why I can't apply one the 2 first solutions that seems to be more adapted
Ofcourse you can't show 2 or more message dialog at the same time (windows phone limits). Moreover MesssageDialog on Windows Phone 8.1 has probably bug and can't be closed.
If closing previous dialog will be solution for you, try to use ContentDialog instead MessageDialog. Check my answer in this topic: Closing MessageDialog programatically in WP 8.1 RT
I think it solve your problem.
I am developing a wp8 application and the need is the above:
My server sends some raw push notifications that i can handle in my mainpage successful. But i have more pages so i need my app continue to get and handle notifications when the user is on the other pages.
As far i have tried to add the same code as i have put in the main page to handle notifications
string channelName = "test";
pushChannel = HttpNotificationChannel.Find(channelName);
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
//pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.Open();
// Bind this new channel for toast events.
//pushChannel.BindToShellToast();
System.Threading.Thread.Sleep(3000);
channel = pushChannel.ChannelUri.ToString();
cSettings.device_notify_id = channel;
}
else
{
// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
// pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
System.Threading.Thread.Sleep(3000);
channel = pushChannel.ChannelUri.ToString();
cSettings.device_notify_id = channel;
// Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
}
and the handlers methods
void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
cSettings.device_notify_id = e.ChannelUri.ToString();
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
});
}
void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
cSettings set = new cSettings();
set.LogEx(new Exception((String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))));
// Error handling logic for your particular application would be here.
Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
);
}
void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
string message;
VibrationDevice vibr = VibrationDevice.GetDefault();
vibr.Vibrate(TimeSpan.FromSeconds(3));
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
cSettings set = new cSettings();
string n_type = "";
string n_header = "";
//var obj = set.parse_stringfromnotify(message, ref n_type, ref n_header);
Dispatcher.BeginInvoke(() => nofication_received_action(message, n_type, ""));
}
private void nofication_received_action(string n_header, string n_type, object data)
{
MessageBoxResult result;
CallSrvData cdata = new CallSrvData();
Exception ex = null;
WP_MemberData m;
WP_MemberRules wpmr;
cSettings set;
MemberRules mr;
Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
Rules c_rules;
Notify.data = data;
Notify.msg_box_text = String.Format("{0}", n_header);
//dose k data sth forma
toast = new Microsoft.Phone.Shell.ShellToast();
toast.Content = "Invitation received";
toast.Title = "Title : ";
//SetProperty(toast, "Sound", new Uri("/data/alert.mp3", UriKind.Relative));
toast.NavigationUri = new Uri("/forms/Notify.xaml?type=0", UriKind.Relative);
toast.Show();
}
When the app is in background and i successfully get the notification and navigate to Notify.xaml the mechanism works fine, but when i go back or i press start button to leave from Notify.xaml and i resend a notification nothing happens. I have tried to add the same code and in Notify.xaml but again nothing happen when i send notification. In comparison with android where you just register listeners once in your app and then you can receive notification in in any page even the app is "closed" who can i succeed something like that or can i succeed something like that?
Thx a lot for your contribution.
I have found that i can create all the notification functionality in a class which will initialize on app.cs or any time is needed.
Is there a way to authenticate a user through Facebook in mvvmcross framework? I'm currently attempting use Mobile Azure Service to authenticate to Facebook, but I don't have any success. Without using mvvmcross, I can authenticate just fine.
Thank You!
Mark
In the MVVM sense what I've found is that no, you can not. Properties on the facebook login page are not bindable, nor should they be and is best treated as a modal view out of your control
What I would do is make it a view concern and use Xamarin.Auth to authenticate.
As an example let's say that you had a LoginView and LoginViewModel.
The LoginView provides your standard login Email/Password but with an option (button) to authenticate via facebook
From that view hook up to the touchupinside event of the facebooklogin button
this.btnFacebookLogin.TouchUpInside += (object sender, EventArgs e) =>
{
DoFacebookLogin ();
}
Then in your DoFacebookLogin method 'present' the viewcontroller for facebook as described here https://github.com/xamarin/Xamarin.Auth/blob/master/GettingStarted.md
For example :
private void DoFacebookLogin ()
{
var auth = new OAuth2Authenticator (
clientId: "yournumericclientidhere",
scope: "",
authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));
auth.AllowCancel = true;
auth.Completed += (sender, eventArgs) => {
DismissViewController (false, null);
if (eventArgs.IsAuthenticated) {
string user = eventArgs.Account.Serialize ();
var messenger = Mvx.Resolve<IMvxMessenger> ();
messenger.Publish (new FacebookLoggedIn (user));
} else {
// Cancelled here
}
};
var vc = auth.GetUI ();
this.PresentViewController (vc, true, null);
}
Cancelled does not need to be handled since the modal viewcontroller will take you back to your LoginView
On success that viewcontroller is dismissed then I would use mvx's interpretation of an eventaggregator (plugins.messenger) to send a message to the viewmodel that the facebook modal view is closed, with that message you can pass the account details - accesstoken etc back to the viewmodel to do as you wish.
View (as above) :
string user = eventArgs.Account.Serialize();
var messenger = Mvx.Resolve<IMvxMessenger> ();
messenger.Publish (new FacebookLoggedIn (user));
Message Class in your PCL :
public class FacebookLoggedIn : MvxMessage
{
public FacebookLoggedIn(object sender) : base(sender) {}
}
ViewModel also in your PCL :
public LoginViewModel()
{
var messenger = Mvx.Resolve<IMvxMessenger> ();
user = messenger.SubscribeOnMainThread<FacebookLoggedIn> (OnFacebookLoggedIn);
}
private void OnFacebookLoggedIn (FacebookLoggedIn MvxMessage)
{
... do something with the accesstoken? call your IUserService etc
ShowViewModel<MainViewModel> ();
}
Since you're dismissing the facebook viewcontroller you'll find yourself back on the loginview momentarily before automatically navigating to the MainView
In your view project you need to ensure the plugin is loaded otherwise you'll receive an error during construction of the viewmodel, so in setup.cs
protected override void InitializeLastChance ()
{
Cirrious.MvvmCross.Plugins.Messenger.PluginLoader.Instance.EnsureLoaded();
base.InitializeLastChance ();
}
Additionally you can also store the account credentials locally, this is described on the Xamarin.Auth link under AccountStore.Create().Save. Note that if you receive a platform not supported exception then add PLATFORM_IOS as a preprocessor directive to your project.
I realise the question is a couple of months old but since it rates high on google thought I'd provide an answer since there isn't any
I have a frame which has a function that updates the frame when an event in another class is raised.
I have the class 'IRCClient' and 'MainFrame'. The IRCClient class has an event 'OnMessageRecvd', the MainFrame has a function 'HandleNewMessageReceived'. In the MainFrame class I have the variables 'CurrentServer' and 'CurrentChannel' to indicate what channel on what server is currently shown to the user.
Now, when I set the 'CurrentServer' and 'CurrentChannel' in the callback of a button, they have a value and all is fine. However, when the 'HandleNewMessageReceived' function is called by the 'OnMessageRecvd' event of IRCClient, the CurrentServer and CurrentChannel are both equal to any value (null) stated in the constructor of MainFrame.
Does anyone have an idea what the source of this behavior is? Thanks a lot in advance.
EDIT:
Below is the code, I've only posted the code in question (any function that uses the CurrentChannel and CurrentServer properties) and snipped away unrelated code.
// Main page, shows chat history.
public sealed partial class MainPage : LIRC.Common.LayoutAwarePage
{
private uint maxMessages;
IRCClient ircc;
IRCHistory irch;
string CurrentServer, CurrentChannel;
// Does all the setup for this class.
public MainPage()
{
this.InitializeComponent();
ircc = App.ircc; // This is a global variable in the 'App' class.
ircc.OnMessage += NewMessageReceived;
irch = App.irch; // This is also a global variable in the 'App' class.
currentChannel = currentServer = null;
}
// Restores the previous state.
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
if (pageState != null)
{
if(pageState.ContainsKey("viewedChannel"))
{
// Retrieve required info.
string[] viewedChannelTokens = (pageState["viewedChannel"] as string).Split('.');
CurrentChannel = viewedChannelTokens[0];
CurrentServer = viewedChannelTokens[1];
// If the saved channel or server got corrupt
if (string.IsNullOrEmpty(CurrentChannel) || string.IsNullOrEmpty(CurrentServer))
{
// Check if a channel is open, if so, select it.
*snip* // Non-relevant code.
}
// Clear and load required history.
ClearHistory();
if(CurrentServer != null && CurrentChannel != null)
LoadHistory(CurrentServer, CurrentChannel);
}
}
// Create buttons that switch to a channel
*Snip* // Calls AddChannelButton
}
// Creates a button that, when clicked, causes the ChatHistoryView to display the ChannelHistory.
void AddChannelButton(string Server, string Channel)
{
Button btn = new Button();
btn.Content = Channel + "\n" + Server;
btn.Width = 150;
// A function to switch to another channel.
btn.Click += (e, s) =>
{
ClearHistory(); // Clears the ChatHistoryVi.ew field.
LoadHistory(Server, Channel); // Does the actual loading of the channel history
CurrentChannel = Channel;
CurrentServer = Server;
};
ChannelBar.Children.Add(btn);
}
// The function that is called by the IRCClient.OnMessageRecv event.
public void NewMessageReceived(ref DataWriter dw, IRCServerInfo ircsi, IRCClient.RecvMessage recvmsg)
{
if (ircsi.Name == CurrentServer && CurrentChannel == recvmsg.recipient)
{
AddMessage(DateTimeToTime(DateTime.UtcNow), recvmsg.author, recvmsg.message);
}
}
}
// Responsible for creating, managing and closing connections.
public class IRCClient
{
// A structure that describes a message.
public struct RecvMessage
{
public string author; // Nickname
public string realName;
public string ipAddress;
public string recipient; // Indicates in what channel or private converstion.
public string message; // The actual message
};
// Describes how a function that handles a message should be declared.
public delegate void MessageHandler(ref DataWriter dw, IRCServerInfo ircsi, RecvMessage msg);
// Gets raised/called whenever a message was received.
public event MessageHandler OnMessage;
}
It's not clear what is happening from what you said, but if the variables are set to the values you set in the constructor when you check them - it means that either you have not changed them yet by the time you are expecting them to be changed or you set the value of some other variables instead of the ones you thought you had.
These are only guesses though and you can't expect more than guesses without showing your code.