AddAccessRule() public method

public AddAccessRule ( SemaphoreAccessRule rule ) : void
rule SemaphoreAccessRule
return void
        public GlobalReaderWriterLock(string nameOfThisLock)
        {
            _hatName = nameOfThisLock;

            // we need to make two native sync objects, a mutex and a semaphore
            // that are global so every process and user on the system can share them as long as they agree on the lock's name
            string mutexId = string.Format("Global\\Mut_{0}", _hatName);
            string semaphoreId = string.Format("Global\\Sem_{0}", _hatName);
            bool iDontCareWhetherItsNew;
            {
                MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                MutexSecurity securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);

                _holdTheHat = new Mutex(false, mutexId, out iDontCareWhetherItsNew, securitySettings);
            }
            {
                SemaphoreAccessRule allowEveryoneRule = new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow);
                SemaphoreSecurity securitySettings = new SemaphoreSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);

                _chipsInTheHat = new Semaphore(READER_CHIPS, READER_CHIPS, semaphoreId, out iDontCareWhetherItsNew, securitySettings);
            }
        }
Example #2
0
        public static Semaphore GetNamedSemaphore(string name, int maximumCount = 10, int initialCount = -1)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw new ArgumentNullException("name", "Argument cannot be empty, null or white space.");

            Semaphore namedSemaphore;
            bool semaphoreWasCreated;

            if (initialCount < 0)
                initialCount = maximumCount;

            // Create a semaphore name that is specific to an object (e.g., a path and file name).
            // Note that we use GetPasswordHash to create a short common name for the name parameter
            // that was passed into the function - this allows the parameter to be very long, e.g.,
            // a file path, and still meet minimum semaphore name requirements.

            // Prefix semaphore name with "Global\" such that semaphore will apply to all active
            // application sessions in case terminal services is running. Note that this is necessary
            // even though .NET documentation does not state it - IL disassembly shows direct calls
            // to WinAPI OpenSemaphore and CreateSemaphore which clearly document this:
            // http://msdn.microsoft.com/en-us/library/windows/desktop/ms684326(v=vs.85).aspx
            string semaphoreName = "Global\\" + Cipher.GetPasswordHash(name.ToLower(), SemaphoreHash).Replace('\\', '-');

#if MONO
            // Mono Semaphore implementations do not include ability to change access rules
            namedSemaphore = new Semaphore(initialCount, maximumCount, semaphoreName, out semaphoreWasCreated);
#else
            bool doesNotExist = false;

            // Attempt to open the named semaphore with minimum needed rights
            try
            {
                namedSemaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize | SemaphoreRights.Modify);
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                namedSemaphore = null;
                doesNotExist = true;
            }

            // If semaphore does not exist we attempt to create it
            if (doesNotExist)
            {
                try
                {
                    SemaphoreSecurity security = new SemaphoreSecurity();
                    security.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Allow));
                    namedSemaphore = new Semaphore(initialCount, maximumCount, semaphoreName, out semaphoreWasCreated, security);
                }
                catch (UnauthorizedAccessException)
                {
                    // Named semaphore exists now but current user doesn't have full control, attempt to open with minimum needed rights
                    namedSemaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize | SemaphoreRights.Modify);
                }
            }
#endif

            return namedSemaphore;
        }
