Пример #1
0
 // SetProject takes a project and converts the nodes and roads to vertices and edges. Only has to be done once.
 public static void SetProject(Project project, Partitions partition)
 {
     Vertices = new List<Vertex>();
     ConvertNodes(project);
     ConvertRoads(project, partition);
     MaxSpeed = project.RoadTypes.Max().Speed;
 }
Пример #2
0
 private static void ConvertRoads(Project project, Partitions partition)
 {
     foreach (Node node in project.Nodes)
         foreach (Road road in node.Roads)
             foreach (Vertex vertex in Vertices)
                 if (road.From.Position == vertex.Position && (road.Partition == partition || road.Partition == Partitions.Shared))
                     vertex.Edges.Add(new Edge(road, vertex, Vertices.Find(v => v.Position == road.To.Position)));
 }
Пример #3
0
 public Road(Node from, Node to, RoadType type, Partitions partition)
 {
     From = from;
     To = to;
     Type = type;
     Partition = partition;
     Vehicles = new List<Vehicle>();
 }
Пример #4
0
        public Partition GetPartitionByNamespace(string ns, bool all = true)
        {
            Partition partition;

            if (string.IsNullOrWhiteSpace(ns))
            {
                throw new ArgumentException("ns");
            }

            try
            {
                partition = all ? Partitions.Single(p => p.Namespace == ns) : Partitions.Single(p => p.Namespace == ns && p.Active);
            }
            catch (Exception ex)
            {
                throw new PartitionException(EXCEPTION_PARTITION_NOT_FOUND, ex);
            }

            return(partition);
        }
Пример #5
0
        public Partition GetPartitionByArea(string area, bool all = true)
        {
            Partition partition;

            if (string.IsNullOrWhiteSpace(area))
            {
                throw new ArgumentException("area");
            }

            try
            {
                partition = all ? Partitions.Single(p => p.Area == area) : Partitions.Single(p => p.Area == area && p.Active);
            }
            catch (Exception ex)
            {
                throw new PartitionException(EXCEPTION_PARTITION_NOT_FOUND, ex);
            }

            return(partition);
        }
Пример #6
0
        void PartitionChanged(Partition partition)
        {
            Partition tmp = null;

            foreach (Partition p in Partitions)
            {
                if (p.Id == partition.Id)
                {
                    tmp = p;
                    break;
                }
            }
            int ix = Partitions.IndexOf(tmp);

            if (tmp == SelectedPartition)
            {
                Partitions[ix]    = partition;
                SelectedPartition = partition;
            }
            else
            {
                Partitions[ix] = partition;
            }
        }
Пример #7
0
        /************************************************************/

        #region Messendger Handlers

        private void PartitionAdded(Partition partition)
        {
            Partitions.Add(partition);
        }
Пример #8
0
        public override string ToString()
        {
            StringBuilder strPosition = new StringBuilder();

            foreach (var elem in Position)
            {
                strPosition.Append(elem.ToString() + " ");
            }

            StringBuilder strSign = new StringBuilder();

            foreach (var elem in Sign)
            {
                strSign.Append(elem.ToString() + " ");
            }

            return("[Position: " + strPosition.ToString() + "]\n[Sign: " + strSign.ToString() + "]\n[Переборов: " + Partitions.ToString() + "]");
        }
