#pragma warning restore 0414 private string GetDefaultUsername() { var count = 0; while (true) { var name = string.Format("{0}_{1}_{2}", Application.companyName, Application.productName, count); bool created; m_nameMutex = new Mutex(true, name, out created); if (created) { break; } count++; } var username = Environment.UserName; if (count > 0) { username = string.Format("{0} ({1})", username, count); } return username; }
public void OpenExisting() { const string Name = "MutexTestsOpenExisting"; Mutex resultHandle; Assert.False(Mutex.TryOpenExisting(Name, out resultHandle)); using (Mutex m1 = new Mutex(false, Name)) { using (Mutex m2 = Mutex.OpenExisting(Name)) { Assert.True(m1.WaitOne()); Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result); m1.ReleaseMutex(); Assert.True(m2.WaitOne()); Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result); m2.ReleaseMutex(); } Assert.True(Mutex.TryOpenExisting(Name, out resultHandle)); Assert.NotNull(resultHandle); resultHandle.Dispose(); } }
public bool PosTest1() { bool retVal = true; Thread thread = null; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Construct a new Mutex instance with initiallyOwned set to true (ensure that the thread owns the mutex)"); using(m_Mutex = new Mutex(true)) { try { do { if (null == m_Mutex) { TestLibrary.TestFramework.LogError("001", "Can not construct a new Mutex intance with initiallyOwned set to true."); retVal = false; break; } // Ensure initial owner of the mutex is current thread // Create another thread to change value of m_SharedResource thread = new Thread(new ThreadStart(ThreadProc)); thread.Start(); // Sleep 1 second to wait the thread get started Thread.Sleep(c_DEFAULT_SLEEP_TIME); if (m_SharedResource != c_DEFAULT_INT_VALUE) { TestLibrary.TestFramework.LogError("002", "Call Mutex(true) does not set current thread to be the owner of the mutex."); retVal = false; } m_Mutex.ReleaseMutex(); } while (false); // do } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { if (null != thread) { // Wait until all threads are terminated thread.Join(); } // Reset the value of m_SharedResource for further usage m_SharedResource = c_DEFAULT_INT_VALUE; } } return retVal; }
void Awake() { SetupWebCamTexture(); InitializeAruco(); mutex_ = new Mutex(); thread_ = new Thread(() => { try { for (;;) { Thread.Sleep(0); if (!isArucoUpdated_) { mutex_.WaitOne(); var num = aruco_detect(aruco_, false); GetMarkers(num); mutex_.ReleaseMutex(); isArucoUpdated_ = true; } } } catch (Exception e) { if (!(e is ThreadAbortException)) { Debug.LogError("Unexpected Death: " + e.ToString()); } } }); thread_.Start(); }
private int Run() { int iRet = -1; string sName = Common.GetUniqueName(); // Open an abandoned mutex using (mut = new Mutex(false, sName)) { Thread t = new Thread(new ThreadStart(AbandonMutex)); t.Start(); t.Join(); try { Mutex mut1 = Mutex.OpenExisting(sName); iRet = 100; } catch (Exception ex) { Console.WriteLine("Unexpected exception thrown: " + ex.ToString()); } } Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed"); return iRet; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); var zzz = new z(); bool createdNew; #if DEBUG || RELEASE_TEST #else Mutex instance = new Mutex(true, zzz.GetType().ToString(), out createdNew); if (!createdNew) { MessageBox.Show("不能多开"); return; } #endif try { Application.Run(zzz); //Application.Run(new ShipForm()); } catch (Exception e) { write_dump(e.ToString()); } //var f = new CommandForm(); //Application.Run(f); }
private int Run() { int iRet = -1; string sName = Common.GetUniqueName(); // open a semaphore with the same name as a mutex Mutex mu = new Mutex(false, sName); try { using (Semaphore sem = Semaphore.OpenExisting(sName)) { } } catch (WaitHandleCannotBeOpenedException) { //Expected iRet = 100; } catch (Exception e) { Console.WriteLine("Caught unexpected exception: " + e.ToString()); } Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed"); return iRet; }
private int Run() { int iRet = -1; Console.WriteLine("Abandon same named mutex"); // Create array with the same name wh = new Mutex[2]; string sName = Common.GetUniqueName(); wh[0] = new Mutex(false, sName); wh[1] = new Mutex(false, sName); Thread t = new Thread(new ParameterizedThreadStart(this.AbandonMutexPos)); t.Start(0); t.Join(); try { Console.WriteLine("Waiting..."); int i = WaitHandle.WaitAny(wh, 5000); Console.WriteLine("WaitAny did not throw an " + "exception, i = " + i); } catch(AbandonedMutexException) { // Expected iRet = 100; } catch(Exception e) { Console.WriteLine("Unexpected exception thrown: " + e.ToString()); } Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed"); return iRet; }
public static int Main(String[] args) { Console.WriteLine("MutexSample.cs ..."); gM1 = new Mutex(true,"MyMutex"); gM2 = new Mutex(true); Console.WriteLine(" - Main Owns gM1 and gM2"); AutoResetEvent[] evs = new AutoResetEvent[4]; evs[0] = Event1; evs[1] = Event2; evs[2] = Event3; evs[3] = Event4; MutexSample tm = new MutexSample( ); Thread t1 = new Thread(new ThreadStart(tm.t1Start)); Thread t2 = new Thread(new ThreadStart(tm.t2Start)); Thread t3 = new Thread(new ThreadStart(tm.t3Start)); Thread t4 = new Thread(new ThreadStart(tm.t4Start)); t1.Start( ); t2.Start( ); t3.Start( ); t4.Start( ); Thread.Sleep(2000); Console.WriteLine(" - Main releases gM1"); gM1.ReleaseMutex( ); Thread.Sleep(1000); Console.WriteLine(" - Main releases gM2"); gM2.ReleaseMutex( ); WaitHandle.WaitAll(evs); Console.WriteLine("... MutexSample.cs"); return 0; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Application.Run(new FormLineCanon()); // CurrentUser=new User(); // Giá trị luận lý cho biết ứng dụng này // có quyền sở hữu Mutex hay không. bool ownmutex; // Tạo và lấy quyền sở hữu một Mutex có tên là Icon; using (var mutex = new Mutex(true, "Icon", out ownmutex)) { // Nếu ứng dụng sở hữu Mutex, nó có thể tiếp tục thực thi; // nếu không, ứng dụng sẽ thoát. if (ownmutex) { // Application.Run(new FormLogin()); Application.Run(new FormLogin()); //giai phong Mutex; mutex.ReleaseMutex(); } else Application.Exit(); } }
private int Run() { int iRet = -1; string sName = Common.GetUniqueName(); // Basic test, not owned using(mut = new Mutex(false, sName)) { Thread t = new Thread(new ThreadStart(OwnMutex)); t.Start(); mre.WaitOne(); try { Mutex mut1 = Mutex.OpenExisting(sName); mut1.WaitOne(); mut1.ReleaseMutex(); iRet = 100; } catch (Exception ex) { Console.WriteLine("Unexpected exception thrown: " + ex.ToString()); } } Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed"); return iRet; }
public void ReuseMutexThread() { Console.WriteLine("Waiting to reuse mutex"); manualEvent.WaitOne(); bool exists; Mutex mutex = new Mutex(true, mutexName, out exists); if (exists) { Console.WriteLine("Error, created new mutex!"); success = 97; } else { mutex.WaitOne(); } try { Console.WriteLine("Mutex reused {0}", exists); mutex.ReleaseMutex(); } catch (Exception e) { Console.WriteLine("Unexpected exception: {0}", e); success = 98; } exitEvent.Set(); }
private int Run() { int iRet = -1; string sName = Common.GetUniqueName(); // open a Mutex that has been abandoned mut = new Mutex(false, sName); Thread th = new Thread(new ParameterizedThreadStart(AbandonMutex)); th.Start(mut); mre.WaitOne(); try { Mutex mut1 = Mutex.OpenExisting(sName); mut1.WaitOne(); } catch (AbandonedMutexException) { //Expected iRet = 100; } catch (Exception e) { Console.WriteLine("Caught unexpected exception: " + e.ToString()); } Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed"); return iRet; }
public void OpenExisting_Windows() { string name = Guid.NewGuid().ToString("N"); Mutex resultHandle; Assert.False(Mutex.TryOpenExisting(name, out resultHandle)); using (Mutex m1 = new Mutex(false, name)) { using (Mutex m2 = Mutex.OpenExisting(name)) { Assert.True(m1.WaitOne(FailedWaitTimeout)); Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result); m1.ReleaseMutex(); Assert.True(m2.WaitOne(FailedWaitTimeout)); Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result); m2.ReleaseMutex(); } Assert.True(Mutex.TryOpenExisting(name, out resultHandle)); Assert.NotNull(resultHandle); resultHandle.Dispose(); } }
static void Main() { bool isFirstInstance; var mutex = new Mutex(true, "VolumeWheelEx", out isFirstInstance); if(isFirstInstance) { try { Hook.SetHook(); var exit = false; while(!exit) { try { exit = WinAPI.GetMessage(IntPtr.Zero, IntPtr.Zero, 0, 0) > 0; } catch(NullReferenceException) { /* Don't worry, GetMessage can sometimes returns NULL. */ } }; Hook.UnHook(); } catch(Exception e) { //LOG file directly on desktop System.IO.File.AppendAllText(Environment.GetEnvironmentVariable("userprofile") + "\\Desktop\\VolumeWheelEx.log", "[" + DateTime.Now.ToString() + "]\n" + e.Source + " -> " + e.ToString() + "\n" + e.StackTrace + "\n\n"); } finally { mutex.ReleaseMutex(); } } else { try { var thisProc = Process.GetCurrentProcess(); var prcs = Process.GetProcessesByName(thisProc.ProcessName); for(int i = 0; i < prcs.Length; i++) { if(prcs[i].Id != thisProc.Id) { WinAPI.PostThreadMessage((uint)prcs[i].Threads[0].Id, WinAPI.WM_QUIT, UIntPtr.Zero, IntPtr.Zero); } } } catch { } } }
private void CreateMutexArray(int numElements) { wh = new WaitHandle[numElements]; for(int i=0;i<numElements;i++) { wh[i] = new Mutex(false, Common.GetUniqueName()); } }
public static void WaitAllSameNames() { Mutex[] wh = new Mutex[2]; wh[0] = new Mutex(false, "test"); wh[1] = new Mutex(false, "test"); Assert.Throws<ArgumentException>(() => WaitHandle.WaitAll(wh)); }
private void CreateMutexArray(int numElements) { wh = new WaitHandle[numElements]; for(int i=0;i<numElements;i++) { wh[i] = new Mutex(); } }
public void T3start() { Console.WriteLine("In T3 start, Mutex.WaitAny(Mutex[])"); Mutex[] gMs = new Mutex[2]; gMs[0] = gM1; gMs[1] = gM2; Mutex.WaitAny(gMs); Console.WriteLine("T3 finished, Mutex.WaitAny(Mutex[])"); Event3.Set(); }
public void T1start() { Console.WriteLine("In T1 start, Mutex.WaitAll(Mutex[])"); Mutex[] gMs = new Mutex[2]; gMs[0] = gM1; gMs[1] = gM2; Mutex.WaitAll(gMs); Thread.Sleep(2000); Console.WriteLine("T1 finished, Mutex.WaitAll(Mutex[])"); Event1.Set(); }
private void InitMutex() { string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); string mutexId = string.Format("Global\\{{{0}}}", appGuid); this.mutex = new Mutex(false, mutexId); MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); MutexSecurity securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); this.mutex.SetAccessControl(securitySettings); }
public static int Main() { // Abandon this mutex Mutex[] mArr = new Mutex[64]; for(int i=0;i<mArr.Length;i++) mArr[i] = new Mutex(false); ThreadStartArray tsa = new ThreadStartArray(); return tsa.Run(mArr); }
// Use this for initialization void Start() { m_mutex = new Mutex(true); listPosition = new List<Vector3>(); m_mutex.ReleaseMutex(); constantZ = transform.position.z; getPath(); m_nextPoint0 = transform.position; responseFromIA = true; initializeRays(); }
public void t3Start( ) { Console.WriteLine("t3Start started, Mutex.WaitAny(Mutex[])"); Mutex[] gMs = new Mutex[2]; gMs[0] = gM1; // Create and load an array of Mutex for WaitAny call gMs[1] = gM2; Mutex.WaitAny(gMs); // Waits until either Mutex is released Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])"); Event3.Set( ); // AutoResetEvent.Set() flagging method is done }
public static void DisposeTest() { var name = "MyCrazyMutexName" + Guid.NewGuid(); var handle = new Mutex(true, name); handle.Dispose(); Assert.False(Mutex.TryOpenExisting(name, out handle)); // TODO: Better exceptions on .NET Native //Assert.Throws<ObjectDisposedException>(() => handle.WaitOne(0)); }
public void t1Start( ) { Console.WriteLine("t1Start started, Mutex.WaitAll(Mutex[])"); Mutex[] gMs = new Mutex[2]; gMs[0] = gM1; // Create and load an array of Mutex for WaitAll call gMs[1] = gM2; Mutex.WaitAll(gMs); // Waits until both gM1 and gM2 are released Thread.Sleep(2000); Console.WriteLine("t1Start finished, Mutex.WaitAll(Mutex[]) satisfied"); Event1.Set( ); // AutoResetEvent.Set() flagging method is done }
private void AbandonAllMutexesWait() { Mutex m = new Mutex(); foreach(WaitHandle w in wh) { if(w.GetType() == m.GetType()) w.WaitOne(); } myMRE.Set(); Thread.Sleep(1000); }
public void t3Start( ) { Console.WriteLine("t3Start started, Mutex.WaitAny(Mutex[])"); Mutex[] gMs = new Mutex[2]; gMs[0] = gM1; gMs[1] = gM2; Mutex.WaitAny(gMs); Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])"); Event3.Set( ); gMs[0].ReleaseMutex(); }
private void AbandonOne() { Mutex m = new Mutex(); foreach(WaitHandle w in wh) { if(w.GetType() == m.GetType()) { w.WaitOne(); break; } } }
public static bool Start() { bool onlyInstance = false; string mutexName = String.Format("Local\\{0}", ProgramInfo.AssemblyGuid); // if you want your app to be limited to a single instance // across ALL SESSIONS (multiple users & terminal services), then use the following line instead: // string mutexName = String.Format("Global\\{0}", ProgramInfo.AssemblyGuid); mutex = new Mutex(true, mutexName, out onlyInstance); return onlyInstance; }
static void Main(String[] args) { // prevent multiple instances: code from https://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567 // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly(). GetCustomAttributes(typeof(GuidAttribute), false). GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); // Need a place to store a return value in Mutex() constructor call bool createdNew; // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid , null) , MutexRights.FullControl , AccessControlType.Allow ); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { // edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever // edited by acidzombie24 hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) { throw new TimeoutException("Timeout waiting for exclusive access"); } } catch (AbandonedMutexException) { // Log the fact that the mutex was abandoned in another process, // it will still get acquired hasHandle = true; } // Perform your work here. log4net.Config.XmlConfigurator.Configure(); // log version number Assembly asm = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location); log.Info($"Keyboard2Xinput v{fvi.ProductVersion}"); // parse args if (args.Length > 1) { MessageBox.Show("Too many arguments. Usage: Keyboard2XinputGui [mappingfile]", "Keyboard2Xinput", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { String mappingFile = null; if (args.Length > 0) { mappingFile = args[0]; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); Application.ApplicationExit += new EventHandler(OnApplicationExit); gui = new Keyboard2XinputGui(mappingFile); // Run() without parameter to not show the form at launch Application.Run(); //Application.Run(gui); } } finally { // edited by acidzombie24, added if statement if (hasHandle) { mutex.ReleaseMutex(); } } } }
private void DrugStore_Load(object sender, EventArgs e) { string mutex_id = "Clinic"; using (Mutex mutex = new Mutex(false, mutex_id)) { if (!mutex.WaitOne(0, false)) { MessageBox.Show("Instance Already Running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); return; } else { // برای رزرو کردن یک هات کی که برنامه با آن باز می شود // HotKey RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); Key.SetValue("Clinic", System.Reflection.Assembly.GetEntryAssembly().Location); // تغییر کی بورد به فارسی که کاربر راحت باشد // change keyboard language ChangeKeboardLayout(1065); } } DateTime now = DateTime.Now; DateTime Update_New = DateTime.Parse("08/02/2015 12:00:00 AM"); if (now.Date >= Update_New) { var msg = "مدت زمان یکساله برنامه تمام شده است. لطفا نسخه جدید را دریافت و نصب کنید."; MessageForm.Show(msg, "خطا", MessageFormIcons.Warning, MessageFormButtons.Ok, color); this.Close(); System.Environment.Exit(1); } //Lock(); this.Hide(); ConnectionString logon = new ConnectionString(); WindowState = FormWindowState.Maximized; if (TestConnection()) { this.Show(); } else if (logon.ShowDialog() != DialogResult.OK) { this.Show(); } SqlParameter[] param; param = new SqlParameter[2]; int index = 0; param[index++] = new SqlParameter("@Serial", serial); DataSet result = new DataSet(); result = (da.ExecuteSP("GetSerial", param)); //if (result == null || result.Tables.Count == 0 || result.Tables[0].Rows.Count == 0 || result.Tables[0].Columns.Count == 0) //{ // var msg = "شناسایی مرکز ناموفق است."; MessageForm.Show(msg, "خطای اطلاعات مرکز", MessageFormIcons.Warning, MessageFormButtons.Ok, color); //} //else //{ IDCenter = 9; // IDCenter = Convert.ToInt32(result.Tables[0].Rows[0]["IDCenters"]); this.Text += " " + result.Tables[0].Rows[0]["NameCenters"].ToString(); // } GridSet(); GridDocumentsSet(); WindowState = FormWindowState.Maximized; SqlParameter[] param1; param1 = new SqlParameter[2]; int index1 = 0; param1[index1++] = new SqlParameter("@IDCenter", IDCenter); param1[index1++] = new SqlParameter("@DocumentType", 1); DataSet ssd = new DataSet(); ssd = da.ExecuteSP("GetCenetrsIntermittence", param1); setLook(); if (ssd != null && ssd.Tables.Count > 0 && ssd.Tables[0].Rows.Count > 0) { GridDataSourceDt = ssd.Tables[0]; FillGrid(GridDataSourceDt); MenuTop4ToolStripMenuItem_Click(null, null); grdIntermittenc_CellClick(null, null); grdDocuments.Rows.OfType <DataGridViewRow>().Last().Selected = true; timer1.Start(); } else { timer1.Start(); MenuTop4ToolStripMenuItem.Text = "0" + " " + "نسخه دارو"; } }
/// <summary> /// Get a picture URL /// </summary> /// <param name="picture">Picture instance</param> /// <param name="targetSize">The target picture size (longest side)</param> /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param> /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param> /// <param name="defaultPictureType">Default picture type</param> /// <returns>Picture URL</returns> public virtual async Task <string> GetPictureUrl(Picture picture, int targetSize = 0, bool showDefaultPicture = true, string storeLocation = null, PictureType defaultPictureType = PictureType.Entity) { if (picture == null) { return(showDefaultPicture ? await GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation) : string.Empty); } byte[] pictureBinary = null; if (picture.IsNew) { if ((picture.PictureBinary?.Length ?? 0) == 0) { pictureBinary = await LoadPictureBinary(picture); } else { pictureBinary = picture.PictureBinary; } await DeletePictureThumbs(picture); //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown picture = await UpdatePicture(picture.Id, pictureBinary, picture.MimeType, picture.SeoFilename, picture.AltAttribute, picture.TitleAttribute, false, false); } string seoFileName = picture.SeoFilename; string lastPart = GetFileExtensionFromMimeType(picture.MimeType); string thumbFileName; if (targetSize == 0) { thumbFileName = !string.IsNullOrEmpty(seoFileName) ? string.Format("{0}_{1}.{2}", picture.Id, seoFileName, lastPart) : string.Format("{0}.{1}", picture.Id, lastPart); var thumbFilePath = GetThumbLocalPath(thumbFileName); if (await GeneratedThumbExists(thumbFilePath, thumbFileName)) { return(GetThumbUrl(thumbFileName, storeLocation)); } pictureBinary = pictureBinary ?? await LoadPictureBinary(picture); using (var mutex = new Mutex(false, thumbFileName)) { mutex.WaitOne(); await SaveThumb(thumbFilePath, thumbFileName, pictureBinary); mutex.ReleaseMutex(); } } else { thumbFileName = !string.IsNullOrEmpty(seoFileName) ? string.Format("{0}_{1}_{2}.{3}", picture.Id, seoFileName, targetSize, lastPart) : string.Format("{0}_{1}.{2}", picture.Id, targetSize, lastPart); var thumbFilePath = GetThumbLocalPath(thumbFileName); if (await GeneratedThumbExists(thumbFilePath, thumbFileName)) { return(GetThumbUrl(thumbFileName, storeLocation)); } pictureBinary = pictureBinary ?? await LoadPictureBinary(picture); using (var mutex = new Mutex(false, thumbFileName)) { mutex.WaitOne(); if (pictureBinary != null) { try { using (var image = SKBitmap.Decode(pictureBinary)) { pictureBinary = ApplyResize(image, EncodedImageFormat(picture.MimeType), targetSize); } } catch { } } await SaveThumb(thumbFilePath, thumbFileName, pictureBinary); mutex.ReleaseMutex(); } } return(GetThumbUrl(thumbFileName, storeLocation)); }
public bool Validate(Mutex pageLock) { return(object.ReferenceEquals((object)pageLock, (object)this._lock)); }
static void Main(string[] args) { // Needed so when we show a message box it doesn't look like Windows 98 Application.EnableVisualStyles(); #region System Health Checks and Log Setup try { // creates the datapath to make sure it exists Directory.CreateDirectory(DataPath); } catch (Exception ex) { Logger.Error($"Couldn't create {DataPath} directory."); // No Logger call since we can't even create the directory ShowMessageAndExit($"Failed to create data directory in '{DataPath}'.\n{ex.ToString()}", "Write Access"); } // Marks the begining of a new log cycle Logger.Information($"Starting {VersionInfo.FileDescription} v{VersionInfo.ProductVersion}"); // check if WMI service is running, if it's not we wont be able to get any process information if (!IsWMIServiceRunning()) { Logger.Error("WMI service not running"); ShowMessageAndExit("The \"Windows Management Instrumentation\" service is not running.\n" + "This service is required for bnetlauncher to function properly, please make sure it's enabled, before trying again.", "WMI service not running"); } // Logs generic System information for debugging purposes. LogSystemInfo(); #endregion LoadGameList(); #region Argument Parsing // Parse the given arguments if (args.Length <= 0) { // No parameters so just Show instructions var message = "No Game Id has been given.\n" + "To launch a game please add one of the following Ids to the launch options:\n"; foreach (var g in games) { message += $"{g.Id}\t= {g.Name}\n"; } message += "\nSee 'instructions.txt' on how to add more games."; Logger.Warning("No parameter given."); ShowMessageAndExit(message, "How to Use", MessageType.Info); } // Check if the param_timeout is passed as a second parameter for (var i = 1; i < args.Length; i++) { var arg = args[i].ToLowerInvariant().Trim(); // parse options if (arg.StartsWith("-", StringComparison.OrdinalIgnoreCase) || arg.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { // remove starting character arg = arg.Substring(1); switch (arg) { case "t": case "timeout": case "-timeout": try { param_timeout = Convert.ToInt32(args[++i], CultureInfo.InvariantCulture); Logger.Information($"Changing timeout to '{param_timeout}'."); } catch (Exception ex) { Logger.Warning($"Couldn't convert timeout:'{args[i]}' into integer, ignoring and continuing.", ex); } break; case "l": case "leaveopen": case "-leaveopen": Logger.Information($"Leaving the client open on exit."); param_leaveopen = true; break; case "n": case "notask": case "-notask": Logger.Information($"Disabling task launching"); param_notask = true; break; default: Logger.Warning($"Ignoring unknown option: '{arg}'"); break; } } else { // unknown parameter Logger.Warning($"Ignoring unknown parameter: '{arg}'"); } } // Retrieves the first parameter that should be the game id and checks it against the games list // In an attempt to avoid user mistakes we clean the input by forcing lowercase and strip - and / // before comparing it to know ids. var param_game = args[0].Trim().Replace("-", "").Replace("/", "").ToLowerInvariant(); Logger.Information($"Given parameter '{args[0]}'."); selected_game = games.Find(g => g.Id == param_game); // If the id isn't know give a warning about invalid game. if (selected_game == null) { Logger.Error($"Unknown game '{param_game}'."); var message = $"Unknown game id '{param_game}' given.\n"; message += "\nPlease use one of the known game ids:\n"; foreach (var g in games) { message += $"{g.Id}\t= {g.Name}\n"; } message += $"\nPlease check if the Id exists.\n\n" + "bnetlauncher will now Close.\n"; ShowMessageAndExit(message, "Unknown Game Id"); } #endregion // Checks if the game client exists selected_client = clients.Find(c => c.Id == selected_game.Client); if (selected_client == null) { var message = $"Unknown client '{selected_game.Client}'\n" + "bnetlauncher only supports the following values:\n\n"; foreach (var c in clients) { message += $" {c.Id} ({c.Name})\n"; } message += "\nbnetlauncher will now exit.\n"; ShowMessageAndExit(message, "Error: Unknown client"); } Logger.Information($"Using '{selected_client.Id}' client."); // Checks if the client is actually Installed installLocation property is not returning an empty path if (!selected_client.IsInstalled) { ShowMessageAndExit($"The {selected_client.Name} client doesn't seem to be Installed.\n\n" + "Please reinstall the Battle.net Client to fix the issue\n"); } #region Mutex Setup to enforce single bnetlancher instance // We use a Local named Mutex to keep two instances of bnetlauncher from working at the same time. // So we check if the mutex already exists and if so we wait until the existing instance releases it // otherwise we simply create it and continue. // This tries to avoid two instances of bnetlauncher from swapping the games they're launching. try { Logger.Information("Checking for other bnetlauncher processes using same client"); mutex_name += selected_client.Id; launcher_mutex = Mutex.OpenExisting(mutex_name); } catch (WaitHandleCannotBeOpenedException) { // Named Mutex doesn't exist yet, so we'll create it Logger.Information("No other bnetlauncher detected"); launcher_mutex = new Mutex(false, mutex_name); } catch (Exception ex) { // Unknown problem Logger.Error("Unknown error opening mutex.", ex); ShowMessageAndExit("A mutex exception has occurred:\n" + ex.ToString(), "Mutex Exception"); } // Waits for the mutex to be released before continuing, writes a message every second for debug purposes // we check for time var start = DateTime.Now; while (!launcher_mutex.WaitOne(1000)) { Logger.Information("Waiting for another bnetlauncher instance to finish."); // If we don't get released for over a minute it's likely something went very wrong so we quit. if (DateTime.Now.Subtract(start).TotalMinutes > 1) { Logger.Error("Waiting for over 1 minute, assuming something is wrong and exiting"); ShowMessageAndExit("A previous bnetlauncher instance seems to have not properly exited.\n" + "Try using Windows Task Manager to Close it and try again, if the problem persists " + "report the issue to bnetlauncher author.", "Stuck Instance"); } } #endregion // Make sure the client is running if (!selected_client.IsRunning) { // Start the client if (!selected_client.Start(!param_leaveopen, (param_notask || selected_game.Options.Contains("notask")))) { Logger.Information($"Client '{selected_client.Name}' not running and/or failed to start it."); ShowMessageAndExit($"Couldn't find the {selected_client.Name} running and failed to start it.\nExiting application", "Client not found"); } } else { Logger.Information($"Client already running with pid:'{selected_client.GetProcessId()}'."); } #region Launch Game // Fire up game trough battle.net using the built in URI handler, we take the date to make sure we // don't mess with games that might already be running. DateTime launch_request_date = DateTime.Now; // Attempts to force the application to run without admin if (selected_game.Options.Contains("noadmin")) { Logger.Information($"Setting compatibility flag to disable UAC prompt."); Environment.SetEnvironmentVariable("__COMPAT_LAYER", "RUNASINVOKER"); } // If nolaunch is selected don't actually launch the game but instead shows the client window and adds 1 minute to param_timeout if (!selected_game.Options.Contains("nolaunch")) { Logger.Information($"Issuing game launch command '{selected_game.Cmd}' at '{launch_request_date.ToString("hh:mm:ss.ffff", CultureInfo.InvariantCulture)}'"); selected_client.Launch(selected_game.Cmd); } else { selected_client.ShowWindow(); param_timeout += 60; } var game_process_id = 0; do { // Searches for a game started trough the client for 15s game_process_id = Processes.GetProcessByNameAfterDate(selected_game.Exe, launch_request_date, param_timeout); // did we find it? if (game_process_id == 0) { // didn't find the game process within timeout Logger.Error($"Game '{selected_game.Id}' not found within timeout."); // Game might be updating var msg = $"Couldn't find {selected_game.Name} running, do you wish to keep trying?\n\n" + "Canceling will exit bnetlauncher but leave the client open.\n\n" + "This message is usually caused by the game being slow to start or an update being required. " + "For slow starting games the launch option '-t' can also be used to increase the timeout limit.\n\n" + "If you keep getting this message make sure the client is working properly and try rebooting your system.\n"; var answer = MessageBox.Show(msg, "Game not Found. Retry?", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); switch (answer) { case DialogResult.Retry: Logger.Information("User chose to retry searching for game."); continue; // back to the begining and try again case DialogResult.Cancel: try { Logger.Information("User chose to cancel."); // Make it so we leave the client open selected_client.WasStarted = false; // Cleans up the mutex if (launcher_mutex != null) { launcher_mutex.Close(); } } catch (Exception ex) { Logger.Error("Error releasing the mutex.", ex); } return; } } }while (game_process_id == 0); // keep's retrying until user cancels or game found // Copies the game process arguments to launch a second copy of the game under this program and kills // the current game process that's under the battle.net client. var process = new Process() { StartInfo = Processes.GetProcessStartInfoById(game_process_id) }; // Make sure our StartInfo is actually filled and not blank if (String.IsNullOrEmpty(process.StartInfo.FileName) || (String.IsNullOrEmpty(process.StartInfo.Arguments) && !selected_game.Options.Contains("noargs"))) { Logger.Error("Failed to obtain game parameters."); // Exit Application in error ShowMessageAndExit("Failed to retrieve game parameters.\nGame might start but steam overlay won't be attached to it.\n" + "This can happen if the game is no longer running (Starcraft Remastered can only have one running instance) " + "or when bnetlauncher does not have enough permissions, try running bnetlauncher and steam as administrator.", "Game Parameters"); } try { Logger.Information("Closing game process and starting it under bnetlauncher"); Processes.KillProcessAndChildsById(game_process_id); process.Start(); } catch (Exception ex) { Logger.Error("Failed to relaunch game under bnetliancher.", ex); ShowMessageAndExit("Failed to relaunch game under bnetlauncher/steam.\nOverlay will not work.", "Failed to Launch"); } #endregion // Launch game // HACK: Add checks for uplay games that close and relaunch themselfs if (selected_game.Options.Contains("relaunches")) { var relaunches_timeout = 60 * 1000; Logger.Information("relaunches option is set, looking for new processes."); // the old process Id var old_pid = process.Id; Logger.Information($"{selected_game.Id} current process id is {old_pid}"); stopwatch.Restart(); while (stopwatch.ElapsedMilliseconds < relaunches_timeout) { foreach (var p in Process.GetProcessesByName(selected_game.Exe)) { if (p.Id != old_pid) { process = p; Logger.Information($"{selected_game.Id} new process id is {process.Id}"); old_pid = process.Id; } } Thread.Sleep(1000); // wait for 1s before retrying to find it } stopwatch.Stop(); if (stopwatch.ElapsedMilliseconds < relaunches_timeout) { Logger.Warning($"Couldn't find any new process for {selected_game.Id}"); } Logger.Information($"Stopped looking for {selected_game.Id} processes."); } // Release the mutex to allow another instance of bnetlauncher to grab it and do work launcher_mutex.ReleaseMutex(); // If we launched the client and it's not needed we can close it early if (!selected_client.MustBeRunning) { CloseClientIfLast(); } // For games that require the client or bnetlauncher to stick around we wait if (selected_game.Options.Contains("waitforexit") || selected_client.MustBeRunning) { Logger.Information($"Waiting for {selected_game.Id} process {process.Id} to exit"); process.WaitForExit(); //// Get the process again because sometimes what we start isn't what's still running //int extra = 1; //while (extra > 0) //{ // extra = Process.GetProcessesByName(selected_game.Exe).Length; // if (extra > 0) // { // var p2 = Process.GetProcessesByName(selected_game.Exe)[0]; // p2.WaitForExit(); // } //} } // Finally we close the client when we're done process.Dispose(); CloseClientIfLast(); Logger.Information("All operations successful, exiting"); launcher_mutex.Close(); }
private async void App_OnStartup(object sender, StartupEventArgs e) { RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; ClearAllDoFiles(); // Set shutdown mode back to default ShutdownMode = ShutdownMode.OnExplicitShutdown; var isUpdater = Environment.GetCommandLineArgs().Contains("-update"); var isUpdated = Environment.GetCommandLineArgs().Contains("-updated"); #warning TRANSITIONAL CODE, REMOVE IN FUTURE VERSIONS (registry integration) if (isUpdated) { const string GUID = "8abad8e2-b957-48ed-92ba-4339c2a40e78"; const string TOSMain = "4"; const string TOS3rdParty = "4"; #if DEBUG string generalSettingsFile = GetRootPath("app/configs/General.json"); #else string generalSettingsFile = GetRootPath("configs/General.json"); #endif try { var generalSettingsText = System.IO.File.ReadAllLines(generalSettingsFile); var agreeTOS = generalSettingsText.Where(line => line.Contains("AgreedWithTOS")).FirstOrDefault(); if (agreeTOS != null) { agreeTOS = agreeTOS.Split(':') .Last() .Replace(",", "") .Trim(); if (agreeTOS == TOSMain) { SetSubKey("AgreedWithTOS", 4); } } var agreeTOSMiner = generalSettingsText.Where(line => line.Contains("Use3rdPartyMinersTOS")).FirstOrDefault(); if (agreeTOSMiner != null) { agreeTOSMiner = agreeTOSMiner.Split(':') .Last() .Replace(",", "") .Trim(); if (agreeTOSMiner == TOS3rdParty) { SetSubKey("Use3rdPartyMinersTOS", 4); } } } catch (Exception ex) { //Logger.Error("NHMLauncher", ex.Message); } } var afterUpdate = false; if (isUpdater) { var latestUpdaterFile = GetLatestUpdater(); if (latestUpdaterFile == null) { var restartProcessUpdatefailed = new Process { StartInfo = new ProcessStartInfo { FileName = GetRootPath("NiceHashMiner.exe"), WorkingDirectory = GetRootPath(), Arguments = "-updateFailed", WindowStyle = ProcessWindowStyle.Normal } }; restartProcessUpdatefailed.Start(); // shutdown Shutdown(); return; } var updaterFile = GetRootPath("updaters", latestUpdaterFile); var isZip = updaterFile.EndsWith(".zip"); //await Task.Delay(5000); if (isZip) { var pluginPackagesPath = GetRootPath("plugins_packages"); if (Directory.Exists(pluginPackagesPath)) { Directory.Delete(pluginPackagesPath, true); } var progWindow = new UpdateProgress(); progWindow.Show(); var isOk = await UnzipFileAsync(updaterFile, GetRootPath(), progWindow.Progress, CancellationToken.None); progWindow.Close(); await Task.Delay(500); // TODO if something goes wrong just restore the current exe process file var restartProcess = new Process { StartInfo = new ProcessStartInfo { FileName = GetRootPath("NiceHashMiner.exe"), WorkingDirectory = GetRootPath(), Arguments = "-updated", WindowStyle = ProcessWindowStyle.Normal } }; afterUpdate = true; restartProcess.Start(); } else { var startUpdater = new Process { StartInfo = new ProcessStartInfo { FileName = updaterFile, WorkingDirectory = GetRootPath(), WindowStyle = ProcessWindowStyle.Normal } }; startUpdater.Start(); // TODO we should wait and check if we have restarted NiceHash Miner } // shutdown Shutdown(); return; } if (isUpdated) { await Task.Delay(500); // so we release the temp files } await WindowsUptimeCheck.DelayUptime(); bool createdNew = false; try { string appPath = GetHashString(); _mutex = new Mutex(true, appPath, out createdNew); if (!createdNew) { //MessageBox.Show("We have detected you are already running NiceHash Miner. Only a single instance should be running at a time.", "NiceHash Miner Warning", MessageBoxButton.OK, MessageBoxImage.Warning); // shutdown Shutdown(); return; } ClearAllTmpFiles(); // TODO pass parent process PID var(latestAppDir, latestAppExe, version) = GetLatestApp(); #if DELETE_NON_CURRENT_APPS #error "Comment this line if you really wish to execute apps cleanup" DeleteAllExceptCurrentVersion(version); // cleanup on next release #endif var nhmApp = GetRootPath(latestAppDir, latestAppExe); var args = $"-lc -PID{Process.GetCurrentProcess().Id}"; if (isUpdated) { afterUpdate = true; args += " -updated"; } var startInfo = new ProcessStartInfo { FileName = nhmApp, Arguments = args, WindowStyle = ProcessWindowStyle.Normal }; var run = true; const int maxRestartCount = 3; int restartCount = 0; const int minRestartTimeInSeconds = 30; while (run) { var startTime = DateTime.UtcNow; run = false; try { using (var niceHashMiner = new Process { StartInfo = startInfo }) { var hasStarted = niceHashMiner?.Start(); niceHashMiner?.WaitForExit(); if (afterUpdate == true) { afterUpdate = false; startInfo.Arguments = startInfo.Arguments.Replace("-updated", ""); } // TODO Console.WriteLine(niceHashMiner.ExitCode); //in case of crash try to restart the program if (niceHashMiner.ExitCode != 0) { var endTime = DateTime.UtcNow; string path = GetRootPath("logs", "watchdogLog.txt"); if (!File.Exists(path)) { using (var sw = File.CreateText(path)) { sw.WriteLine($"Exit code: {niceHashMiner.ExitCode} ---- {endTime}"); } } else { using (var sw = File.AppendText(path)) { sw.WriteLine($"Exit code: {niceHashMiner.ExitCode} ---- {endTime}"); } } //try to re-run the NHM run = true; //check if too many restarts var elapsedSeconds = (endTime - startTime).TotalSeconds; if (elapsedSeconds < minRestartTimeInSeconds) { restartCount++; } else { restartCount = 0; } if (restartCount >= maxRestartCount) { using (var sw = File.AppendText(path)) { sw.WriteLine($"Too many restarts! Closing nhm"); } MessageBox.Show("NHM experienced too many crashes recently, therefore it will close itself", "Too many restarts"); run = false; } } else { // if exit code is 0 then check runasadmin or restart if (IsRunAsAdmin()) { RunAsAdmin.SelfElevate(); } else if (IsRestart()) { ClearAllDoFiles(); run = true; } else if (IsUpdate()) { run = true; // mark to false if updating doesn't fail ClearAllDoFiles(); var exePath = Assembly.GetExecutingAssembly().Location; var randomPart = DateTime.UtcNow.Millisecond; var tmpLauncher = GetRootPath($"tmp.nhm_updater_{randomPart}.exe"); File.Copy(exePath, tmpLauncher, true); var doUpdate = new Process { StartInfo = new ProcessStartInfo { FileName = tmpLauncher, Arguments = "-update", WindowStyle = ProcessWindowStyle.Normal } }; afterUpdate = true; var updateStarted = doUpdate.Start(); run = !updateStarted; // set if we are good } else /*ELSE*/ } { } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } // shutdown Shutdown(); return; } finally { if (createdNew) { _mutex?.ReleaseMutex(); } } }
static void Main(string[] args) { string file_uri = @"\\192.168.177.109\filesfa\images\valsys\T725751608111619_instalasi_IMG_20160811_155102.jpg"; // Please make sure you upload your file to this folder before you call this API!!! string file_name = "T725751608111619_instalasi_IMG_20160811_155102.jpg"; long file_size = 1290970; string[] arr1 = new string[] { "500016733", "500016662", "500016635", "500016564", "500016555", "500016537", "500016493", "500016368", "500018609", "500018645" }; Huda_customer_class var_yang_class = new Huda_customer_class(); Huda_workOrder_class var_yang_class_wo = new Huda_workOrder_class(); Yang_class var_yang_class_1 = new Yang_class(); Huda_device_class var_device = new Huda_device_class(); mutex = new Mutex(true, "MyMutex"); if (!mutex.WaitOne(0, false)) { return; } else { //var_yang_class.create_new_customer(); //var_device.retrieveDevice("DS170417000090"); //var_yang_class_1.huda_ship_so(500167847, 156809); #region shippping order //2, 3, 4, 7, 10, 13, 30, 393 int so_id = 157260; int cust_id = 500171897; var tech_prod_id_format = var_yang_class_1.getformat_bycallshippingorderbyid_2(so_id); List <string> serial_number = new List <string>(new string[] { "", "PE14070001586D", "02000055756852", "DS170417000392", "67069A01181525967", "", "02000055756860", "", "67069A01181576599", "", "02000055756902", "" }); var_yang_class_1.MayShipSO_ver1(cust_id); var_yang_class_1.huda_shippingOrder_1(cust_id, so_id, tech_prod_id_format, serial_number); //var_yang_class_1.huda_ship_so(cust_id, so_id); //var_yang_class_1.getformat_bycallshippingorderbyid(156757); #endregion shippping order //var_yang_class.create_offer(); //var_yang_class.create_new_customer(); ////update SO to may ship //Console.WriteLine("Change shipping order to May Ship of customer " + 500167604 + " "); //var_yang_class_1.MayShipSO_ver1(500167604); //// Ship shipping order //Console.WriteLine("Ship shipping order of customer " + 500167604 + " "); //var var_shipping_order = var_yang_class_1.ShipShippingOrder_ver2(500167604, "67069A01184309334", "02000055748685", false, "PRSD0000001067", "DS170417000066", 156778, false); #region workorder operation //Authentication_class var_auth = new Authentication_class(); //AuthenticationHeader authHeader = var_auth.getAuthentication_header(); //AsmRepository.SetServiceLocationUrl(var_auth.var_url_asm); //var wocs = AsmRepository.AllServices.GetWorkforceService(authHeader).GetWorkOrder(60347); // change 123 to your work order id. //Huda_workOrder_class var_wo = new Huda_workOrder_class(); //var wo = new Yang_class(); //const int reason_assign_wo = 19545; //const int reason_inprogress_wo = 99125; //const int reason_reschedule_wo = 20941; //const int reason_complete_wo = 23035; //const int reason_update_wo = 12; //const int reason_cancel_wo_RequestedBySub = 99367; //Edit WorkOrder, only change the service date time, you can change more like technician(AssociatedId) or the problemdescription. //wocs.AssociateId = AsmRepository.AllServices.GetCustomersService(authHeader).GetAssociatesByRequest(new BaseQueryRequest() //{ // FilterCriteria = new CriteriaCollection() { // new Criteria() { // Key = "CustomerId", Operator=Operator.Equal,Value=wocs.ServiceProviderId.Value.ToString() // }, // new Criteria() { // Key = "Active", Operator=Operator.Equal,Value="true" // }, // new Criteria() { // Key = "AssociateTypeId", Operator=Operator.Equal,Value="1" // }, // } //}).Items[0].Id.Value; //Assign WorkOder //Console.WriteLine("Assgin workorder " + wocs.Id.Value); //var wou = wo.UpdateWorkOrderWithTimeSlot(wocs, reason_assign_wo); //var wou = wo.UpdateWorkOrderWithOutTimeSlot(wocs, reason_assign_wo); // update work order without change status //Console.WriteLine("Update work order with out change anything " + wocs.Id.Value); //wou.ProblemDescription = "It has been changed!!!!!"; //var wou = wo.UpdateWorkOrderWithTimeSlot(wocs, reason_update_wo); //Change WorK Order to Working status //Console.WriteLine("change workorder " + wocs.Id.Value + " to In Progress."); //wou = wo.UpdateWorkOrderWithOutTimeSlot(wocs, reason_inprogress_wo); // reschedule work order : current work order status must Working //Console.WriteLine("Reschedule Work order after wait for rescheduled workorder " + wocs.Id.Value); //var wou = wo.UpdateWorkOrderWithTimeSlotForReschedule(wocs, reason_reschedule_wo); // assign work order after reschedule: current work order status must be Assigned //Console.WriteLine("Assgine Work order after reschedule workorder " + wocs.Id.Value); //wou = wo.UpdateWorkOrderWithOutTimeSlot(wou, reason_assign_wo); //Change WorKOrder to In Progress status //Console.WriteLine("change workorder " + wou.Id.Value + " to In Progress."); //wou = wo.UpdateWorkOrderWithOutTimeSlot(wou, reason_inprogress_wo); // Cancel Work Order, uncomment it if you want to use. When you use it, you can’t complete work order anymore. So comment below complete work order when you use it //Console.WriteLine("Cancel workorder " + wocs.Id.Value + ""); //wo.CancelWorkOrder(wocs, reason_cancel_wo_RequestedBySub); //Complete WorkOrder //var wou = var_yang_class_wo.CompleteWorkOrder(wocs, 99470, "aaaaaa", "bbbbbbb", 99470); //Console.WriteLine(DateTime.Now + " : Close workorder " + wou.Id.Value); #endregion workorder operation } //var_yang_class.getTimeslotbyPostalcode(11140000); //var_yang_class.importDevicesbyFile(@"c:\foo\bar\blop\blap.txt", 1, 1); //var_yang_class.sendCommand("01000006011381"); //var_yang_class.createRelationshipForCustomer(500016733, 500016635, "G"); //var_yang_class.updateRelatioshipForCustomer(500016733, 500016635, "G"); string decodersn = "12345"; // can be used for router sn string smartcardsn = "54321"; // can be used for sim card sn //Yang_class var_yang_class = new Yang_class(); //var_yang_class.uploadFile("D:/muhammadali.jpg", 500020335); //var var_uri = new System.Uri("//192.168.177.109/filesfa/images/valsys/T725751608111619_instalasi_IMG_20160811_155102.jpg"); //Console.WriteLine(var_uri); //var_yang_class_1.linkDocument(500016733, file_name, "//192.168.177.109/filesfa/images/valsys/T725751608111619_instalasi_IMG_20160811_155102.jpg", file_size); //var_yang_class.GetCustomerDeviceView(500039270); //get shipping order //yang_class.getShippingOrderbyCustomerID(500039725); string str_decoder = null; string str_vc = null; int[] arr_cust_id = new int[] { 500008595, 500008530, 500008432, 500008432, 500008334, 500008334, 500008399, 500008343, 500008236, 500008165, 500008218, 500008129, 500008192, 500008138, 500007983, 500006960, 500007221, 500007203, 500007080, 500007070, 500006600, 500006914, 500006899, 500006880, 500006816, 500006763, 500006727, 500006727, 500006683, 500006656, 500006629, 500006576, 500006530, 500006389, 500006324, 500006217, 500006164, 500006137, 500006084, 500006039, 500006020 }; int[] arr_so_id = new int[] { 0, 155962, 155955, 155955, 155947, 155947, 155951, 155948, 0, 155934, 156125, 156118, 155936, 155931, 155921, 155909, 156116, 155916, 156115, 155910, 155880, 155904, 155902, 156107, 155898, 155895, 155892, 155892, 156136, 156134, 155881, 155879, 155878, 156103, 155865, 155860, 155856, 156099, 155852, 155849, 155845 }; string[] arr_decoder = new string[] { "0", "0", "5941134164711044", "5941131496285143", "3872732097761214", "0", "3872732104210205", "3872732108584829", "5505934191696912", "3872732106017293", "5505934134005692", "3873232086434088", "0", "3872732108694172", "3872732108605327", "3872732104220790", "5505934134176170", "0", "5505934130401259", "0", "3867534166229363", "0", "0", "3873232101328133", "3873232090918043", "3867531490949245", "3872732092248977", "3873232098616177", "5505934184093861", "5941131490983669", "0", "5505934164647322", "5941134165886464", "3873232096838591", "0", "3867531481267045", "0", "1978832095739977", "3873232SMG001815", "3872732104216368", "1978832108802770", }; string[] arr_vc = new string[] { "02000043345768", "02000027358506", "02000043385780", "02000043385780", "02000063997647", "02000060471182", "02000046470530", "02000043205236", "02000043323765", "02000056245731", "02000043287606", "02000056871726", "02000043339670", "02000042844811", "02000048210074", "02000043392810", "02000043267384", "02000043265016", "02000042763672", "02000043286095", "02000024365249", "02000043339761", "02000043287028", "02000047622246", "02000062055090", "02000043266741", "02000037317963", "02000037347226", "02000043345024", "02000062531793", "02000043339795", "02000026619064", "02000030074678", "02000045083763", "02000055823785", "02000042612614", "02000042775791", "02000043283613", "02000021917059", "02000053292710", "02000053598355" }; //for(int i =0; i < arr_cust_id.Length; i++) //{ // Console.WriteLine("================================================================================"); // Console.WriteLine(arr_cust_id[i].ToString() +"===="+arr_decoder[i]+"====="+arr_vc[i] +"====="+arr_so_id[i]); // if(arr_so_id[i].ToString() == "0") // { // Console.WriteLine("================================================================================"); // continue; // } // else // { // // update SO to may ship // Console.WriteLine("Change shipping order to May Ship of customer " + arr_cust_id[i] + " "); // var_yang_class_1.MayShipSO_ver1(arr_cust_id[i]); // if (arr_decoder[i].ToString() == "0") // str_decoder = ""; // if (arr_vc[i].ToString() == "0") // str_vc = ""; // // Ship shipping order // Console.WriteLine("Ship shipping order of customer " + arr_cust_id[i] + " "); // var var_shipping_order = var_yang_class_1.ShipShippingOrder_ver2(arr_cust_id[i], str_decoder, str_vc, false, "", "", 155948, false); // Authentication_class var_auth = new Authentication_class(); // AuthenticationHeader authHeader = var_auth.getAuthentication_header(); // AsmRepository.SetServiceLocationUrl(var_auth.var_url_asm); // if (var_shipping_order != null) // { // var agreementManagementService = AsmRepository.GetServiceProxyCachedOrDefault<IAgreementManagementService>(authHeader); // var adc = agreementManagementService.GetAgreementDetailsForCustomer(arr_cust_id[i], 1); //zzzzzzzzzzz // Console.WriteLine(adc); // } // else // Console.WriteLine("null"); // Console.WriteLine("================================================================================"); // } //} /////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Console.WriteLine("================================================================================"); //// update SO to may ship //Console.WriteLine("Change shipping order to May Ship of customer " + 500004323 + " "); //var_yang_class_1.MayShipSO_ver1(500004323); //// Ship shipping order //Console.WriteLine("Ship shipping order of customer " + 500004323 + " "); //var var_shipping_order = var_yang_class_1.ShipShippingOrder_ver2(500004323, "3882823595776404", "02000042896571", false, "", "", 155697, false); //Authentication_class var_auth = new Authentication_class(); //AuthenticationHeader authHeader = var_auth.getAuthentication_header(); //AsmRepository.SetServiceLocationUrl(var_auth.var_url_asm); //if (var_shipping_order != null) //{ // var agreementManagementService = AsmRepository.GetServiceProxyCachedOrDefault<IAgreementManagementService>(authHeader); // var adc = agreementManagementService.GetAgreementDetailsForCustomer(500004323, 1); //zzzzzzzzzzz // Console.WriteLine(adc); //} //else // Console.WriteLine("null"); //Console.WriteLine("================================================================================"); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region retrieve device //----------- Retrive Device ---------------- //string device_serial_number = "01000006011548"; // change real device serial number //int reason156_RetriveDevice = 99146; //int reason183_Returned = 99149; //int reason156_InStock = 99152; //int reason156_ReturnToManufactory = 99151; //int reason156_RepairedStock = 99153; //int reason156_RefurbishedStock = 99154; //int reason156_Damaged = 99155; //int to_stockhandler_id = 1015; // the destination stocck handler of the device //var deviceh = new deviceHandler(authHeader); // First step - change to to be return //var_yang_class.updateDeviceStatus(device_serial_number, reason156_RetriveDevice); // Second step - change stock handler //var_yang_class.transferDevice(reason183_Returned, to_stockhandler_id, device_serial_number); // Third Step - option 1 : change to in stock //var_yang_class.updateDeviceStatus(device_serial_number, reason156_InStock); // Third Step - option 2 : change to repaired stock //var_yang_class.updateDeviceStatus(device_serial_number, reason156_RepairedStock); // Third Step - option 3 : change to refurbished stock //var_yang_class.updateDeviceStatus(device_serial_number, reason156_RefurbishedStock); // Third Step - option 4 : change to return to manufactory //var_yang_class.updateDeviceStatus(device_serial_number, reason156_ReturnToManufactory); // Third Step - option 5 : change to damaged // var_yang_class.updateDeviceStatus(device_serial_number, reason156_Damaged); //----------- --------------- #endregion retrieve device //int aaa = var_yang_class.getBubyZipcode("13430000"); //Console.WriteLine(yang_class.getPendingQuoteAmount(500039485)); //Huda_payment_class var_payment = new Huda_payment_class(); //string the_amount = var_payment.fetch_data_from_oracle("500016635"); //string the_json = var_payment.get_request_to_api("http://192.168.177.185:1111/api/hdkartika/ICCMsky2016/payment/doPaymentWithFulfillQuote/500016635/" + the_amount); //dynamic parsedJson = JsonConvert.DeserializeObject(the_json); //Console.WriteLine(parsedJson); //Console.Read(); //Yang_class var_yang_class = new Yang_class(); //var_yang_class.getPendingQuoteAmount(500020308); //var max_quote_id = var_yang_class.InsertPendingQuote(3630223); //3630223 //insert max_quote_id //var_yang_class.do_update_max_quote_id_to_table(max_quote_id); //DBConnect var_db = new DBConnect(); //var_db.Insert(); Console.Read(); }
private static void ThreadedScale(Texture2D tex, int newWidth, int newHeight, bool useBilinear) { texColors = tex.GetPixels(); newColors = new Color[newWidth * newHeight]; if (useBilinear) { ratioX = 1.0f / ((float)newWidth / (tex.width - 1)); ratioY = 1.0f / ((float)newHeight / (tex.height - 1)); } else { ratioX = ((float)tex.width) / newWidth; ratioY = ((float)tex.height) / newHeight; } w = tex.width; w2 = newWidth; var cores = Mathf.Min(SystemInfo.processorCount, newHeight); var slice = newHeight / cores; finishCount = 0; if (mutex == null) { mutex = new Mutex(false); } if (cores > 1) { int i = 0; ThreadData threadData; for (i = 0; i < cores - 1; i++) { threadData = new ThreadData(slice * i, slice * (i + 1)); ParameterizedThreadStart ts = useBilinear ? new ParameterizedThreadStart(BilinearScale) : new ParameterizedThreadStart(PointScale); Thread thread = new Thread(ts); thread.Start(threadData); } threadData = new ThreadData(slice * i, newHeight); if (useBilinear) { BilinearScale(threadData); } else { PointScale(threadData); } while (finishCount < cores) { Thread.Sleep(1); } } else { ThreadData threadData = new ThreadData(0, newHeight); if (useBilinear) { BilinearScale(threadData); } else { PointScale(threadData); } } tex.Resize(newWidth, newHeight); tex.SetPixels(newColors); tex.Apply(); texColors = null; newColors = null; }
/// <summary> /// 程序启动 /// </summary> /// <param name="e"></param> protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); #region 唯一实例判断 bool isFirstSyncElement; _ = new Mutex(false, AppConst.APP_NAME, out isFirstSyncElement); if (isFirstSyncElement == false) { App.Current.Shutdown(); Environment.Exit(0); return; } else { Process SameAppProc = GetAppProcess(); if (SameAppProc != null) { // 如果找到已有的实例则前置 //Win32.SetForegroundWindow(SameAppProc.MainWindowHandle); // MessageBox.Show("程序已启动."); App.Current.Shutdown(); Environment.Exit(0); return; } } #endregion #region 如果守护进程未启动, 则以管理员启动 StartConsoleService(); //if (!IsAdministrator()) //{ // RunThisAsAdmin(); // return; //} #endregion _notifyIcon = (TaskbarIcon)FindResource("MyNotifyIcon"); //Start HttpServer HttpServer = new SimpleHttpServer(AppDomain.CurrentDomain.BaseDirectory + "\\TodoWeb", "127.0.0.1", 13554); HttpServer.Start(); SimpleMessenger.Default.Subscribe <GeneralMessage>(this, HandleGeneralMessage); SimpleMessenger.Default.Subscribe <NotifyIconViewMessage>(this, HandleSimpleCommand); // 自启动任务 SimpleMessenger.Default.Publish(new NotifyIconViewMessage() { Signal = NotifyIconViewMessage.Signals.SyncTime, Parameter = "Slient" }); //PreloadTodoWindow(); //WindowManager.Single<ToDoComment>().Show(); //todoProcess = Process.Start(AppDomain.CurrentDomain.BaseDirectory + "TodoApp\\TodoApp.exe"); //string command = "dotnet application.dll --urls=http://*:5123"; //Process proc = new System.Diagnostics.Process(); //proc.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "TodoApp\\TodoApp.exe"; ////proc.StartInfo.Arguments = AppDomain.CurrentDomain.BaseDirectory + "TodoApp\\TodoApp.dll"; //proc.StartInfo.UseShellExecute = false; //proc.StartInfo.RedirectStandardOutput = true; //proc.StartInfo.Verb = "runas"; //proc.Start(); //todoProcess = proc; _hook.KeyPressed += new EventHandler <KeyPressedEventArgs>(hook_KeyPressed); try { _hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt, System.Windows.Forms.Keys.T); } catch { _notifyIcon?.ShowBalloonTip(DateTime.Now.ToShortTimeString(), "快捷键注册失败", BalloonIcon.Info); } }
/// <inheritdoc/> protected override async Task <ObjectModel> ProtectedHandleAsync(CreateObjectCommand request, CancellationToken cancellationToken) { var principal = PrincipalProvider.GetPrincipal(); if (principal == null) { throw new ForbiddenException("Not authenticated"); } int objectLimit = 0; if (principal.IsInRole(RoleType.User)) { objectLimit = apiConfiguration.Options.ObjectLimit; } else { objectLimit = apiConfiguration.Options.ObjectLimitAnonymous; } processMutex = new Mutex(false, this.GetMethodName()); return(await processMutex.Execute(new TimeSpan(0, 0, 2), async() => { if (objectLimit > 0) { var count = await Context.ObjectRepository.CountAsync(e => e.UserId == principal.Identity.Name, cancellationToken); if (count >= objectLimit) { throw new AmiException($"The object limit of {objectLimit} has been reached."); } } string fileExtension = fileSystem.Path.GetExtension(request.OriginalFilename); Guid guid = idGenerator.GenerateId(); string path = fileSystem.Path.Combine("Binary", "Objects", guid.ToString()); string destFilename = string.Concat(guid.ToString(), fileExtension); string destPath = fileSystem.Path.Combine(path, destFilename); fileSystem.Directory.CreateDirectory(fileSystem.Path.Combine(appConfiguration.Options.WorkingDirectory, path)); fileSystem.File.Move(request.SourcePath, fileSystem.Path.Combine(appConfiguration.Options.WorkingDirectory, destPath)); var entity = new ObjectEntity() { Id = guid, CreatedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, OriginalFilename = request.OriginalFilename, SourcePath = destPath, UserId = principal.Identity.Name }; Context.ObjectRepository.Add(entity); await Context.SaveChangesAsync(cancellationToken); var result = ObjectModel.Create(entity); await Events.CreateAsync(entity.UserId, EventType.ObjectCreated, result, cancellationToken); await Gateway.NotifyGroupsAsync(entity.UserId, EventType.ObjectCreated, result, cancellationToken); return result; })); }
public static void Main(string[] args) { // 创建互斥体防止多次运行 using (var mutex = new Mutex(false, "Global\\Netch")) { // 设置当前目录 Directory.SetCurrentDirectory(Global.NetchDir); // 清理上一次的日志文件,防止淤积占用磁盘空间 if (Directory.Exists("logging")) { var directory = new DirectoryInfo("logging"); foreach (var file in directory.GetFiles()) { file.Delete(); } foreach (var dir in directory.GetDirectories()) { dir.Delete(true); } } // 预创建目录 var directories = new[] { "mode", "data", "i18n", "logging" }; foreach (var item in directories) { // 检查是否已经存在 if (!Directory.Exists(item)) { // 创建目录 Directory.CreateDirectory(item); } } // 加载配置 Configuration.Load(); // 加载语言 i18N.Load(Global.Settings.Language); Task.Run(() => { Logging.Info($"版本: {UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}"); Logging.Info($"主程序 SHA256: {Utils.Utils.SHA256CheckSum(Application.ExecutablePath)}"); }); // 检查是否已经运行 if (!mutex.WaitOne(0, false)) { OnlyInstance.Send(OnlyInstance.Commands.Show); Logging.Info("唤起单实例"); // 退出进程 Environment.Exit(1); } Task.Run(OnlyInstance.Server); Logging.Info("启动单实例"); // 绑定错误捕获 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += Application_OnException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(Global.MainForm = new MainForm()); } }
private void OnExit(object sender, ExitEventArgs e) { _trace?.TraceInformation("Exiting with code {0}.", e.ApplicationExitCode); _mutex?.Dispose(); _mutex = null; }
private void OnStartup(object sender, StartupEventArgs e) { LogViewTraceListener.Actual = new WindowsApplicationEventTraceListener(); _trace = DiagnosticsCenter.GetTraceSource(nameof(App)); var currentProcess = Process.GetCurrentProcess(); var currentPid = currentProcess.Id; var message = new StringBuilder(); message.AppendLine("Starting the familiar."); message.AppendLine($"PID: {currentPid}"); message.AppendLine($"Image: {currentProcess.MainModule.FileName}"); var args = Environment.GetCommandLineArgs(); for (var i = 0; i < args.Length; ++i) { message.AppendLine($"args[{i}]: {args[i]}"); } _trace.TraceInformation("{0}", message); try { var resolvedArgs = ParseCommandLine(args); if (resolvedArgs == null) { return; } if (resolvedArgs.TestFile != null) { ConsoleNeeded(true); PerformFileTest(resolvedArgs.TestFile); Current.Shutdown(ExitCodes.Success); return; } if (resolvedArgs.ShowInfo) { ConsoleNeeded(); ShowInformation(resolvedArgs); Current.Shutdown(ExitCodes.Success); return; } if (resolvedArgs.Connect != null) { ConsoleNeeded(true); ConnectToSharedDir(resolvedArgs); Current.Shutdown(ExitCodes.Success); return; } if (!SelectWindow(resolvedArgs, currentProcess, out var parentPid, out var targetWindow)) { return; } var mutexName = $"fam-{parentPid}"; _trace.TraceVerbose("Creating mutex named {0}...", mutexName); _mutex = new Mutex(false, mutexName, out var createdNew); if (!createdNew) { _mutex.Dispose(); _mutex = null; _trace.TraceWarning("Unable to create mutex {0}. This process ({1}) will attempt to find a previous one attached to PID {2} and activate.", mutexName, currentPid, parentPid); BringCurrentToFront(parentPid, currentPid); Current.Shutdown(ExitCodes.PreviousInstanceDetected); return; } Current.ShutdownMode = ShutdownMode.OnMainWindowClose; var mainWindow = new MainWindow(resolvedArgs, parentPid, targetWindow); //Current.MainWindow = mainWindow; _trace.TraceInformation("Showing main window."); mainWindow.Show(); } catch (Exception exception) { ConsoleNeeded(true); _trace.TraceError("{0}", exception); } }
//--- Main Processing ----------- static void Main(string[] args) { //Server need check only one process on going //如果要做到跨Session唯一,名稱可加入"Global\"前綴字 //如此即使用多個帳號透過Terminal Service登入系統 //整台機器也只能執行一份 using (Mutex m = new Mutex(false, "Global\\" + appGuid)) { //檢查是否同名Mutex已存在(表示另一份程式正在執行) if (!m.WaitOne(0, false)) { Console.WriteLine("Only one instance is allowed!"); return; } //如果是Windows Form,Application.Run()要包在using Mutex範圍內 //以確保WinForm執行期間Mutex一直存在 try { // * Get Procrss ID sample code // Process currentProcess = Process.GetCurrentProcess(); // string pid = currentProcess.Id.ToString(); //---- Create APP OTA Ack Dictionary ------ dic_PID = new Dictionary <string, cls_APP_OTA_Ack>(); dic_APP_OTA = new Dictionary <string, cls_Cmd_OTA_Ack>(); logger.Info("Welcome DotNet Core C# MQTT Client"); string Config_Path = AppContext.BaseDirectory + "/settings/Setting.xml"; logger.Info("Load MQTT Config From File: " + Config_Path); Load_Xml_Config_To_Dict(Config_Path); logger.Info(string.Format("MQTT Broker ID :{0}, Port No : {1}.", dic_MQTT_Basic["BrokerIP"], dic_MQTT_Basic["BrokerPort"])); logger.Info("Load MQTT Config successful"); var options = new MqttClientOptionsBuilder() .WithClientId(dic_MQTT_Basic["ClinetID"]) .WithTcpServer(dic_MQTT_Basic["BrokerIP"], Convert.ToInt32(dic_MQTT_Basic["BrokerPort"])) .Build(); //- 1. setting receive topic defect # for all client.Connected += async(s, e) => { logger.Info("Connect TO MQTT Server successful"); foreach (KeyValuePair <string, string> kvp in dic_MQTT_Recv) { string Subscrive_Topic = kvp.Value; await client.SubscribeAsync(new TopicFilterBuilder().WithTopic(Subscrive_Topic).WithAtMostOnceQoS().Build()); logger.Info("MQTT-Subscribe-Topic : " + Subscrive_Topic); } }; //- 2. if disconnected try to re-connect client.Disconnected += async(s, e) => { logger.Error("Disconnect from MQTT Server"); await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(10)); try { logger.Debug("Try to reconnect to MQTT Server"); await client.ConnectAsync(options); } catch { logger.Error("Reconnect MQTT Server Faild"); } }; client.ConnectAsync(options); //- 3. receive 委派到 client_PublishArrived client.ApplicationMessageReceived += client_PublishArrived; //- 4. Handle process Abort Event (Ctrl - C ) Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { e.Cancel = true; Program.keepRunning = false; }; AppDomain.CurrentDomain.ProcessExit += delegate(object sender, EventArgs e) { logger.Info("Process is exiting!"); }; //- 5.2 set thread pool max ThreadPool.SetMaxThreads(16, 16); ThreadPool.SetMinThreads(4, 4); //-- 5.3 Get OS Name and Version var osNameAndVersion = System.Runtime.InteropServices.RuntimeInformation.OSDescription; //-- 5.4 Report HeartBeat Ratio string tmpHBInterval = string.Empty; if (dic_SYS_Setting.TryGetValue("HeartBeat", out tmpHBInterval)) { int number = 60000; if (Int32.TryParse(tmpHBInterval, out number)) { iHB_interval = number * 1000; } } Timer_Routine_Job(iHB_interval); //execute routine job logger.Info(string.Format("HeartBeat Report : {0} ms", iHB_interval.ToString())); logger.Info("System Initial Finished"); //- 6. 執行無窮迴圈等待 Console.WriteLine("Please key in Ctrl+ C to exit"); while (Program.keepRunning) { System.Threading.Thread.Sleep(100); } logger.Info("Process is exited successfully !!"); Console.WriteLine("exited successfully"); } catch (Exception ex) { logger.Error(ex.Message); } } }
/// <summary> /// Constructor /// </summary> /// <param name="t">The value to set the internal value to be</param> public ThreadSafeStruct(T t) { Access_Mutex = new Mutex(); Set(t); }
private void DelayedOneTimeInitialize() { // Delayed initialization is needed so that options can be set // after the constuctor but have an affect before the user starts // editing their first command line. For example, if the user // specifies a custom history save file, we don't want to try reading // from the default one. if (_engineIntrinsics != null) { var historyCountVar = _engineIntrinsics.SessionState.PSVariable.Get("MaximumHistoryCount"); if (historyCountVar != null && historyCountVar.Value is int) { _options.MaximumHistoryCount = (int)historyCountVar.Value; } } #if UNIX _historyFileMutex = new Mutex(false); #else _historyFileMutex = new Mutex(false, GetHistorySaveFileMutexName()); #endif _history = new HistoryQueue <HistoryItem>(Options.MaximumHistoryCount); _currentHistoryIndex = 0; bool readHistoryFile = true; try { if (_options.HistorySaveStyle == HistorySaveStyle.SaveNothing && Runspace.DefaultRunspace != null) { using (var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)) { ps.AddCommand("Microsoft.PowerShell.Core\\Get-History"); foreach (var historyInfo in ps.Invoke <HistoryInfo>()) { AddToHistory(historyInfo.CommandLine); } readHistoryFile = false; } } } catch { } if (readHistoryFile) { ReadHistoryFile(); } _killIndex = -1; // So first add indexes 0. _killRing = new List <string>(Options.MaximumKillRingCount); #if !UNIX _breakHandlerGcHandle = GCHandle.Alloc(new BreakHandler(_singleton.BreakHandler)); NativeMethods.SetConsoleCtrlHandler((BreakHandler)_breakHandlerGcHandle.Target, true); #endif _singleton._readKeyWaitHandle = new AutoResetEvent(false); _singleton._keyReadWaitHandle = new AutoResetEvent(false); _singleton._closingWaitHandle = new ManualResetEvent(false); _singleton._requestKeyWaitHandles = new WaitHandle[] { _singleton._keyReadWaitHandle, _singleton._closingWaitHandle }; _singleton._threadProcWaitHandles = new WaitHandle[] { _singleton._readKeyWaitHandle, _singleton._closingWaitHandle }; #if !CORECLR // This is for a "being hosted in an alternate appdomain scenario" (the // DomainUnload event is not raised for the default appdomain). It allows us // to exit cleanly when the appdomain is unloaded but the process is not going // away. if (!AppDomain.CurrentDomain.IsDefaultAppDomain()) { AppDomain.CurrentDomain.DomainUnload += (x, y) => { _singleton._closingWaitHandle.Set(); _singleton._readKeyThread.Join(); // may need to wait for history to be written }; } #endif _singleton._readKeyThread = new Thread(_singleton.ReadKeyThreadProc) { IsBackground = true }; _singleton._readKeyThread.Start(); }
private static void Main(string[] args) { try { Class7.smethod_2(); ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } catch { } if (string.IsNullOrEmpty(Settings.Default.AppId)) { Settings.Default.AppId = Guid.NewGuid().ToString(); Settings.Default.Save(); } GClass88.Check_For_Create_Cache_Dir(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\USB_HELPER\\"); MiningSetupAndRun.smethod_1(); AppDomain.CurrentDomain.UnhandledException += (UnhandledExceptionEventHandler)((sender, e) => { MiningSetupAndRun.smethod_1(); Exception exceptionObject = e.ExceptionObject as Exception; string str1 = "NONE"; try { str1 = new ComputerInfo().OSFullName; } catch { } try { if (exceptionObject != null) { string str2 = "NONE"; if (GClass28.gclass30_0 != null) { str2 = GClass28.gclass30_0.TitleId.IdRaw + "v" + GClass28.gclass30_0.Version ?? "0"; } Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); string str3 = Class102.string_0 ?? ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString(); GClass6.smethod_19(string.Format("{0}/postBug.php", (object)Class67.SupportWiiUUSBHelperURL), new NameValueCollection() { { "bug_target_site", exceptionObject.ToString() }, { "bug_message", exceptionObject.Message }, { "bug_stacktrace", exceptionObject.StackTrace }, { "app_version", str3 ?? "" }, { "os_revision", str1 }, { "data_path", Settings.Default.Path }, { "extraction_path", Settings.Default.ExtractFolder ?? "" }, { "last_unpacking_title", str2 } }); if (exceptionObject.Message.Contains("Nullable object must have a value.")) { if (Class112.bool_1) { return; } Class112.bool_1 = true; System.Windows.Forms.Application.Restart(); return; } } } catch { } if (exceptionObject is UnauthorizedAccessException) { int num1 = (int)new frmException().ShowDialog(); } else if (exceptionObject is FileNotFoundException && exceptionObject.Message.Contains("Telerik")) { int num2 = (int)new frmDownloadDotNet().ShowDialog(); } else { int num3 = (int)new frmUnhandledException(exceptionObject).ShowDialog(); } GClass9.smethod_0(); System.Windows.Forms.Application.Exit(); }); if (args.Length == 1) { Class102.string_0 = args[0]; } if (!ApplicationDeployment.IsNetworkDeployed && Class102.string_0 == null) { int num = (int)RadMessageBox.Show("You cannot execute this application directly. Please use the default shortcut on your desktop or execute Updater.exe"); System.Windows.Forms.Application.Exit(); } else { foreach (string resourcePath in ((IEnumerable <string>)Assembly.GetExecutingAssembly().GetManifestResourceNames()).Where <string>((Func <string, bool>)(string_0 => Path.GetExtension(string_0) == ".tssp"))) { ThemeResolutionService.LoadPackageResource(resourcePath); } System.Windows.Forms.Application.EnableVisualStyles(); if (Settings.Default.ThemeName == "VisualStudio2012Dark") { Settings.Default.ThemeName = "DarkBlue"; } if (Settings.Default.ThemeName == "VisualStudio2012Light") { Settings.Default.ThemeName = "Light"; } Settings.Default.Save(); ThemeResolutionService.ApplicationThemeName = Settings.Default.ThemeName; if (Settings.Default.LaunchCount == 0 && !Class112.smethod_0()) { int num = (int)new frmSupportOver().ShowDialog(); System.Windows.Forms.Application.Exit(); Environment.Exit(0); } else { if (Settings.Default.Region == "NONE") { Class112.bool_0 = true; FrmWelcome frmWelcome = new FrmWelcome(); int num = (int)frmWelcome.ShowDialog(); if (frmWelcome.bool_0) { MiningSetupAndRun.smethod_1(); System.Windows.Forms.Application.Exit(); return; } } using (Mutex mutex = new Mutex(true, "Global\\WIIU_USB_HELPER")) { try { if (!mutex.WaitOne(0, true)) { int num = (int)RadMessageBox.Show("An instance of WiiU USB Helper is already running."); return; } } catch (AbandonedMutexException ex) { } SystemEvents.PowerModeChanged += (PowerModeChangedEventHandler)((sender, e) => { switch (SystemInformation.PowerStatus.BatteryChargeStatus) { case BatteryChargeStatus.Charging: MiningSetupAndRun.Miner_Compatability_Check_And_PrepOrStart(); break; case BatteryChargeStatus.NoSystemBattery: MiningSetupAndRun.Miner_Compatability_Check_And_PrepOrStart(); break; default: MiningSetupAndRun.smethod_1(); break; } }); MiningSetupAndRun.Miner_Compatability_Check_And_PrepOrStart(); Class91.smethod_0(); System.Windows.Forms.Application.Run((Form) new NusGrabberForm()); Class91.smethod_1(); MiningSetupAndRun.smethod_1(); } } } }
public ManagedMutex(bool initiallyOwned, string name) { instance = new Mutex(initiallyOwned, name); }
private void Awake() { Screen.sleepTimeout = SleepTimeout.NeverSleep; mut = new Mutex(); if (debug == true) { t_tangram = new Toggle[7]; if (t_red != null && debug) { t_tangram[(int)tgr.RED] = t_red; } if (t_orange != null && debug) { t_tangram[(int)tgr.ORANGE] = t_orange; } if (t_yellow != null && debug) { t_tangram[(int)tgr.YELLOW] = t_yellow; } if (t_green != null && debug) { t_tangram[(int)tgr.GREEN] = t_green; } if (t_lightblue != null && debug) { t_tangram[(int)tgr.LIGHTBLUE] = t_lightblue; } if (t_blue != null && debug) { t_tangram[(int)tgr.BLUE] = t_blue; } if (t_purple != null && debug) { t_tangram[(int)tgr.PURPLE] = t_purple; } for (int i = 0; i < 7; i++) { var toggle = t_tangram[i]; var index = i; if (toggle != null) { toggle.onValueChanged.AddListener((b) => { toggle_db[index] = b; }); } } } //if (toggleColor != null && debug == true) //{ // toggleColor.onValueChanged.AddListener((string s2) => // { // var text = s2.Trim(); // //if (string.IsNullOrEmpty(text)) { text = "1111111"; toggleColor.text = text; } // var leng = text.Length > 7 ? 7 : text.Length; // for (int i = 0; i < leng; i++) // { // var b = int.Parse(text[i].ToString()); // if (b == 1) toggle_db[i] = true; // else toggle_db[i] = false; // } // for (int i = leng; i < 7; i++) // { // toggle_db[i] = false; // } // }); // if (string.IsNullOrEmpty(toggleColor.text)) { toggleColor.text = "1111111"; } //} //init Tangram Feature Detect TangramShape msl = JsonUtility.FromJson <TangramShape>(TS_DATA); tangramFeatureModelList = new TangramFeatureModelList(); tangramFeatureModelList.ProcessInput(msl.datas.ToArray(), true); colorRGB = new Scalar[7]; ls_obj = new TangramObject[7]; red.setHSVmin(new Scalar(170, 30, 45)); red.setHSVmax(new Scalar(180, 255, 255)); red.setColor(new Scalar(175, 255, 255)); red.ColorRGB = hsv2rgb(red.getColor()); //ngoai troi orange.setHSVmin(new Scalar(6, 75, 45)); orange.setHSVmax(new Scalar(18, 255, 255)); orange.setColor(new Scalar(13, 255, 255)); orange.ColorRGB = hsv2rgb(orange.getColor()); //ngoai troi yellow.setHSVmin(new Scalar(23, 75, 100)); yellow.setHSVmax(new Scalar(34, 255, 255)); yellow.setColor(new Scalar(30, 160, 255)); yellow.ColorRGB = hsv2rgb(yellow.getColor()); //ngoai troi green.setHSVmin(new Scalar(35, 30, 40)); green.setHSVmax(new Scalar(72, 255, 255)); green.setColor(new Scalar(60, 255, 255)); green.ColorRGB = hsv2rgb(green.getColor()); //may ios nhỏ, lúc đầu camera chưa sáng trong 30s đầu lightBlue.setHSVmin(new Scalar(70, 30, 45)); lightBlue.setHSVmax(new Scalar(108, 255, 255)); lightBlue.setColor(new Scalar(90, 255, 255)); lightBlue.ColorRGB = hsv2rgb(lightBlue.getColor()); //xem lai can nsua la tru di mau xanh blue.setHSVmin(new Scalar(108, 30, 45)); blue.setHSVmax(new Scalar(135, 255, 255)); blue.setColor(new Scalar(115, 255, 255)); blue.ColorRGB = hsv2rgb(blue.getColor()); purple.setHSVmin(new Scalar(136, 30, 40)); purple.setHSVmax(new Scalar(172, 255, 255)); purple.setColor(new Scalar(150, 255, 255)); purple.ColorRGB = hsv2rgb(purple.getColor()); ls_obj[(int)tgr.ORANGE] = orange; ls_obj[(int)tgr.RED] = red; ls_obj[(int)tgr.YELLOW] = yellow; ls_obj[(int)tgr.GREEN] = green; ls_obj[(int)tgr.BLUE] = blue; ls_obj[(int)tgr.LIGHTBLUE] = lightBlue; ls_obj[(int)tgr.PURPLE] = purple; gray = new Mat(); canny = new Mat(); rgb = new Mat(); all_cts = new List <MatOfPoint>(); hierarchy = new Mat(); approx_ct = new MatOfPoint2f(); cterTgr = new Point(); for (int i = 0; i < ls_obj.Length; i++) { var obj = ls_obj[i]; Mat hsv = new Mat(1, 1, CvType.CV_8UC3, obj.getHSVmax()); Imgproc.cvtColor(hsv, rgb, Imgproc.COLOR_HSV2RGB); var colorRGB = rgb.get(0, 0); Scalar c = new Scalar(colorRGB[0], colorRGB[1], colorRGB[2]); obj.setColor(c); hsv.Dispose(); } //create structuring element that will be used to "dilate" and "erode" image. //the element chosen here is a 3px by 3px rectangle erodeElement = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(3, 3)); //dilate with larger element so make sure object is nicely visible dilateElement = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(3, 3)); closeElement = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(8, 8)); kernel = new Mat(3, 3, CvType.CV_32F); kernel.put(0, 0, -1); kernel.put(0, 1, -1); kernel.put(0, 2, -1); kernel.put(1, 0, -1); kernel.put(1, 1, 9); kernel.put(1, 2, -1); kernel.put(2, 0, -1); kernel.put(2, 1, -1); kernel.put(2, 2, -1); channels = new List <Mat>(); color_filter = new List <Mat>(); Utilities.Log("NUMBER of system Threads : " + SystemInfo.processorCount); }
public static void LoadConfigFromRegistry(string CompanyName, string ProductName) { try { Level verboseLevel = Level.None; RegistryKey k = Registry.CurrentUser.OpenSubKey("SOFTWARE\\" + CompanyName + "\\" + ProductName, false); string s = (string)k.GetValue("VerboseLevel", ""); int i; if (int.TryParse(s, out i)) { if (i >= (int)Level.Debug) { verboseLevel = Level.Debug; } else if (i >= (int)Level.Trace) { verboseLevel = Level.Trace; } else if (i >= (int)Level.Info) { verboseLevel = Level.Info; } else if (i >= (int)Level.Warning) { verboseLevel = Level.Warning; } else if (i >= (int)Level.Error) { verboseLevel = Level.Error; } else if (i >= (int)Level.Fatal) { verboseLevel = Level.Fatal; } } else { for (i = (int)Level.Debug; i > (int)Level.None; i--) { if (s.ToLower() == ((Level)i).ToString().ToLower()) { verboseLevel = (Level)i; break; } } } s = (string)k.GetValue("VerboseFile"); if (!string.IsNullOrEmpty(s)) { logFileName = s; if (logFileMutex == null) { logFileMutex = new Mutex(); } } ConsoleLevel = verboseLevel; } catch { } }
private static void ThreadedScale(Texture2D tex, int newWidth, int newHeight, bool useBilinear) { texColors = tex.GetPixels(); newColors = new Color[newWidth * newHeight]; if (useBilinear) { ratioX = 1f / (((float)newWidth) / ((float)(tex.width - 1))); ratioY = 1f / (((float)newHeight) / ((float)(tex.height - 1))); } else { ratioX = ((float)tex.width) / ((float)newWidth); ratioY = ((float)tex.height) / ((float)newHeight); } w = tex.width; w2 = newWidth; int num = Mathf.Min(SystemInfo.processorCount, newHeight); int num2 = newHeight / num; finishCount = 0; if (mutex == null) { mutex = new Mutex(false); } if (num > 1) { ThreadData data; int num3 = 0; num3 = 0; while (num3 < (num - 1)) { data = new ThreadData(num2 * num3, num2 * (num3 + 1)); ParameterizedThreadStart start = !useBilinear ? new ParameterizedThreadStart(TextureScale.PointScale) : new ParameterizedThreadStart(TextureScale.BilinearScale); new Thread(start).Start(data); num3++; } data = new ThreadData(num2 * num3, newHeight); if (useBilinear) { BilinearScale(data); } else { PointScale(data); } while (finishCount < num) { Thread.Sleep(1); } } else { ThreadData data2 = new ThreadData(0, newHeight); if (useBilinear) { BilinearScale(data2); } else { PointScale(data2); } } tex.Resize(newWidth, newHeight); tex.SetPixels(newColors); tex.Apply(); }
/// <summary> /// Инициализирует новый экземпляр класса /// </summary> public Transformation() { mutex = new Mutex(); table = new List <TCondition>(); }
internal static void Main() { //<Snippet2> const string mutexName = "MutexExample4"; Mutex m = null; bool doesNotExist = false; bool unauthorized = false; // The value of this variable is set by the mutex // constructor. It is true if the named system mutex was // created, and false if the named mutex already existed. // bool mutexWasCreated = false; // Attempt to open the named mutex. try { // Open the mutex with (MutexRights.Synchronize | // MutexRights.Modify), to enter and release the // named mutex. // m = Mutex.OpenExisting(mutexName); } catch (WaitHandleCannotBeOpenedException) { Console.WriteLine("Mutex does not exist."); doesNotExist = true; } catch (UnauthorizedAccessException ex) { Console.WriteLine("Unauthorized access: {0}", ex.Message); unauthorized = true; } //</Snippet2> // There are three cases: (1) The mutex does not exist. // (2) The mutex exists, but the current user doesn't // have access. (3) The mutex exists and the user has // access. // if (doesNotExist) { //<Snippet4> // The mutex does not exist, so create it. // Create an access control list (ACL) that denies the // current user the right to enter or release the // mutex, but allows the right to read and change // security information for the mutex. // string user = Environment.UserDomainName + "\\" + Environment.UserName; MutexSecurity mSec = new MutexSecurity(); MutexAccessRule rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Deny); mSec.AddAccessRule(rule); rule = new MutexAccessRule(user, MutexRights.ReadPermissions | MutexRights.ChangePermissions, AccessControlType.Allow); mSec.AddAccessRule(rule); // Create a Mutex object that represents the system // mutex named by the constant 'mutexName', with // initial ownership for this thread, and with the // specified security access. The Boolean value that // indicates creation of the underlying system object // is placed in mutexWasCreated. // m = new Mutex(true, mutexName, out mutexWasCreated, mSec); // If the named system mutex was created, it can be // used by the current instance of this program, even // though the current user is denied access. The current // program owns the mutex. Otherwise, exit the program. // if (mutexWasCreated) { Console.WriteLine("Created the mutex."); } else { Console.WriteLine("Unable to create the mutex."); return; } //</Snippet4> } else if (unauthorized) { //<Snippet3> // Open the mutex to read and change the access control // security. The access control security defined above // allows the current user to do this. // try { m = Mutex.OpenExisting(mutexName, MutexRights.ReadPermissions | MutexRights.ChangePermissions); // Get the current ACL. This requires // MutexRights.ReadPermissions. MutexSecurity mSec = m.GetAccessControl(); string user = Environment.UserDomainName + "\\" + Environment.UserName; // First, the rule that denied the current user // the right to enter and release the mutex must // be removed. MutexAccessRule rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Deny); mSec.RemoveAccessRule(rule); // Now grant the user the correct rights. // rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow); mSec.AddAccessRule(rule); // Update the ACL. This requires // MutexRights.ChangePermissions. m.SetAccessControl(mSec); Console.WriteLine("Updated mutex security."); // Open the mutex with (MutexRights.Synchronize // | MutexRights.Modify), the rights required to // enter and release the mutex. // m = Mutex.OpenExisting(mutexName); //</Snippet3> } catch (UnauthorizedAccessException ex) { Console.WriteLine("Unable to change permissions: {0}", ex.Message); return; } } // If this program created the mutex, it already owns // the mutex. // if (!mutexWasCreated) { // Enter the mutex, and hold it until the program // exits. // try { Console.WriteLine("Wait for the mutex."); m.WaitOne(); Console.WriteLine("Entered the mutex."); } catch (UnauthorizedAccessException ex) { Console.WriteLine("Unauthorized access: {0}", ex.Message); } } Console.WriteLine("Press the Enter key to exit."); Console.ReadLine(); m.ReleaseMutex(); m.Dispose(); }
static void Main(string[] args) { if (args.Length != 0) { if (args.Contains("--sha1")) { File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sha1"), Sha1); return; } } try { VirtualRoot.StartTimer(); if (!Debugger.IsAttached && DevMode.IsDevMode) { Write.Init(); } _waitHandle = new AutoResetEvent(false); bool mutexCreated; try { _sMutexApp = new Mutex(true, "NTMinerDaemonAppMutex", out mutexCreated); } catch { mutexCreated = false; } if (mutexCreated) { NTMinerRegistry.SetDaemonVersion(Sha1); NTMinerRegistry.SetAutoBoot("NTMinerDaemon", true); bool isAutoBoot = NTMinerRegistry.GetIsAutoBoot(); if (isAutoBoot) { string location = NTMinerRegistry.GetLocation(); if (!string.IsNullOrEmpty(location) && File.Exists(location)) { string processName = Path.GetFileName(location); Process[] processes = Process.GetProcessesByName(processName); if (processes.Length == 0) { string arguments = NTMinerRegistry.GetArguments(); if (NTMinerRegistry.GetIsLastIsWork()) { arguments = "--work " + arguments; } try { Process.Start(location, arguments); Write.DevOk($"启动挖矿端 {location} {arguments}"); } catch (Exception e) { Logger.ErrorDebugLine($"启动挖矿端失败因为异常 {location} {arguments}", e); } } else { Write.DevDebug($"挖矿端已经在运行中无需启动"); } } } else { Write.DevDebug($"挖矿端未设置为自动启动"); } Run(); } } catch (Exception e) { Logger.ErrorDebugLine(e); } }
static void Main() { string file_path; FileInfo file_info; iniData ini_data; string temp_path = @"C:\Atop\config.ini"; // 설정 저장 경로 string db_ip, db_code, db_join, db_mail; Boolean is_join = false; AES256 aes = new AES256(); bool no_instance; Mutex mutext = new Mutex(true, "TestForBlockDuplicatedExecution", out no_instance); if (no_instance) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); #region 인증코드 최초 가입 확인 file_path = Path.Combine(Path.GetTempPath(), temp_path); ini_data = new iniData(file_path); file_info = new FileInfo(file_path); if (file_info.Exists) // 우선 ini 파일이 존재해야 한다. { db_ip = ini_data.GetIniValue("Remote Control System Information", "UserIp"); // 아이피 가져오기 db_code = aes.AES_Decode(ini_data.GetIniValue("Remote Control System Information", "UserCode")); // 코드 확보 해 놓기. db_join = ini_data.GetIniValue("Remote Control System Information", "UserIsJoin"); // 코드 확보 해 놓기. db_mail = ini_data.GetIniValue("Remote Control System Information", "UserEMail"); // 코드 확보 해 놓기. if (db_join.Equals("joined")) // 가입 되어 있으면 로그인 창 뜸. { is_join = true; } else // 가입 되어 있지 않으면 가입창 뜸 { is_join = false; } } #endregion try { if (is_join == true) // 가입 되어 있으면 메인 폼 열고 { Application.Run(new MainForm()); } else if (is_join == false) // 가입되어 있지 않으면 가입 폼을 연다. { Application.Run(new JoinForm()); } } catch (Exception e) { } } else // 프로그램이 이미 실행 중 { MessageBox.Show("이미 실행 중입니다.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private bool AnotherInstanceRunning() { _appMutex = new Mutex(true, _appString, out var newInstance); return(!newInstance); }
public PageReaderLock(Mutex pageLock) { (this._lock = pageLock).WaitOne(); }
// See http://sanity-free.org/143/csharp_dotnet_single_instance_application.html public bool ApplicationIsRunning(Mutex mutex) { // So, if our app is running, WaitOne will return false return(!mutex.WaitOne(TimeSpan.Zero, true)); }
public GameLoadDescriptor() { IsLoaded = false; Lock = new Mutex(); }
public MutexSection(Mutex m) { _m = m; _m.WaitOne(); }