Example #3
0
        public MainWindow()
        {
            Settings.LoadFromXmlFile();
            CommonManager.Instance.NWMode = Settings.Instance.NWMode;

            CommonManager.Instance.MM.ReloadWorkData();
            CommonManager.Instance.ReloadCustContentColorList();

            if (Settings.Instance.NoStyle == 0)
            {
                if (System.IO.File.Exists(System.Reflection.Assembly.GetEntryAssembly().Location + ".rd.xaml"))
                {
                    //ResourceDictionaryを定義したファイルがあるので本体にマージする
                    try
                    {
                        App.Current.Resources.MergedDictionaries.Add(
                            (ResourceDictionary)System.Windows.Markup.XamlReader.Load(
                                System.Xml.XmlReader.Create(System.Reflection.Assembly.GetEntryAssembly().Location + ".rd.xaml")));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
                else
                {
                    //既定のテーマ(Aero)をマージする
                    App.Current.Resources.MergedDictionaries.Add(
                        Application.LoadComponent(new Uri("/PresentationFramework.Aero, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35;component/themes/aero.normalcolor.xaml", UriKind.Relative)) as ResourceDictionary
                        );
                }
            }

            SemaphoreSecurity ss = new SemaphoreSecurity();
            ss.AddAccessRule(new SemaphoreAccessRule("Everyone", SemaphoreRights.FullControl, AccessControlType.Allow));
            semaphore = new Semaphore(int.MaxValue, int.MaxValue, "Global\\EpgTimer_Bon2", out firstInstance, ss);
            semaphore.WaitOne(0);
            if (!firstInstance)
            {
                CheckCmdLine();

                if (Settings.Instance.ApplyMultiInstance == false)
                {
                    semaphore.Release();
                    semaphore.Close();
                    semaphore = null;

                    CloseCmd();
                    return;
                }
            }

            InitializeComponent();

            initExe = true;

            try
            {
                // 多重起動時は最小化しない
                if (firstInstance && Settings.Instance.WakeMin == true)
                {
                    // Icon化起動すると Windows_Loaded イベントが来ないので
                    // InitializeComponent 後に ConnectCmd しておく。
                    if (Settings.Instance.NWMode == false || Settings.Instance.WakeReconnectNW == true)
                    {
                        ConnectCmd(false);
                    }

                    if (Settings.Instance.ShowTray && Settings.Instance.MinHide)
                    {
                        this.Visibility = Visibility.Hidden;
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            this.WindowState = System.Windows.WindowState.Minimized;
                        }));
                    }
                }

                //ウインドウ位置の復元
                if (Settings.Instance.MainWndTop != -100)
                {
                    this.Top = Settings.Instance.MainWndTop;
                }
                if (Settings.Instance.MainWndLeft != -100)
                {
                    this.Left = Settings.Instance.MainWndLeft;
                }
                if (Settings.Instance.MainWndWidth != -100)
                {
                    this.Width = Settings.Instance.MainWndWidth;
                }
                if (Settings.Instance.MainWndHeight != -100)
                {
                    this.Height = Settings.Instance.MainWndHeight;
                }
                this.WindowState = Settings.Instance.LastWindowState;

                //上のボタン
                Action<string, RoutedEventHandler> ButtonGen = (key, handler) =>
                {
                    Button btn = new Button();
                    btn.MinWidth = 75;
                    btn.Margin = new Thickness(2, 2, 2, 5);
                    if (handler != null) btn.Click += new RoutedEventHandler(handler);
                    btn.Content = key;
                    buttonList.Add(key, btn);
                };
                ButtonGen("設定", settingButton_Click);
                ButtonGen("検索", null);
                ButtonGen("終了", closeButton_Click);
                ButtonGen("スタンバイ", standbyButton_Click);
                ButtonGen("休止", suspendButton_Click);
                ButtonGen("EPG取得", epgCapButton_Click);
                ButtonGen("EPG再読み込み", epgReloadButton_Click);
                ButtonGen("カスタム1", custum1Button_Click);
                ButtonGen("カスタム2", custum2Button_Click);
                ButtonGen("NetworkTV終了", nwTVEndButton_Click);
                ButtonGen("情報通知ログ", logViewButton_Click);
                ButtonGen("再接続", connectButton_Click);
                ButtonGen("予約簡易表示", showInfoWindowButton_Click);

                //検索ボタンは他と共通でショートカット割り振られているので、コマンド側で処理する。
                this.CommandBindings.Add(new CommandBinding(EpgCmds.Search, searchButton_Click));
                mBinds.SetCommandToButton(buttonList["検索"], EpgCmds.Search);
                RefreshButton();

                ResetButtonView();

                //タスクトレイの表示
                taskTray = new TaskTrayClass(this);
                taskTray.Icon = Properties.Resources.TaskIconBlue;
                taskTray.Visible = Settings.Instance.ShowTray;
                taskTray.ContextMenuClick += new EventHandler(taskTray_ContextMenuClick);
                taskTray.Text = GetTaskTrayReserveInfoText();
                ResetTaskMenu();

                CheckCmdLine();

                // 設定から情報を読み取るので設定をロードした後作る
                infoWindowViewModel = new InfoWindowViewModel();
                if(Settings.Instance.InfoWindowEnabled)
                {
                    ShowInfoWindow();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
Example #4
0
        public MainWindow()
        {
            Settings.LoadFromXmlFile();
            CommonManager.Instance.NWMode = Settings.Instance.NWMode;

            CommonManager.Instance.MM.ReloadWorkData();
            CommonManager.Instance.ReloadCustContentColorList();
            Settings.Instance.ReloadOtherOptions();

            CommonUtil.ApplyStyle(Settings.Instance.NoStyle == 0 ? Settings.Instance.StyleXamlPath : null);

            SemaphoreSecurity ss = new SemaphoreSecurity();
            ss.AddAccessRule(new SemaphoreAccessRule("Everyone", SemaphoreRights.FullControl, AccessControlType.Allow));
            semaphore = new Semaphore(int.MaxValue, int.MaxValue, "Global\\EpgTimer_Bon3", out firstInstance, ss);
            semaphore.WaitOne(0);
            if (!firstInstance && Settings.Instance.ApplyMultiInstance == false)
            {
                ConnectSrv();
                DisconnectServer();

                semaphore.Release();
                semaphore.Close();
                semaphore = null;

                CloseCmd();
                return;
            }

            InitializeComponent();

            #if DEBUG
            appName += "(debug)";
            #endif

            initExe = true;

            try
            {
                infoWindowViewModel = new InfoWindowViewModel();

                // 多重起動時は最小化しない
                if (firstInstance && Settings.Instance.WakeMin == true)
                {
                    // Icon化起動すると Windows_Loaded イベントが来ないので
                    // InitializeComponent 後に ConnectCmd しておく。
                    Dispatcher.BeginInvoke(new Action(() =>
                                            ConnectCmd(Settings.Instance.NWMode && Settings.Instance.WakeReconnectNW == false)
                                            ), DispatcherPriority.Loaded);

                    if (Settings.Instance.ShowTray && Settings.Instance.MinHide)
                    {
                        this.Visibility = Visibility.Hidden;
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            this.WindowState = System.Windows.WindowState.Minimized;
                            minimizedStarting = true;
                        }));
                    }
                }

                //ウインドウ位置の復元
                if (Settings.Instance.MainWndTop != -100)
                {
                    this.Top = Settings.Instance.MainWndTop;
                }
                if (Settings.Instance.MainWndLeft != -100)
                {
                    this.Left = Settings.Instance.MainWndLeft;
                }
                if (Settings.Instance.MainWndWidth != -100)
                {
                    this.Width = Settings.Instance.MainWndWidth;
                }
                if (Settings.Instance.MainWndHeight != -100)
                {
                    this.Height = Settings.Instance.MainWndHeight;
                }
                this.WindowState = Settings.Instance.LastWindowState;

                //上のボタン
                Action<string, Action> ButtonGen = (key, handler) =>
                {
                    Button btn = new Button();
                    btn.MinWidth = 75;
                    btn.Margin = new Thickness(2, 2, 2, 5);
                    btn.Click += (sender, e) => handler();
                    btn.Content = key;
                    buttonList.Add(key, btn);
                };
                ButtonGen("設定", OpenSettingDialog);
                ButtonGen("再接続", OpenConnectDialog);
                ButtonGen("再接続(前回)", () => ConnectCmd());
                ButtonGen("検索", OpenSearchDialog);
                ButtonGen("スタンバイ", () => SuspendCmd(1));
                ButtonGen("休止", () => SuspendCmd(2));
                ButtonGen("終了", CloseCmd);
                ButtonGen("EPG取得", EpgCapCmd);
                ButtonGen("EPG再読み込み", EpgReloadCmd);
                ButtonGen("NetworkTV終了", NwTVEndCmd);
                ButtonGen("情報通知ログ", OpenNotifyLogDialog);
                ButtonGen("予約簡易表示", () => ShowInfoWindow());
                ButtonGen("カスタム1", () => CustumCmd(1));
                ButtonGen("カスタム2", () => CustumCmd(2));
                ButtonGen("カスタム3", () => CustumCmd(3));

                //検索ボタンは他と共通でショートカット割り振られているので、その部分はコマンド側で処理する。
                this.CommandBindings.Add(new CommandBinding(EpgCmds.Search, (sender, e) => CommonButtons_Click("検索")));
                mBinds.AddInputCommand(EpgCmds.Search);
                SetSearchButtonTooltip(buttonList["検索"]);

                StatusbarReset();//ステータスバーリセット

                if(Settings.Instance.InfoWindowEnabled)
                {
                    ShowInfoWindow();
                }

                //タスクトレイの表示
                taskTray = new TaskTrayClass(this);
                if (CommonManager.Instance.NWMode == true && Settings.Instance.ChkSrvRegistTCP == true)
                {
                    taskTray.Icon = TaskIconSpec.TaskIconGray;
                }
                else
                {
                    taskTray.Icon = TaskIconSpec.TaskIconBlue;
                }
                taskTray.ContextMenuClick += (sender, e) => CommonButtons_Click(sender as string);

                ResetMainView();

                //初期タブ選択
                switch (Settings.Instance.StartTab)
                {
                    //case CtxmCode.ReserveView:
                    //    this.tabItem_reserve.IsSelected = true;
                    //    break;
                    case CtxmCode.TunerReserveView:
                        this.tabItem_tunerReserve.IsSelected = true;
                        break;
                    case CtxmCode.RecInfoView:
                        this.tabItem_recinfo.IsSelected = true;
                        break;
                    case CtxmCode.EpgAutoAddView:
                        this.tabItem_AutoAdd.IsSelected = true;
                    //    this.autoAddView.tabItem_epgAutoAdd.IsSelected = true;
                        break;
                    case CtxmCode.ManualAutoAddView:
                        this.tabItem_AutoAdd.IsSelected = true;
                        this.autoAddView.tabItem_manualAutoAdd.IsSelected = true;
                        break;
                    case CtxmCode.EpgView:
                        this.tabItem_epg.IsSelected = true;
                        break;
                }
            }
            catch (Exception ex)
            {
                ExceptionLogger.Log(ex);
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
Example #5
0
            internal ManagedMemoryBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable<string> servicePrincpal)
            {
                Namespace = @namespace;
                Key = key;

                EventWaitHandleSecurity handleSecurity = null;
                MemoryMappedFileSecurity memSecurity = null;
                SemaphoreSecurity semaphoreSecurity = null;

                var serviceIdentity = servicePrincpal.FirstOrDefault();
                var currentIdentity = WindowsIdentity.GetCurrent();
                if (serviceIdentity != null && currentIdentity != null)
                {
                    handleSecurity = new EventWaitHandleSecurity();
                    handleSecurity.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    // The event handles need more than just EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize to work
                    handleSecurity.AddAccessRule(new EventWaitHandleAccessRule(serviceIdentity, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    memSecurity = new MemoryMappedFileSecurity();
                    memSecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    memSecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>(serviceIdentity, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));

                    semaphoreSecurity = new SemaphoreSecurity();
                    semaphoreSecurity.AddAccessRule(new SemaphoreAccessRule(currentIdentity.Name, SemaphoreRights.FullControl, AccessControlType.Allow));
                    semaphoreSecurity.AddAccessRule(new SemaphoreAccessRule(serviceIdentity, SemaphoreRights.FullControl, AccessControlType.Allow));
                }

                bool createdNew;

                ProfilerHasResults = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Results_SendResults_Event_", bufferId),
                    out createdNew,
                    handleSecurity);

                ResultsHaveBeenReceived = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Results_ReceiveResults_Event_", bufferId),
                    out createdNew,
                    handleSecurity);

                _semaphore = new Semaphore(0, 2,
                    MakeName(@"\OpenCover_Profiler_Results_Semaphore_", bufferId),
                    out createdNew,
                    semaphoreSecurity);

                _mmfResults = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Results_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    memSecurity,
                    HandleInheritability.Inheritable);

                Buffer = new byte[bufferSize];
                StreamAccessorResults = _mmfResults.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);
                StreamAccessorResults.Write(BitConverter.GetBytes(0), 0, 4);
                StreamAccessorResults.Flush();

                BufferSize = bufferSize;
            }