Пример #9
0
        internal unsafe IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondaryType, string?partition, ref bool advanced, int context, SafeLibraryHandle libHandle)
        {
            IntPtr info           = (IntPtr)0;
            int    result         = 0;
            bool   needToTryAgain = true;

            // first try to use the DsReplicaGetInfo2W API which does not exist on win2k machine
            // call DsReplicaGetInfo2W
            var dsReplicaGetInfo2W = (delegate * unmanaged <IntPtr, int, char *, IntPtr, char *, char *, int, int, IntPtr *, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfo2W");

            if (dsReplicaGetInfo2W == null)
            {
                // a win2k machine which does not have it.
                var dsReplicaGetInfoW = (delegate * unmanaged <IntPtr, int, char *, IntPtr, IntPtr *, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW");
                if (dsReplicaGetInfoW == null)
                {
                    throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
                }

                fixed(char *partitionPtr = partition)
                {
                    result = dsReplicaGetInfoW(dsHandle, secondaryType, partitionPtr, (IntPtr)0, &info);
                }

                advanced       = false;
                needToTryAgain = false;
            }
            else
            {
                fixed(char *partitionPtr = partition)
                {
                    result = dsReplicaGetInfo2W(dsHandle, type, partitionPtr, (IntPtr)0, null, null, 0, context, &info);
                }
            }

            // check the result
            if (needToTryAgain && result == DS_REPL_NOTSUPPORTED)
            {
                // this is the case that client is xp/win2k3, dc is win2k
                var dsReplicaGetInfoW = (delegate * unmanaged <IntPtr, int, char *, IntPtr, IntPtr *, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW");
                if (dsReplicaGetInfoW == null)
                {
                    throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
                }

                fixed(char *partitionPtr = partition)
                {
                    result = dsReplicaGetInfoW(dsHandle, secondaryType, partitionPtr, (IntPtr)0, &info);
                }

                advanced = false;
            }

            if (result != 0)
            {
                if (partition != null)
                {
                    // this is the case of meta data
                    if (type == (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_2_FOR_OBJ)
                    {
                        if (result == ExceptionHelper.ERROR_DS_DRA_BAD_DN || result == ExceptionHelper.ERROR_DS_NAME_UNPARSEABLE)
                        {
                            throw new ArgumentException(ExceptionHelper.GetErrorMessage(result, false), "objectPath");
                        }

                        DirectoryEntry verifyEntry = DirectoryEntryManager.GetDirectoryEntry(this.context, partition);
                        try
                        {
                            verifyEntry.RefreshCache(new string[] { "name" });
                        }
                        catch (COMException e)
                        {
                            if (e.ErrorCode == unchecked ((int)0x80072020) |          // dir_error on server side
                                e.ErrorCode == unchecked ((int)0x80072030))           // object not exists
                            {
                                throw new ArgumentException(SR.DSNoObject, "objectPath");
                            }
                            else if (e.ErrorCode == unchecked ((int)0x80005000) | // bad path name
                                     e.ErrorCode == unchecked ((int)0x80072032))  // ERROR_DS_INVALID_DN_SYNTAX
                            {
                                throw new ArgumentException(SR.DSInvalidPath, "objectPath");
                            }
                        }
                    }
                    else
                    {
                        if (!Partitions.Contains(partition))
                        {
                            throw new ArgumentException(SR.ServerNotAReplica, nameof(partition));
                        }
                    }
                }

                throw ExceptionHelper.GetExceptionFromErrorCode(result, Name);
            }

            return(info);
        }
Пример #10
0
 private void AddRoad(Partitions partition)
 {
     object obj = Viewport.GetObjByGridPos();
     if (obj != null && obj is Node)
     {
         if (_firstNodeConnection)
         {
             _firstNode = (Node)obj;
             _firstNodeConnection = false;
             Viewport.HoverConnection = ((Node)obj).Position;
         }
         else
         {
             _firstNode.Roads.Add(new Road(_firstNode, (Node)obj, SelectedRoadType, partition));
             if (Control.ModifierKeys == Keys.Shift)
             {
                 _firstNode = (Node)obj;
                 Viewport.HoverConnection = ((Node)obj).Position;
             }
             else
             {
                 _firstNodeConnection = true;
                 Viewport.HoverConnection = new Point(-1, -1);
             }
             Viewport.Connections.Refresh();
         }
     }
 }
Пример #11
0
        // GetHomes //
        private Node[] GetHomes(Partitions partition, int count)
        {
            int inbound;
            if (partition == Partitions.Primary) inbound = Project.Settings.PrimaryInbound;
            else inbound = Project.Settings.SecondaryInbound;
            int inboundCount = count * (inbound / 100);

            List<Node> homes = new List<Node>();
            for (int i = 0; i < inboundCount; i++)
                homes.Add(GetNextInbound(partition));

            int remaining = count - inboundCount;
            for (int i = 0; i < remaining; i++)
                homes.Add(GetNextHome(partition));

            return homes.ToArray();
        }
Пример #12
0
 private Vehicle[] CopyVehicles(Partitions partition)
 {
     List<Vehicle> vehicles = new List<Vehicle>();
     if (partition == Partitions.Primary)
     {
         Pathfinder.SetProject(SecondaryProject, Partitions.Secondary);
         foreach (Vehicle vehicle in _primaryVehicles)
             vehicles.Add(new Vehicle(SecondaryProject, vehicle.Home, vehicle.Destination,
                 vehicle.Type, vehicle.ToDestTime, vehicle.ToHomeTime));
     }
     else
     {
         Pathfinder.SetProject(PrimaryProject, Partitions.Primary);
         foreach (Vehicle vehicle in _secondaryVehicles)
             vehicles.Add(new Vehicle(PrimaryProject, vehicle.Home, vehicle.Destination,
                 vehicle.Type, vehicle.ToDestTime, vehicle.ToHomeTime));
     }
     return vehicles.ToArray();
 }
Пример #13
0
    void Start()
    {
        newseed = (thisLevel.number == GameControl.control.stagedata[GameControl.control.Stage].highestReachedLevel);
        // GetComponent<AdsManager>().Display_Banner();
        thisLevel = GameControl.control.leveltoLoad;
        GameControl.control.Stage       = thisLevel.stage;
        GameControl.control.LevelNumber = thisLevel.number;
        GameControl.control.phasenum    = thisLevel.phase;
        gameSpeed = 0;
        LevelSelect.lSelect.gameObject.SetActive(false);
        AdventureBag.aBag.gameObject.SetActive(false);
        if (GameControl.control.stagedata.Count == 0)
        {
            GameControl.control.stagedata.Add(new Stage());
        }



        screenSize.x = Vector2.Distance(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)), Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)));  // * 0.5; //Grab the world-space position values of the start and end positions of the screen, then calculate the distance between them and store it as half, since we only need half that value for distance away from the camera to the edge
        screenSize.y = Vector2.Distance(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)), Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height))); // * 0.5f;

        int a;

        if (GameControl.control.Stage == 0)
        {
            a          = 5;
            difficulty = Mathf.Clamp(thisLevel.number, 0, a);//GameControl.control.LevelNumber;
        }
        if (GameControl.control.Stage == 1)
        {
            a          = 12;
            difficulty = Mathf.Clamp(thisLevel.number, 0, a);//GameControl.control.LevelNumber;
        }
        if (GameControl.control.Stage == 2)
        {
            a          = 29;
            difficulty = Mathf.Clamp(thisLevel.number, 0, a);//GameControl.control.LevelNumber;
        }


        originalPos = Camera.main.transform.position;
        int complexity = 1 + (GameControl.control.LevelNumber / 10);

        open = true;
        StartCoroutine(OpenCloseInfo());
        gameLayout            = new Partitions(Maze.xSize, Maze.ySize, screenSize);
        gameLayout.Dimensions = screenSize;
        gameLayout.createSectors();

        Random.InitState(thisLevel.randomSeed);
        //CreateStartAndFinish();

        StartCoroutine(Loadlevel());



        thisLevel.number = GameControl.control.LevelNumber;


        // GameControl.control.updateinfo();


        OpenTutorial(player, ("this is the Chicken, tap and move your finger to control it"));

        StartCoroutine(LevelInfoScroll());
        StartCoroutine(dropScore());
        GameControl.control.Save();
    }
