static void Main() { try { //http://covingtoninnovations.com/mc/SingleInstance.html bool gotMutex; //GUID is generated using the built-in VS capability System.Threading.Mutex m = new System.Threading.Mutex(true, "{6FE49292-F7B3-4EB7-B8F2-0CDDFE20B737}", out gotMutex); //http://covingtoninnovations.com/mc/SingleInstance.html if (gotMutex) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); GC.KeepAlive(m); } else { //http://www.codebetter.com/paullaudeman/2004/07/17/windows-forms-tip-ensure-only-one-instance-of-your-application-is-running-at-a-time/ // see if we can find the other app and Bring it to front //NOTE: the link referenced for this specifies a string for the first value, but //I ended up being able to just use the Window name IntPtr hWnd = NativeMethods.FindWindow(null, "OOFSponder"); if (hWnd != IntPtr.Zero) { NativeMethods.WINDOWPLACEMENT placement = new NativeMethods.WINDOWPLACEMENT(); placement.length = System.Runtime.InteropServices.Marshal.SizeOf(placement); NativeMethods.GetWindowPlacement(hWnd, ref placement); if (placement.showCmd != NativeMethods.SW_MINIMIZE) { placement.showCmd = NativeMethods.SW_RESTORE; NativeMethods.SetWindowPlacement(hWnd, ref placement); NativeMethods.SetForegroundWindow(hWnd); } } return; } } catch (Exception ex) { OOFSponderInsights.TrackException("Fatal error on startup", ex); MessageBox.Show("Uh oh! Fatal error for OOFSponder. Please try again."); return; } }
public async System.Threading.Tasks.Task <bool> TrySetOOF365(string oofMessageExternal, string oofMessageInternal, DateTime StartTime, DateTime EndTime) { OOFSponderInsights.TrackInfo(OOFSponderInsights.CurrentMethod()); toolStripStatusLabel1.Text = DateTime.Now.ToString() + " - Sending to O365"; //need to convert the times from local datetime to DateTimeTimeZone and UTC DateTimeTimeZone oofStart = new DateTimeTimeZone { DateTime = StartTime.ToUniversalTime().ToString("u").Replace("Z", ""), TimeZone = "UTC" }; DateTimeTimeZone oofEnd = new DateTimeTimeZone { DateTime = EndTime.ToUniversalTime().ToString("u").Replace("Z", ""), TimeZone = "UTC" }; //create local OOF object AutomaticRepliesSetting localOOF = new AutomaticRepliesSetting(); localOOF.ExternalReplyMessage = oofMessageExternal; localOOF.InternalReplyMessage = oofMessageInternal; localOOF.ScheduledStartDateTime = oofStart; localOOF.ScheduledEndDateTime = oofEnd; localOOF.Status = AutomaticRepliesStatus.Scheduled; try { OOFSponderInsights.Track("Getting OOF settings from O365"); string getOOFraw = await O365.GetHttpContentWithToken(O365.AutomatedReplySettingsURL); AutomaticRepliesSetting remoteOOF = JsonConvert.DeserializeObject <AutomaticRepliesSetting>(getOOFraw); OOFSponderInsights.Track("Successfully got OOF settings"); bool externalReplyMessageEqual = remoteOOF.ExternalReplyMessage.CleanReplyMessage() == localOOF.ExternalReplyMessage.CleanReplyMessage(); bool internalReplyMessageEqual = remoteOOF.InternalReplyMessage.CleanReplyMessage() == localOOF.InternalReplyMessage.CleanReplyMessage(); //local and remote are both UTC, so just compare times //Not sure it can ever happen to have the DateTime empty, but wrap this in a TryCatch just in case //set both to false - that way, we don't care if either one blows up //because if one is false, the overall evaluation is false anyway bool scheduledStartDateTimeEqual = false; bool scheduledEndDateTimeEqual = false; try { scheduledStartDateTimeEqual = DateTime.Parse(remoteOOF.ScheduledStartDateTime.DateTime) == DateTime.Parse(localOOF.ScheduledStartDateTime.DateTime); scheduledEndDateTimeEqual = DateTime.Parse(remoteOOF.ScheduledEndDateTime.DateTime) == DateTime.Parse(localOOF.ScheduledEndDateTime.DateTime); } catch (Exception) { //do nothing because we will just take the initialized false values; } if (!externalReplyMessageEqual || !internalReplyMessageEqual || !scheduledStartDateTimeEqual || !scheduledEndDateTimeEqual ) { OOFSponderInsights.Track("Local OOF doesn't match remote OOF"); System.Net.Http.HttpResponseMessage result = await O365.PatchHttpContentWithToken(O365.MailboxSettingsURL, localOOF); if (result.StatusCode == System.Net.HttpStatusCode.OK) { UpdateStatusLabel(toolStripStatusLabel1, DateTime.Now.ToString() + " - OOF message set - Start: " + StartTime + " - End: " + EndTime); //report back to AppInsights OOFSponderInsights.Track("Successfully set OOF"); return(true); } else { OOFSponderInsights.Track("Unable to set OOF"); UpdateStatusLabel(toolStripStatusLabel1, DateTime.Now.ToString() + " - Unable to set OOF message"); return(false); } } else { OOFSponderInsights.Track("Remote OOF matches - no changes"); UpdateStatusLabel(toolStripStatusLabel1, DateTime.Now.ToString() + " - No changes needed, OOF Message not changed - Start: " + StartTime + " - End: " + EndTime); return(true); } } catch (Exception ex) { notifyIcon1.ShowBalloonTip(100, "OOF Exception", "Unable to set OOF: " + ex.Message, ToolTipIcon.Error); UpdateStatusLabel(toolStripStatusLabel1, DateTime.Now.ToString() + " - Unable to set OOF"); OOFSponderInsights.TrackException("Unable to set OOF: " + ex.Message, ex); return(false); } }
/// <summary> /// Call AcquireTokenAsync - to acquire a token requiring user to sign-in /// </summary> internal async static Task <bool> MSALWork(AADAction action) { OOFSponderInsights.TrackInfo(OOFSponderInsights.CurrentMethod()); bool _result = false; if (action == AADAction.SignIn | action == AADAction.ForceSignIn) { try { authResult = await PublicClientApp.AcquireTokenSilentAsync(_scopes, PublicClientApp.Users.FirstOrDefault()); } catch (MsalUiRequiredException ex) { // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token //Don't track this one since it can basically be considered expected. //OOFSponderInsights.TrackException($"MsalUiRequiredException: {ex.Message}", ex); try { authResult = await PublicClientApp.AcquireTokenAsync(_scopes); } catch (MsalException msalex) { OOFSponderInsights.TrackException("MsalException", new Exception($"Error Acquiring Token:{System.Environment.NewLine}", msalex)); } } catch (Exception ex) { OOFSponderInsights.TrackException("Error Acquiring Token Silently", ex); return(false); } if (PublicClientApp.Users.Count() > 0) { //BuddyOptions.authResult = BuddyOptions.authResult; _result = true; //also, update the Application Insights info with the authenticated user OOFSponderInsights.AIClient.Context.User.Id = authResult.User.DisplayableId.Split('@')[0]; } else { _result = false; } } else { if (PublicClientApp.Users.Any()) { try { PublicClientApp.Remove(PublicClientApp.Users.FirstOrDefault()); _result = true; } catch (MsalException ex) { OOFSponder.Logger.Error($"Error signing-out user: {ex.Message}"); OOFSponderInsights.TrackException($"Error signing-out user: {ex.Message}", ex); } } } return(_result); }