Example #6
0
            internal ManagedCommunicationBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable<string> servicePrincpal)
            {
                Namespace = @namespace;
                Key = key;

                EventWaitHandleSecurity eventSecurity = null;
                MemoryMappedFileSecurity memorySecurity = null;

                var serviceIdentity = servicePrincpal.FirstOrDefault();
                var currentIdentity = WindowsIdentity.GetCurrent();
                SemaphoreSecurity semaphoreSecurity = null;
                if (serviceIdentity != null && currentIdentity != null)
                {
                    eventSecurity = new EventWaitHandleSecurity();
                    eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow));
                    eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(serviceIdentity, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    memorySecurity = new MemoryMappedFileSecurity();
                    memorySecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    memorySecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>(serviceIdentity, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));

                    semaphoreSecurity = new SemaphoreSecurity();
                    semaphoreSecurity.AddAccessRule(new SemaphoreAccessRule(currentIdentity.Name, SemaphoreRights.FullControl, AccessControlType.Allow));
                    semaphoreSecurity.AddAccessRule(new SemaphoreAccessRule(serviceIdentity, SemaphoreRights.FullControl, AccessControlType.Allow));
                }

                bool createdNew;

                ProfilerRequestsInformation = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendData_Event_", bufferId),
                    out createdNew,
                    eventSecurity);

                InformationReadyForProfiler = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveData_Event_", bufferId),
                    out createdNew,
                    eventSecurity);

                InformationReadByProfiler = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ChunkData_Event_", bufferId),
                    out createdNew,
                    eventSecurity);

                _semaphore = new Semaphore(0, 2,
                    MakeName(@"\OpenCover_Profiler_Communication_Semaphore_", bufferId),
                    out createdNew,
                    semaphoreSecurity);

                _memoryMappedFile = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Communication_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    memorySecurity,
                    HandleInheritability.Inheritable);

                StreamAccessorComms = _memoryMappedFile.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);

                DataCommunication = new byte[bufferSize];
                PinnedDataCommunication = GCHandle.Alloc(DataCommunication, GCHandleType.Pinned);
            }