Пример #14
0
        internal unsafe void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallback syncAllCallback, string partition, SyncFromAllServersOptions option, SyncUpdateCallback?callback, SafeLibraryHandle libHandle)
        {
            IntPtr errorInfo = (IntPtr)0;

            if (!Partitions.Contains(partition))
            {
                throw new ArgumentException(SR.ServerNotAReplica, nameof(partition));
            }

            // we want to return the dn instead of DNS guid
            // call DsReplicaSyncAllW
            var dsReplicaSyncAllW = (delegate * unmanaged <IntPtr, char *, int, IntPtr, IntPtr, IntPtr *, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaSyncAllW");

            if (dsReplicaSyncAllW == null)
            {
                throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
            }

            int result;

            fixed(char *partitionPtr = partition)
            {
                IntPtr syncAllFunctionPointer = Marshal.GetFunctionPointerForDelegate(syncAllCallback);

                result = dsReplicaSyncAllW(handle, partitionPtr, (int)option | DS_REPSYNCALL_ID_SERVERS_BY_DN, syncAllFunctionPointer, (IntPtr)0, &errorInfo);
                GC.KeepAlive(syncAllCallback);
            }

            try
            {
                // error happens during the synchronization
                if (errorInfo != (IntPtr)0)
                {
                    SyncFromAllServersOperationException?e = ExceptionHelper.CreateSyncAllException(errorInfo, false);
                    if (e == null)
                    {
                        return;
                    }
                    else
                    {
                        throw e;
                    }
                }
                else
                {
                    // API does not return error infor occurred during synchronization, but result is not success.
                    if (result != 0)
                    {
                        throw new SyncFromAllServersOperationException(ExceptionHelper.GetErrorMessage(result, false));
                    }
                }
            }
            finally
            {
                // release the memory
                if (errorInfo != (IntPtr)0)
                {
                    global::Interop.Kernel32.LocalFree(errorInfo);
                }
            }
        }
Пример #15
0
 private void SortPartitions()
 {
     Partitions.Sort();
 }
Пример #16
0
 public void AddPartition(string partitionId, string masterUrl)
 {
     Console.WriteLine("Creating partition " + partitionId);
     Partitions.Add(partitionId, new AdvancedServerPartition(partitionId, masterUrl, this));
 }
Пример #17
0
 public static void Draw_BAR_PARTITIONS_FILL_Y(float _x, float _y, float _w, float _h, Partitions _partitions)
 {
     for (int i = 0; i < _partitions.count; i++)
     {
         Partition _P = _partitions.Get(i);
         GL_DRAW.Draw_RECT_FILL(_x, _y + (_h * _P.start), _w, _h * _partitions.Get_Share(i), _P.colour);
     }
 }
Пример #18
0
        internal unsafe void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, string?sourceServer, int option, SafeLibraryHandle libHandle)
        {
            int              structSize    = Marshal.SizeOf(typeof(Guid));
            IntPtr           unmanagedGuid = (IntPtr)0;
            Guid             guid          = Guid.Empty;
            AdamInstance?    adamServer    = null;
            DomainController?dcServer      = null;

            unmanagedGuid = Marshal.AllocHGlobal(structSize);
            try
            {
                if (sourceServer != null)
                {
                    DirectoryContext newContext = Utils.GetNewDirectoryContext(sourceServer, DirectoryContextType.DirectoryServer, context);
                    if (isADAM)
                    {
                        adamServer = AdamInstance.GetAdamInstance(newContext);
                        guid       = adamServer.NtdsaObjectGuid;
                    }
                    else
                    {
                        dcServer = DomainController.GetDomainController(newContext);
                        guid     = dcServer.NtdsaObjectGuid;
                    }

                    Marshal.StructureToPtr(guid, unmanagedGuid, false);
                }

                // call DsReplicaSyncW
                var dsReplicaSyncW = (delegate * unmanaged <IntPtr, char *, IntPtr, int, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaSyncW");
                if (dsReplicaSyncW == null)
                {
                    throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
                }

                fixed(char *partitionPtr = partition)
                {
                    int result = dsReplicaSyncW(dsHandle, partitionPtr, unmanagedGuid, (int)option);

                    // check the result
                    if (result != 0)
                    {
                        if (!Partitions.Contains(partition))
                        {
                            throw new ArgumentException(SR.ServerNotAReplica, nameof(partition));
                        }

                        string?serverDownName = null;
                        // this is the error returned when the server that we want to sync from is down
                        if (result == ExceptionHelper.RPC_S_SERVER_UNAVAILABLE)
                        {
                            serverDownName = sourceServer;
                        }
                        // this is the error returned when the server that we want to get synced is down
                        else if (result == ExceptionHelper.RPC_S_CALL_FAILED)
                        {
                            serverDownName = Name;
                        }

                        throw ExceptionHelper.GetExceptionFromErrorCode(result, serverDownName);
                    }
                }
            }
            finally
            {
                if (unmanagedGuid != (IntPtr)0)
                {
                    Marshal.FreeHGlobal(unmanagedGuid);
                }

                adamServer?.Dispose();
                dcServer?.Dispose();
            }
        }
Пример #19
0
        /// <summary>
        /// Handle an acknowledgement with a ProduceResponse. Essentially search for errors and discard/retry
        /// accordingly. The logic is rather painful and boring. We try to be as efficient as possible
        /// in the standard case (i.e. no error).
        /// </summary>
        /// <param name="acknowledgement"></param>
        /// <returns></returns>
        private async Task HandleProduceAcknowledgement(ProduceAcknowledgement acknowledgement)
        {
            // The whole point of scanning the response is to search for errors
            var originalBatch   = acknowledgement.OriginalBatch;
            var produceResponse = acknowledgement.ProduceResponse.ProducePartitionResponse;
            var throttled       = acknowledgement.ProduceResponse.ThrottleTime;

            if (throttled > 0)
            {
                Throttled(throttled);
            }

            // Fill partitions in error caches
            _tmpPartitionsInError.Clear();
            _tmpPartitionsInRecoverableError.Clear();
            foreach (var tr in produceResponse.TopicsResponse)
            {
                bool errors = false;
                foreach (var p in tr.PartitionsData.Where(p => !IsPartitionOkForClients(p.ErrorCode)))
                {
                    if (!errors)
                    {
                        errors = true;
                        _tmpPartitionsInError[tr.TopicName]            = new HashSet <int>();
                        _tmpPartitionsInRecoverableError[tr.TopicName] = new HashSet <int>();
                    }

                    if (Error.IsPartitionErrorRecoverableForProducer(p.ErrorCode))
                    {
                        _cluster.Logger.LogWarning(
                            string.Format("Recoverable error detected: [topic: {0} - partition: {1} - error: {2}]",
                                          tr.TopicName, p.Partition, p.ErrorCode));
                        _tmpPartitionsInRecoverableError[tr.TopicName].Add(p.Partition);
                        if (p.ErrorCode != ErrorCode.InvalidMessageSize && p.ErrorCode != ErrorCode.InvalidMessage)
                        {
                            _cluster.Logger.LogWarning(
                                string.Format("Will ignore [topic: {0} / partition: {1}] for a time", tr.TopicName,
                                              p.Partition));
                            BlacklistPartition(tr.TopicName, p.Partition);

                            if (p.ErrorCode == ErrorCode.RequestTimedOut)
                            {
                                BrokerTimeoutError(tr.TopicName);
                            }
                        }
                    }
                    else
                    {
                        _cluster.Logger.LogError(
                            string.Format("Irrecoverable error detected: [topic: {0} - partition: {1} - error: {2}]",
                                          tr.TopicName, p.Partition, p.ErrorCode));
                        _tmpPartitionsInError[tr.TopicName].Add(p.Partition);
                    }
                }
            }

            // In case of recoverable errors, refresh metadata if they are too old
            if (_tmpPartitionsInRecoverableError.Count > 0 && acknowledgement.ReceiveDate > _routingTable.LastRefreshed)
            {
                await EnsureHasRoutingTable();
            }

            // Scan messages for errors and release memory if needed.
            // Messages associated to recoverable errors are reenqueued for rerouting,
            // messages with irrecoverable errors are discarded and messages with
            // no error are marked sent.
            foreach (var grouping in originalBatch)
            {
                int           sent = 0;
                HashSet <int> errPartitions;
                if (!_tmpPartitionsInError.TryGetValue(grouping.Key, out errPartitions))
                {
                    errPartitions = NullHash;
                }
                HashSet <int> recPartitions;
                if (!_tmpPartitionsInRecoverableError.TryGetValue(grouping.Key, out recPartitions))
                {
                    recPartitions = NullHash;
                }

                foreach (var pm in grouping.SelectMany(g => g))
                {
                    if (recPartitions.Contains(pm.Partition))
                    {
                        ReEnqueueAfterError(pm);
                    }
                    else
                    {
                        if (errPartitions.Contains(pm.Partition))
                        {
                            _cluster.Logger.LogError(
                                string.Format(
                                    "[Producer] Irrecoverable error, discarding message for [topic: {0} / partition: {1}]",
                                    pm.Topic, Partitions.Format(pm.Partition)));
                            OnMessageDiscarded(pm);
                        }
                        else
                        {
                            ++sent;
                            ClearMessage(pm.Message);
                        }
                    }
                }
                if (sent > 0)
                {
                    MessagesAcknowledged(grouping.Key, sent);
                }
            }
        }
Пример #20
0
 private Node GetNextHome(Partitions partition)
 {
     Node home;
     if (partition == Partitions.Primary)
     {
         home = _primaryHomeNodes[_primaryHomeIndex];
         if (_primaryHomeIndex + 1 == _primaryHomeNodes.Count) _primaryHomeIndex = 0;
         else _primaryHomeIndex++;
     }
     else
     {
         home = _secondaryHomeNodes[_secondaryHomeIndex];
         if (_secondaryHomeIndex + 1 == _secondaryHomeNodes.Count) _secondaryHomeIndex = 0;
         else _secondaryHomeIndex++;
     }
     return home;
 }
Пример #21
0
        // Raise the MessageExpired event and release a message.
        private void OnMessageExpired(ProduceMessage message)
        {
            _cluster.Logger.LogError(string.Format(
                                         "[Producer] Not able to send message before reaching TTL for [topic: {0} / partition: {1} (required {2})], message expired.",
                                         message.Topic, Partitions.Format(message.Partition), Partitions.Format(message.RequiredPartition)));

            ClearMessage(message.Message, shouldClearKeyValue: false);
            MessageExpired(message.Topic, message.Message);
        }
Пример #22
0
 private int[] GetTimes(Partitions partition, int count, bool toDest)
 {
     int spread, time;
     if (partition == Partitions.Primary)
     {
         spread = Project.Settings.PrimaryTimeSpread;
         if (toDest) time = Project.Settings.PrimaryToDestTime;
         else time = Project.Settings.PrimaryToHomeTime;
     }
     else
     {
         spread = Project.Settings.SecondaryTimeSpread;
         if (toDest) time = Project.Settings.SecondaryToDestTime;
         else time = Project.Settings.SecondaryToHomeTime;
     }
         
     Random random = new Random();
     List<int> times = new List<int>();
     for (int i = 0; i < count; i++)
         times.Add(time + random.Next(spread * -1, spread));
     return times.ToArray();
 }
Пример #23
0
        private Vehicle[] CreateVehicles(Partitions partition, int count)
        {
            Project project;
            if (partition == Partitions.Primary) project = PrimaryProject;
            else project = SecondaryProject;

            Node[] homes = GetHomes(partition, count);
            Destination[] destinations = GetDestinations(partition, count);
            VehicleType[] vehicleTypes = GetVehicleTypes(count);
            int[] toDestTimes = GetTimes(partition, count, true);
            int[] toHomeTimes = GetTimes(partition, count, false);

            Pathfinder.SetProject(project, partition);
            Vehicle[] vehicles = new Vehicle[count];
            for (int i = 0; i < count; i++)
                vehicles[i] = new Vehicle(project, homes[i], destinations[i], 
                    vehicleTypes[i], toDestTimes[i], toHomeTimes[i]);
            return vehicles;
        }
Пример #24
0
        internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, string sourceServer, int option, LoadLibrarySafeHandle libHandle)
        {
            int              structSize    = Marshal.SizeOf(typeof(Guid));
            IntPtr           unmanagedGuid = (IntPtr)0;
            Guid             guid          = Guid.Empty;
            AdamInstance     adamServer    = null;
            DomainController dcServer      = null;

            unmanagedGuid = Marshal.AllocHGlobal(structSize);
            try
            {
                if (sourceServer != null)
                {
                    DirectoryContext newContext = Utils.GetNewDirectoryContext(sourceServer, DirectoryContextType.DirectoryServer, context);
                    if (isADAM)
                    {
                        adamServer = AdamInstance.GetAdamInstance(newContext);
                        guid       = adamServer.NtdsaObjectGuid;
                    }
                    else
                    {
                        dcServer = DomainController.GetDomainController(newContext);
                        guid     = dcServer.NtdsaObjectGuid;
                    }

                    Marshal.StructureToPtr(guid, unmanagedGuid, false);
                }

                // call DsReplicaSyncW
                IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaSyncW");
                if (functionPtr == (IntPtr)0)
                {
                    throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
                }
                UnsafeNativeMethods.DsReplicaSyncW dsReplicaSyncW = (UnsafeNativeMethods.DsReplicaSyncW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaSyncW));

                int result = dsReplicaSyncW(dsHandle, partition, unmanagedGuid, (int)option);

                // check the result
                if (result != 0)
                {
                    if (!Partitions.Contains(partition))
                    {
                        throw new ArgumentException(SR.ServerNotAReplica, "partition");
                    }

                    string serverDownName = null;
                    // this is the error returned when the server that we want to sync from is down
                    if (result == ExceptionHelper.RPC_S_SERVER_UNAVAILABLE)
                    {
                        serverDownName = sourceServer;
                    }
                    // this is the error returned when the server that we want to get synced is down
                    else if (result == ExceptionHelper.RPC_S_CALL_FAILED)
                    {
                        serverDownName = Name;
                    }

                    throw ExceptionHelper.GetExceptionFromErrorCode(result, serverDownName);
                }
            }
            finally
            {
                if (unmanagedGuid != (IntPtr)0)
                {
                    Marshal.FreeHGlobal(unmanagedGuid);
                }

                if (adamServer != null)
                {
                    adamServer.Dispose();
                }

                if (dcServer != null)
                {
                    dcServer.Dispose();
                }
            }
        }
Пример #25
0
 private Node GetNextInbound(Partitions partition)
 {
     Node inbound;
     if (partition == Partitions.Primary)
     {
         inbound = _primaryInboundNodes[_primaryInboundIndex];
         if (_primaryInboundIndex + 1 == _primaryInboundNodes.Count) _primaryInboundIndex = 0;
         else _primaryInboundIndex++;
     }
     else
     {
         inbound = _secondaryInboundNodes[_primaryInboundIndex];
         if (_secondaryInboundIndex + 1 == _secondaryInboundNodes.Count) _secondaryInboundIndex = 0;
         else _secondaryInboundIndex++;
     }
     return inbound;
 }
Пример #26
0
        private void SetupCommands()
        {
            this.Open = new RelayCommand(async() => {
                this.IsOpening = true;
                this.Partitions.Clear();
                this.Messages.Clear();

                _partitionSubscription = _service.PartitionFound.Subscribe((p) =>
                {
                    App.Current.Dispatcher.BeginInvoke(new Action(() => {
                        this.TotalMessageCount = _service.MessageCount;
                        Partitions.Add(new PartitionViewModel(p));
                    }), null);
                },
                                                                           () => {
                    App.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        this.IsOpening = false;
                    }));
                });
                await _service.OpenEventHubAsync(EventHubConnectionString, HubName);
                UpdateCommands();
            });

            this.ReadAll = new RelayCommand(() =>
            {
                ResetReading();
                switch (CheckPoint)
                {
                case CheckPointTypes.Start:
                    _service.ReadAllAsync(DateTime.MinValue);
                    break;

                case CheckPointTypes.Now:
                    _service.ReadAllAsync(DateTime.Now);
                    break;

                case CheckPointTypes.PastMinutes:
                    _service.ReadAllAsync(TimeSpan.FromMinutes(this.PastMinutes));
                    break;

                case CheckPointTypes.PastMessages:
                    _service.ReadAllAsync(this.PastMessages);
                    break;

                default:
                    break;
                }
                IsReading = true;
                UpdateCommands();
            }, () => {
                return(!_service.IsReading && _service.IsOpen);
            });

            this.Read = new RelayCommand <PartitionViewModel>((p) => {
                ResetReading();
                switch (CheckPoint)
                {
                case CheckPointTypes.Start:
                    _service.ReadAsync(p.PartitionId, DateTime.MinValue);
                    break;

                case CheckPointTypes.Now:
                    _service.ReadAsync(p.PartitionId, DateTime.Now);
                    break;

                case CheckPointTypes.PastMinutes:
                    break;

                case CheckPointTypes.PastMessages:
                    break;

                default:
                    break;
                }
                IsReading = true;
                UpdateCommands();
            }
                                                              );

            this.FilterByPublisher = new RelayCommand <string>((publisher) =>
            {
                if (string.IsNullOrWhiteSpace(publisher))
                {
                    return;
                }

                var found = (from m in Messages where m.Publisher == publisher select m).ToList();
                Messages.Clear();
                foreach (var f in found)
                {
                    Messages.Add(f);
                }
            });

            this.Stop = new RelayCommand(() =>
            {
                StopReading();
            }, () => { return(_service.IsReading); });
        }