Example #7
0
        public static Semaphore GetNamedSemaphore(string name, int maximumCount = 10, int initialCount = -1)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw new ArgumentNullException("name", "Argument cannot be empty, null or white space.");

            Semaphore namedSemaphore = null;
            bool doesNotExist = false;
            bool unauthorized = false;

            if (initialCount < 0)
                initialCount = maximumCount;

            // Create a semaphore name that is specific to an object (e.g., a path and file name).
            string semaphoreName = Cipher.GetPasswordHash(name.ToLower(), SemaphoreHash).Replace('\\', '-');

            // Attempt to open the named semaphore
            try
            {
                namedSemaphore = Semaphore.OpenExisting(semaphoreName);
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                doesNotExist = true;
            }
            catch (UnauthorizedAccessException)
            {
                unauthorized = true;
            }

            // Mono Semaphore implementations do not include ability to change access rules
#if MONO
            // If semaphore does not exist we create it
            if (doesNotExist || unauthorized)
            {
                try
                {
                    bool semaphoreWasCreated;

                    namedSemaphore = new Semaphore(initialCount, maximumCount, semaphoreName, out semaphoreWasCreated);

                    if (!semaphoreWasCreated)
                        throw new InvalidOperationException("Failed to create semaphore.");
                }
                catch (UnauthorizedAccessException ex)
                {
                    throw new InvalidOperationException("Failed to create semaphore: " + ex.Message);
                }
            }