Пример #27
0
        // GetDestinations //
        private Destination[] GetDestinations(Partitions partition, int count)
        {
            int outbound;
            if (partition == Partitions.Primary) outbound = Project.Settings.PrimaryOutbound;
            else outbound = Project.Settings.SecondaryOutbound;
            int outboundCount = count * (outbound / 100);

            List<Destination> destinations = new List<Destination>();
            for (int i = 0; i < outboundCount; i++)
                destinations.Add(null);

            int remaining = count - outboundCount;
            foreach (DestinationType destType in Project.DestinationTypes)
            {
                if (destType.Distribution == 0)
                    continue;

                List<Destination> destsWithType = Project.Destinations.FindAll(d => d.Type == destType);
                if (destsWithType.Count == 0)
                    throw new Exception("No destinations with type: " + destType.Name);

                int addAmount = Convert.ToInt32(remaining * (destType.Distribution / 100));
                int index = 0;
                for (int i = 0; i < addAmount; i++)
                {
                    destinations.Add(destsWithType[index]);
                    if (index + 1 == destsWithType.Count) index = 0;
                    else index++;
                }
            }

            return destinations.ToArray();
        }
Пример #28
0
        public void InsertPartition(Partition partition, int commandTopics, int commandSubscriptions,
                                    string area, string ns,
                                    string owner, string ownerSecret, string storageAccount,
                                    string acs, string acsSecret)
        {
            if (partition == null)
            {
                throw new ArgumentNullException("partition");
            }

            if (commandTopics <= 0)
            {
                throw new ArgumentOutOfRangeException("commandTopics");
            }

            if (commandSubscriptions <= 0)
            {
                throw new ArgumentOutOfRangeException("commandSubscriptions");
            }

            if (string.IsNullOrWhiteSpace(area))
            {
                throw new ArgumentException("area");
            }

            if (string.IsNullOrWhiteSpace(ns))
            {
                throw new ArgumentException("ns");
            }

            if (string.IsNullOrWhiteSpace(owner))
            {
                throw new ArgumentException("owner");
            }

            if (string.IsNullOrWhiteSpace(ownerSecret))
            {
                throw new ArgumentException("ownerSecret");
            }

            if (string.IsNullOrWhiteSpace(storageAccount))
            {
                throw new ArgumentException("storageAccount");
            }

            if (string.IsNullOrWhiteSpace(acs))
            {
                throw new ArgumentException("acs");
            }

            if (string.IsNullOrWhiteSpace(acsSecret))
            {
                throw new ArgumentException("acsSecret");
            }

            partition.Area = area;
            partition.MaximumCommandTopic = commandTopics;
            partition.MaximumSubscription = commandSubscriptions;
            partition.Namespace           = ns;
            partition.Owner               = owner;
            partition.OwnerSecret         = ownerSecret;
            partition.StorageAccount      = storageAccount;
            partition.AccessControl       = acs;
            partition.AccessControlSecret = acsSecret;
            Partitions.Add(partition);

            SaveChanges();
            DetachEntity(partition);
        }
Пример #29
0
        internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondaryType, string partition, ref bool advanced, int context, LoadLibrarySafeHandle libHandle)
        {
            IntPtr info           = (IntPtr)0;
            int    result         = 0;
            bool   needToTryAgain = true;
            IntPtr functionPtr;

            // first try to use the DsReplicaGetInfo2W API which does not exist on win2k machine
            // call DsReplicaGetInfo2W
            functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfo2W");
            if (functionPtr == (IntPtr)0)
            {
                // a win2k machine which does not have it.
                functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfoW");
                if (functionPtr == (IntPtr)0)
                {
                    throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
                }
                UnsafeNativeMethods.DsReplicaGetInfoW dsReplicaGetInfoW = (UnsafeNativeMethods.DsReplicaGetInfoW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaGetInfoW));
                result         = dsReplicaGetInfoW(dsHandle, secondaryType, partition, (IntPtr)0, ref info);
                advanced       = false;
                needToTryAgain = false;
            }
            else
            {
                UnsafeNativeMethods.DsReplicaGetInfo2W dsReplicaGetInfo2W = (UnsafeNativeMethods.DsReplicaGetInfo2W)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaGetInfo2W));
                result = dsReplicaGetInfo2W(dsHandle, type, partition, (IntPtr)0, null, null, 0, context, ref info);
            }

            // check the result
            if (needToTryAgain && result == DS_REPL_NOTSUPPORTED)
            {
                // this is the case that client is xp/win2k3, dc is win2k
                functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfoW");
                if (functionPtr == (IntPtr)0)
                {
                    throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
                }
                UnsafeNativeMethods.DsReplicaGetInfoW dsReplicaGetInfoW = (UnsafeNativeMethods.DsReplicaGetInfoW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaGetInfoW));

                result   = dsReplicaGetInfoW(dsHandle, secondaryType, partition, (IntPtr)0, ref info);
                advanced = false;
            }

            if (result != 0)
            {
                if (partition != null)
                {
                    // this is the case of meta data
                    if (type == (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_2_FOR_OBJ)
                    {
                        if (result == ExceptionHelper.ERROR_DS_DRA_BAD_DN || result == ExceptionHelper.ERROR_DS_NAME_UNPARSEABLE)
                        {
                            throw new ArgumentException(ExceptionHelper.GetErrorMessage(result, false), "objectPath");
                        }

                        DirectoryEntry verifyEntry = DirectoryEntryManager.GetDirectoryEntry(this.context, partition);
                        try
                        {
                            verifyEntry.RefreshCache(new string[] { "name" });
                        }
                        catch (COMException e)
                        {
                            if (e.ErrorCode == unchecked ((int)0x80072020) |          // dir_error on server side
                                e.ErrorCode == unchecked ((int)0x80072030))           // object not exists
                            {
                                throw new ArgumentException(SR.DSNoObject, "objectPath");
                            }
                            else if (e.ErrorCode == unchecked ((int)0x80005000) | // bad path name
                                     e.ErrorCode == unchecked ((int)0x80072032))  // ERROR_DS_INVALID_DN_SYNTAX
                            {
                                throw new ArgumentException(SR.DSInvalidPath, "objectPath");
                            }
                        }
                    }
                    else
                    {
                        if (!Partitions.Contains(partition))
                        {
                            throw new ArgumentException(SR.ServerNotAReplica, "partition");
                        }
                    }
                }

                throw ExceptionHelper.GetExceptionFromErrorCode(result, Name);
            }

            return(info);
        }