#else
            // If semaphore does not exist we create it
            if (doesNotExist)
            {
                try
                {
                    SemaphoreSecurity security = new SemaphoreSecurity();
                    bool semaphoreWasCreated;

                    security.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow));
                    namedSemaphore = new Semaphore(initialCount, maximumCount, semaphoreName, out semaphoreWasCreated, security);

                    if (!semaphoreWasCreated)
                        throw new InvalidOperationException("Failed to create semaphore.");
                }
                catch (UnauthorizedAccessException)
                {
                    SemaphoreSecurity security = new SemaphoreSecurity();
                    bool semaphoreWasCreated;

                    security.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Allow));
                    namedSemaphore = new Semaphore(initialCount, maximumCount, semaphoreName, out semaphoreWasCreated, security);

                    if (!semaphoreWasCreated)
                        throw new InvalidOperationException("Failed to create semaphore.");
                }
            }
            else if (unauthorized)
            {
                namedSemaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions);

                // Get the current ACL. This requires MutexRights.ReadPermission
                SemaphoreSecurity security = new SemaphoreSecurity();
                SemaphoreAccessRule rule = new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow);
                security.RemoveAccessRule(rule);

                // Now grant specific user rights for less than full access
                rule = new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Allow);
                security.AddAccessRule(rule);

                // Update the ACL. This requires MutexRighs.ChangePermission.
                namedSemaphore.SetAccessControl(security);
                namedSemaphore = Semaphore.OpenExisting(semaphoreName);
            }