Пример #30
0
        public DiskModel(LsblkJsonModel.Blockdevice source)
        {
            Guid       = System.Guid.NewGuid().ToString();
            Name       = source.name;
            Kname      = source.kname;
            MajMin     = source.maj_min;
            Fstype     = source.fstype;
            Mountpoint = source.mountpoint;
            Label      = source.label;
            Uuid       = source.uuid;
            Parttype   = source.parttype;
            Partlabel  = source.partlabel;
            Partuuid   = source.partuuid;
            Partflags  = source.partflags;
            Ra         = source.ra;
            Ro         = source.ro;
            Rm         = source.rm;
            Hotplug    = source.hotplug;
            Model      = source.model;
            Serial     = source.serial;
            Size       = source.size;
            State      = source.state;
            Owner      = source.owner;
            Group      = source.group;
            Mode       = source.mode;
            Alignment  = source.alignment;
            MinIo      = source.min_io;
            OptIo      = source.opt_io;
            PhySec     = source.phy_sec;
            LogSec     = source.log_sec;
            Rota       = source.rota;
            Sched      = source.sched;
            RqSize     = source.rq_size;
            Type       = source.type;
            DiscAln    = source.disc_aln;
            DiscGran   = source.disc_gran;
            DiscMax    = source.disc_max;
            DiscZero   = source.disc_zero;
            Wsame      = source.wsame;
            Wwn        = source.wwn;
            Rand       = source.rand;
            Pkname     = source.pkname;
            Hctl       = source.hctl;
            Tran       = source.tran;
            Subsystems = source.subsystems;
            Rev        = source.rev;
            Vendor     = source.vendor;

            var list = new List <PartitionModel>();

            if (source.children != null)
            {
                foreach (var c in source.children)
                {
                    var p = new PartitionModel(c);
                    list.Add(p);
                }
            }
            Partitions = list;

            if (Partitions.Any())
            {
                HasPartition = true;
            }
            var bash = new Bash();

            Partprobe = bash.Execute($"partprobe -s /dev/{Name}");
        }
Пример #31
0
 public MemoryPartition GetPartition(Partitions Partition)
 {
     return MemoryPartitionsUid.Get((int)Partition);
 }
Пример #32
0
 public MemoryPartition GetPartition(Partitions Partition)
 {
     return(MemoryPartitionsUid.Get((int)Partition));
 }