#endif

            return namedSemaphore;
        }
Example #8
0
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        /// <returns></returns>
        public static bool Initialize()
        {
            bool bResult = false;

            if (CurrentElement == null)
            {
                // lock
                lock (typeof(CompanyWebSiteSemaphore))
                {
                    if (CurrentElement == null)
                    {
                        int maxPortalsCount = License.PortalsCount;

                        Semaphore semaphore = null;

                        if (maxPortalsCount > 0)
                        {
                            // Step 1. Try open Semaphore

                            try
                            {
                                semaphore = Semaphore.OpenExisting(Uid);
                            }
                            catch (WaitHandleCannotBeOpenedException)
                            {
                                // The named semaphore does not exist.
                                SemaphoreSecurity security = new SemaphoreSecurity();

                                // OZ 2009-03-10/Fix: System.Security.Principal.IdentityNotMappedException
                                //SemaphoreAccessRule accessRule = new SemaphoreAccessRule("Everyone", SemaphoreRights.TakeOwnership | SemaphoreRights.FullControl, AccessControlType.Allow);
                                SecurityIdentifier everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                                SemaphoreAccessRule accessRule = new SemaphoreAccessRule(everyoneSid, SemaphoreRights.TakeOwnership | SemaphoreRights.FullControl, AccessControlType.Allow);

                                security.AddAccessRule(accessRule);

                                bool createdNew;
                                semaphore = new Semaphore(maxPortalsCount, maxPortalsCount, Uid, out createdNew, security);
                            }

                            // Wait one with timeout
                            if (!semaphore.WaitOne(3000, false))
                            {
                                throw new LicenseRestrictionException("License.PortalsCount");
                            }

                            CurrentElement = new CompanyWebSiteSemaphore(semaphore);
                        }
                        else if (maxPortalsCount==-1)
                        {
                            // Unlimited
                            CurrentElement = new CompanyWebSiteSemaphore(null);
                        }
                        else
                            throw new LicenseRestrictionException("Wrong License.PortalsCount = " + maxPortalsCount.ToString());

                        bResult = true;
                    }
                }
            }

            return bResult;
        }
Example #9
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                if (args[0].ToLower().Equals("start"))
                {

                    ProcessStartInfo startInfo = new ProcessStartInfo("startup\\startuptask.exe");
                    startInfo.CreateNoWindow = true;
                    try
                    {
                        Process exeProcess = Process.Start(startInfo);
                    }
                    catch 
                    {
                       
                    }
                    return;
                }
            }
            else
            {
                const string semaphoreName = "SemaphoreShutDown";
                Semaphore sem = null;
                bool doesNotExist = false;
                // Attempt to open the named semaphore.
                try
                {
                    sem = Semaphore.OpenExisting(semaphoreName);
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    doesNotExist = true;
                }

                if (doesNotExist)
                {
                    // The semaphore does not exist, so create it.
                    //
                    // The value of this variable is set by the semaphore
                    // constructor. It is true if the named system semaphore was
                    // created, and false if the named semaphore already existed.
                    //
                    bool semaphoreWasCreated;


                    string user = "******";
                    SemaphoreSecurity semSec = new SemaphoreSecurity();

                    SemaphoreAccessRule rule = new SemaphoreAccessRule(user,
                        SemaphoreRights.Synchronize | SemaphoreRights.Modify,
                        AccessControlType.Allow);
                    semSec.AddAccessRule(rule);

                    // Create a Semaphore object 
                    sem = new Semaphore(1, 1, semaphoreName,
                        out semaphoreWasCreated, semSec);
                    if (!semaphoreWasCreated)
                        return;
                }

                // Enter the semaphore, and hold it until the program
                // exits.
                //
                try
                {
                    sem.WaitOne();
                    sem.WaitOne();
                    ProcessStartInfo startInfo = new ProcessStartInfo("NET");
                    startInfo.Arguments = "STOP W3SVC";
                    startInfo.CreateNoWindow = false;
                    try
                    {
                        // Start the process with the info we specified.
                        // Call WaitForExit and then the using statement will close.
                        using (Process exeProcess = Process.Start(startInfo))
                        {
                            exeProcess.WaitForExit();
                            int exitCode = exeProcess.ExitCode;
                        }
                    }
                    catch 
                    {
                    }
                    sem.Release();
                }
                catch 
                {
                }
            }
        }