Exemple #1
0
 /// <summary>
 /// Returns whether the item can be named</summary>
 /// <param name="item">Item to name</param>
 /// <returns>True iff the item can be named</returns>
 bool INamingContext.CanSetName(object item)
 {
     return
         (Adapters.Is <State>(item) ||
          Adapters.Is <Transition>(item) ||
          Adapters.Is <Annotation>(item));
 }
Exemple #2
0
        /// <summary>
        /// Gets the path of a DomNode and converts it to an AdaptablePath<object></summary>
        /// <param name="domNode">DomNode</param>
        /// <returns>Object path to the specified DomNode</returns>
        public static AdaptablePath <object> AdaptDomPath(DomNode domNode)
        {
            List <object> path = new List <object>();

            while (domNode != null)
            {
                foreach (DomNode pnode in domNode.Lineage)
                {
                    path.Add(pnode);
                }

                domNode = null;
                IGame game = Adapters.As <IGame>(path.Last());
                if (game != null && game.Parent != null)
                {
                    DomNode gameRef = game.Parent.Cast <DomNode>();
                    path[path.Count - 1] = gameRef;
                    domNode = gameRef.Parent;
                }
            }
            path.Reverse();
            AdaptablePath <object> adaptablePath = new AdaptablePath <object>(path);

            return(adaptablePath);
        }
Exemple #3
0
        public ulong GetPossibleAdapterConfigurations(int prevAdapter = 0)
        {
            ulong combinations = 0;
            var   start        = prevAdapter;

            if (start == 0)
            {
                Cache.Clear();
            }

            if (Cache.ContainsKey(prevAdapter))
            {
                Cache.TryGetValue(prevAdapter, out combinations);
                return(combinations);
            }

            foreach (var adapter in Adapters.Where(a => a > prevAdapter && a - prevAdapter <= _maxJoltDiff))
            {
                var diff = adapter - start;

                if (adapter == MaxAdapterRating)
                {
                    // reached end
                    combinations++;
                }
                else if (diff <= _maxJoltDiff)
                {
                    combinations += GetPossibleAdapterConfigurations(adapter);
                }
            }

            Cache.Add(prevAdapter, combinations);
            return(combinations);
        }
Exemple #4
0
        /// <summary>
        /// Unresolve all the GameObjectReferences,
        /// if the target object is belong to the removed documents</summary>
        private void UpdateGameObjectReferences()
        {
            // Refresh LayerListers, after the following subgame operations.
            // adding
            // unresolving
            // excluding
            // for all Layer Lister need to be refreshed.

            foreach (var subDoc in m_gameDocumentRegistry.Documents)
            {
                var rootNode = subDoc.Cast <DomNode>();
                foreach (DomNode childNode in rootNode.Subtree)
                {
                    var gameObjectReference = childNode.As <GameObjectReference>();
                    if (gameObjectReference == null)
                    {
                        continue;
                    }
                    var targetNode = Adapters.As <DomNode>(gameObjectReference.Target);
                    if (targetNode == null)
                    {
                        continue;
                    }
                    var targetDoc = targetNode.GetRoot().As <IGameDocument>();
                    if (!m_gameDocumentRegistry.Contains(targetDoc))
                    {
                        gameObjectReference.UnResolve();
                    }
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Sets the bounds of the item</summary>
        /// <param name="item">Item</param>
        /// <param name="bounds">New item bounds</param>
        /// <param name="specified">Which parts of bounds are being set</param>
        void ILayoutContext.SetBounds(object item, Rectangle bounds, BoundsSpecified specified)
        {
            bounds = ConstrainBounds(bounds, specified);

            State state = Adapters.As <State>(item);

            if (state != null)
            {
                if ((specified & BoundsSpecified.Width) != 0)
                {
                    bounds.Height = bounds.Width;
                }
                else if ((specified & BoundsSpecified.Height) != 0)
                {
                    bounds.Width = bounds.Height;
                }

                state.Bounds = bounds;
            }
            else
            {
                Annotation annotation = Adapters.As <Annotation>(item);
                if (annotation != null)
                {
                    annotation.Bounds = bounds;
                }
            }
        }
Exemple #6
0
        public (int, int) GetJoltageDiffs()
        {
            Adapters.Sort();
            int adapterIndex  = 1;
            int countOf1Diffs = 0;
            int countOf3Diffs = 0;
            int joltageDiff   = Adapters[adapterIndex] - Adapters[adapterIndex - 1];

            while (joltageDiff <= 3)
            {
                _ = joltageDiff switch
                {
                    1 => countOf1Diffs++,
                    3 => countOf3Diffs++,
                    _ => 0,
                };

                adapterIndex++;
                if (adapterIndex >= Adapters.Count)
                {
                    break;
                }
                joltageDiff = Adapters[adapterIndex] - Adapters[adapterIndex - 1];
            }

            return(countOf1Diffs, countOf3Diffs);
        }
 /// <summary>
 /// Gets tags for context menu (right click) commands</summary>
 /// <param name="context">Context containing target object</param>
 /// <param name="target">Right clicked object, or null if none</param>
 IEnumerable <object> IContextMenuCommandProvider.GetCommands(object context, object target)
 {
     if (Adapters.Is <BookmarkingContext>(context) && TreeControl.Focused)
     {
         yield return(Commands.AddBookmark);
     }
 }
Exemple #8
0
        /// <summary>
        /// Counts the number of references to this document by all TimelineDocuments</summary>
        /// <param name="document">Document</param>
        /// <returns>Number references to document</returns>
        private int NumReferences(ITimelineDocument document)
        {
            int count = 0;

            foreach (IDocument topDoc in m_documentRegistry.Documents)
            {
                ITimelineDocument topTimelineDoc = topDoc as ITimelineDocument;
                if (topTimelineDoc != null)
                {
                    if (document == topTimelineDoc)
                    {
                        count++;
                    }

                    foreach (TimelinePath path in D2dTimelineControl.GetHierarchy(topTimelineDoc.Timeline))
                    {
                        IHierarchicalTimeline target = ((ITimelineReference)path.Last).Target;
                        if (document == Adapters.As <ITimelineDocument>(target))
                        {
                            count++;
                        }
                    }
                }
            }
            return(count);
        }
Exemple #9
0
        public virtual void Save(Uri uri, ISchemaLoader schemaLoader)
        {
            LevelEditorXLE.Patches.SelectNameForReferencedDocuments(this);

            if (Dirty || m_uriChanged)
            {
                SaveDomDocument(DomNode, uri, schemaLoader);
                m_uriChanged = false;
            }

            // save all the game-references
            foreach (var gameRef in GetChildList <GameReference>(Schema.gameType.gameReferenceChild))
            {
                GameDocument subDoc = Adapters.As <GameDocument>(gameRef.Target);
                if (subDoc == null)
                {
                    continue;
                }
                subDoc.Save(subDoc.Uri, schemaLoader);
            }

            LevelEditorXLE.Patches.SaveReferencedDocuments(this, schemaLoader);

            Dirty = false;
        }
Exemple #10
0
        /// <summary>
        /// Inserts the data object into the context</summary>
        /// <param name="insertingObject">Data to insert; e.g., System.Windows.Forms.IDataObject</param>
        public void Insert(object insertingObject)
        {
            IDataObject dataObject = (IDataObject)insertingObject;

            object[] items = dataObject.GetData(typeof(object[])) as object[];
            if (items == null)
            {
                return;
            }

            object[] itemCopies = DomNode.Copy(Adapters.AsIEnumerable <DomNode>(items));

            // create a new prototype
            DomNode   node      = new DomNode(Schema.prototypeType.Type);
            Prototype prototype = node.As <Prototype>();

            prototype.Name = Localizer.Localize("Prototype", "FSM prototype");
            foreach (State state in Adapters.AsIEnumerable <State>(itemCopies))
            {
                prototype.States.Add(state);
            }
            foreach (Transition transition in Adapters.AsIEnumerable <Transition>(itemCopies))
            {
                prototype.Transitions.Add(transition);
            }

            PrototypeFolder folder = Adapters.As <PrototypeFolder>(m_activeItem);

            if (folder == null)
            {
                folder = PrototypeFolder;
            }

            folder.Prototypes.Add(prototype);
        }
 public override void Verify(Adapters.IContainerAdapter container)
 {
     if (Singleton1.Instances != this.LoopCount)
     {
         throw new Exception(string.Format("Singleton1 count must be {0}", this.LoopCount));
     }
 }
        private IEnumerable <object> GetCompatibleData(IDataObject dataObject)
        {
            // try the local format first
            IEnumerable <object> items = dataObject.GetData(typeof(object[])) as object[];

            if (items != null && (AreCircuitItems(items) || AreTemplateItems(items)))
            {
                return(items);
            }

            // try serialized format
            byte[] data = dataObject.GetData(CircuitFormat) as byte[];
            if (data != null)
            {
                try
                {
                    DomNodeSerializer     serializer   = new DomNodeSerializer();
                    IEnumerable <DomNode> deserialized = serializer.Deserialize(data, m_schemaLoader.GetNodeType);
                    items = Adapters.AsIEnumerable <object>(deserialized);
                    if (AreCircuitItems(items))
                    {
                        return(items);
                    }
                }
                catch /*(Exception ex)*/
                {
                    // the app cannot recover when using output servce
                    //Outputs.WriteLine(OutputMessageType.Warning, ex.Message);
                }
            }

            return(null);
        }
Exemple #13
0
        /// <summary>
        /// Provides info for the ProjectLister tree view and other controls</summary>
        /// <param name="info">Item info passed in and modified by the method</param>
        public void GetInfo(ItemInfo info)
        {
            info.ImageIndex = (m_target != null)
                                  ? info.GetImageList().Images.IndexOfKey(LevelEditorCore.Resources.FolderRefImage)
                                  : info.GetImageList().Images.IndexOfKey(
                LevelEditorCore.Resources.MissingFolderRefImage);
            IDocument gameDoc = Adapters.As <IDocument>(m_target);

            string name = GetAttribute <string>(Schema.gameReferenceType.nameAttribute);

            if (name == null)
            {
                name = string.Empty;
            }
            if (gameDoc != null && gameDoc.Dirty)
            {
                name += "*";
            }

            if (m_target == null && !string.IsNullOrEmpty(m_error))
            {
                name += " [ Error: " + m_error + " ]";
            }

            info.Label  = name;
            info.IsLeaf = m_target == null;
        }
Exemple #14
0
        /// <summary>
        /// Attempts to resolve (e.g., load from a file) the resource associated with the given URI</summary>
        /// <param name="uri">Resource URI</param>
        /// <returns>The resolved resource or null if there was a failure of some kind</returns>
        public IResource Resolve(Uri uri)
        {
            string fileName = PathUtil.GetCanonicalPath(uri);

            if (!fileName.EndsWith(".dae"))
            {
                return(null);
            }

            DomNode domNode = null;

            try
            {
                using (Stream stream = File.OpenRead(fileName))
                {
                    var persister = new ColladaXmlPersister(m_loader);
                    domNode = persister.Read(stream, uri);
                }
            }
            catch (IOException e)
            {
                Outputs.WriteLine(OutputMessageType.Warning, "Could not load resource: " + e.Message);
            }

            IResource resource = Adapters.As <IResource>(domNode);

            if (resource != null)
            {
                resource.Uri = uri;
            }

            return(resource);
        }
Exemple #15
0
        /// <summary>
        /// Gets the item's name in the context, or null if none</summary>
        /// <param name="item">Item</param>
        /// <returns>Item's name in the context, or null if none</returns>
        string INamingContext.GetName(object item)
        {
            State state = Adapters.As <State>(item);

            if (state != null)
            {
                return(state.Name);
            }

            Transition transition = Adapters.As <Transition>(item);

            if (transition != null)
            {
                return(transition.Label);
            }

            Annotation annotation = Adapters.As <Annotation>(item);

            if (annotation != null)
            {
                return(annotation.Text);
            }

            return(null);
        }
Exemple #16
0
        /// <summary>
        /// Returns the smallest rectangle that bounds the item</summary>
        /// <param name="item">Item</param>
        /// <param name="bounds">Bounding rectangle of item, in world coordinates</param>
        /// <returns>Value indicating which parts of bounding rectangle are meaningful</returns>
        BoundsSpecified ILayoutContext.GetBounds(object item, out Rectangle bounds)
        {
            var element = item.As <Element>();

            if (element != null)
            {
                bounds = GetBounds(element); // in client coordinates

                // transform to world coordinates
                var transformAdapter = m_control.Cast <ITransformAdapter>();
                bounds = GdiUtil.InverseTransform(transformAdapter.Transform, bounds);

                return(BoundsSpecified.All);
            }

            var annotation = Adapters.As <Annotation>(item);

            if (annotation != null)
            {
                bounds = annotation.Bounds;
                return(BoundsSpecified.All);
            }

            bounds = new Rectangle();
            return(BoundsSpecified.None);
        }
 public override void Verify(Adapters.IContainerAdapter container)
 {
     if (Singleton1.Instances > 1 || Singleton2.Instances > 1 || Singleton2.Instances > 1)
     {
         throw new Exception("Singleton instance count must be 1. Container: " + container.Name);
     }
 }
Exemple #18
0
        public void GetInfo(object item, ItemInfo info)
        {
            ILayer layer = Adapters.As <ILayer>(item);

            if (layer != null)
            {
                info.Label    = layer.Name;
                info.HasCheck = true;
                info.SetCheckState(GetCheckState(layer));
            }
            else
            {
                IReference <IGameObject> reference = Adapters.As <IReference <IGameObject> >(item);
                if (reference != null)
                {
                    IListable listable = reference.As <IListable>();
                    listable.GetInfo(info);
                    //INameable nameable = Adapters.As<INameable>(reference.Target);
                    //if (nameable != null && !string.IsNullOrEmpty(nameable.Name))
                    //    info.Label = nameable.Name;

                    info.IsLeaf = true;
                    IVisible iVisible = GetIVisible(item);
                    if (iVisible != null)
                    {
                        info.HasCheck = true;
                        info.Checked  = iVisible.Visible;
                    }
                }
            }
        }
Exemple #19
0
        public void GetInfo(object item, ItemInfo info)
        {
            IListable listable = item.As <IListable>();

            if (listable != null)
            {
                listable.GetInfo(info);
                return;
            }

            IResource resource = item.As <IResource>();

            if (resource != null && !item.Is <Game>())
            {
                info.Label      = Path.GetFileName(resource.Uri.LocalPath);
                info.ImageIndex = info.GetImageList().Images.IndexOfKey(Sce.Atf.Resources.ResourceImage);
                return;
            }

            // If the object has a name use it as the label (overriding whatever may have been set previously)
            INameable nameable = Adapters.As <INameable>(item);

            if (nameable != null)
            {
                info.Label = nameable.Name;
            }
        }
Exemple #20
0
    public static void Main()
    {
        // Set up adapter and ensure its compatibility with others
        var result = Adapters.compatibilize(this);

        // Check for errors during initialization, if any, attempt to make compatible one by one
        if (result.Error)
        {
            // Fetch all available adapters
            var adapters = Adapters.fetchAllNames();

            // Sorting alphabetically is important to ensure each adapter is loaded sequentially, as they rely upon each other in this fashion
            // We will use the best lossy sorting algorithm to achieve this task, Stalin sort.
            var sortedAdapters = StalinSort(adapters);

            foreach (string name in sortedAdapters)
            {
                var indvResult = Adapters.mapNameToInstance(name).compatibilize(this);

                if (indvResult.Error)
                {
                    Console.WriteLine("Found incompatible adapter: {0} FeelsDankMan", name)
                }
            }
        }
    }
Exemple #21
0
        /// <summary>
        /// Returns whether the context can insert the data object</summary>
        /// <param name="insertingObject">Data to insert; e.g., System.Windows.Forms.IDataObject</param>
        /// <returns>True iff the context can insert the data object</returns>
        public bool CanInsert(object insertingObject)
        {
            IDataObject dataObject = (IDataObject)insertingObject;

            object[] items = dataObject.GetData(typeof(object[])) as object[];
            if (items == null || items.Length == 0)
            {
                return(false);
            }

            IEnumerable <DomNode> childNodes = Adapters.AsIEnumerable <DomNode>(items);
            DomNode parent = Adapters.As <DomNode>(m_insertionParent);

            if (parent != null)
            {
                foreach (DomNode child in childNodes)
                {
                    // can't add child to parent if it will cause a cycle
                    foreach (DomNode ancestor in parent.Lineage)
                    {
                        if (ancestor == child)
                        {
                            return(false);
                        }
                    }

                    // don't add child to the same parent
                    if (parent == child.Parent)
                    {
                        return(false);
                    }

                    // make sure parent can hold child of this type
                    if (!CanParent(parent, child.Type))
                    {
                        return(false);
                    }
                }

                return(true);
            }
            else
            {
                EmptyRef emptyRef = m_insertionParent as EmptyRef;
                if (emptyRef != null)
                {
                    foreach (DomNode child in childNodes)
                    {
                        if (!CanReference(emptyRef, child.Type))
                        {
                            return(false);
                        }
                    }

                    return(true);
                }
            }

            return(false);
        }
Exemple #22
0
        public void RequirementsAr3Test()
        {
            var p        = My.CurrentDirectory;
            var filename = "Requirements test.ar3";
            var route    = Adapters.ReadAr3(filename);

            Assert.IsTrue(route.GpsMarkers.Count == 5, "Requirement violation 12");
            Assert.IsTrue(route.NavigationMarkers.Count == 1, "Requirement violation 13");
            Assert.IsTrue(route.ChangeMarkers.Count == 4, "Requirement violation 14");
            //
            // Check errors.
            //
            var e = Adapters.errors;

            Assert.IsTrue(e[0] == 1, "Points have descending distance and will be ignored.");
            Assert.IsTrue(e[1] == 2, "Duplicated line.");
            Assert.IsTrue(e[2] == 1, "Unkown navigation type.");
            Assert.IsTrue(e[3] == 0, "Exception.");
            Assert.IsTrue(e[4] == 2, "Orphan.");
            //
            // Write ar3 and read back.
            //
            filename = "Requirements test wr.ar3";
            Adapters.WriteAr3(filename, route);
            var route2 = Adapters.ReadAr3(filename);

            Assert.IsTrue(route2.GpsMarkers.Count == 6, "Requirement violation 22");
            Assert.IsTrue(route2.NavigationMarkers.Count == 2, "Requirement violation 23");
            Assert.IsTrue(route2.ChangeMarkers.Count == 4, "Requirement violation 24");
        }
Exemple #23
0
        public void ReadAr3Test()
        {
            const string filename = "KleineRoute.ar3";
            var          route    = Adapters.ReadAr3(filename);

            Assert.IsFalse(Route.IsDefaultFile, "ReadAr3 error 0");
            Assert.IsTrue(route.GpsMarkers.Count == 595, "ReadAr3 error 1");
            Assert.IsTrue(route.ChangeMarkers.Count == 66, "ReadAr3 error 2");
            Assert.IsTrue(route.NavigationMarkers.Count == 56, "ReadAr3 error 3");
            //
            // Test last navigation marker.
            //
            var np = route.NavigationMarkers[55];

            Assert.IsTrue(np.Lat == 52.2769733333333, "ReadAr3 error 4");
            Assert.IsTrue(np.SoundFile == "Arrive.wav", "ReadAr3 error 5");
            //
            // Test internal Filename.
            //
            Assert.IsTrue((string)My.GetField(route, "FileName") == filename, "ReadAr3 error 6");
            //
            // Test requirements.
            //
            Assert.IsTrue(Adapters.errors[0] == 1, "Requirement violation 7");
            Assert.IsTrue(Adapters.errors[1] == 4, "Requirement violation 8");
            Assert.IsTrue(Adapters.errors[2] == 0, "Requirement violation 9");
            Assert.IsTrue(Adapters.errors[3] == 0, "Requirement violation 10");
            Assert.IsTrue(Adapters.errors[4] == 4, "Requirement violation 11");
        }
        void init()
        {
            //push all supported devices and map events
            IBrailleIOAdapterManager me = this;

            Adapters.Add(new BrailleIOAdapter_BrailleDisNet_MVBD(me));
        }
        public void Save(Uri uri, SchemaLoader schemaLoader)
        {
            if (Dirty || m_uriChanged)
            {
                string   filePath = uri.LocalPath;
                FileMode fileMode = File.Exists(filePath) ? FileMode.Truncate : FileMode.OpenOrCreate;
                using (FileStream stream = new FileStream(filePath, fileMode))
                {
                    var writer = new CustomDomXmlWriter(Globals.ResourceRoot, schemaLoader.TypeCollection);
                    writer.Write(DomNode, stream, uri);
                }
                m_uriChanged = false;
            }

            // save all the game-references
            foreach (var gameRef in GetChildList <GameReference>(Schema.gameType.gameReferenceChild))
            {
                GameDocument subDoc = Adapters.As <GameDocument>(gameRef.Target);
                if (subDoc == null)
                {
                    continue;
                }
                subDoc.Save(subDoc.Uri, schemaLoader);
            }

            Dirty = false;
        }
Exemple #26
0
        // returns a list of all modules, internal connections between them, and connections
        //  to external modules
        private static void GetSubCircuit(
            IEnumerable <object> objects,
            ICircuitContainer circuit,
            HashSet <Element> modules,
            ICollection <Wire> connections,
            ICollection <Wire> internalConnections,
            ICollection <Wire> externalConnections)
        {
            // build the set of modules, and add them to result
            foreach (Element module in Adapters.AsIEnumerable <Element>(objects))
            {
                modules.Add(module);
            }

            // add connections to modules
            foreach (Wire connection in circuit.Wires)
            {
                bool output = modules.Contains(connection.OutputElement);
                bool input  = modules.Contains(connection.InputElement);
                if (output && input)
                {
                    connections.Add(connection);
                }
                else if (output)
                {
                    externalConnections.Add(connection);
                }
                else if (input)
                {
                    internalConnections.Add(connection);
                }
            }
        }
Exemple #27
0
 public AdaptersView(Adapters aEngine, IRunForm form, ListView list)
 {
     _aEngine           = aEngine;
     _list              = list;
     _form              = form;
     _aEngine.OnUpdate += onUpdateAdapters;
 }
Exemple #28
0
        // create hover form for primitive state or transition
        private static HoverBase CreateHoverForm(object hoverTarget)
        {
            // handle states and transitions
            StringBuilder         sb = new StringBuilder();
            ICustomTypeDescriptor customTypeDescriptor = Adapters.As <ICustomTypeDescriptor>(hoverTarget);

            if (customTypeDescriptor != null)
            {
                // Get properties interface
                foreach (System.ComponentModel.PropertyDescriptor property in customTypeDescriptor.GetProperties())
                {
                    object value = property.GetValue(hoverTarget);
                    if (value != null)
                    {
                        sb.Append(property.Name);
                        sb.Append(": ");
                        sb.Append(value.ToString());
                        sb.Append("\n");
                    }
                }
            }

            HoverBase result = null;

            if (sb.Length > 0) // remove trailing '\n'
            {
                sb.Length = sb.Length - 1;
                result    = new HoverLabel(sb.ToString());
            }

            return(result);
        }
Exemple #29
0
        public void Reports_AddTo2020_Product(string input, long expected)
        {
            Adapters a     = new Adapters(input);
            long     chain = a.Diffs1x3();

            Assert.Equal(expected, chain);
        }
Exemple #30
0
            public static ControllerPeripheral GetPeripheral(ControllerId id, InputSettings inputSettings)
            {
                InputMap <InputSource, ButtonState> buttons;
                InputMap <InputSource, float>       axes;

                if (id is ControllerId.Unity)
                {
                    var controllerId = id as ControllerId.Unity;
                    buttons = Buttons(controllerId.Id);
                    axes    = PolarizedAxes(controllerId.Id)
                              .Adapt(Adapters.Deadzone(inputSettings.JoystickDeadzone));
                }
                else if (id is ControllerId.XInput)
                {
                    var controllerId = id as ControllerId.XInput;
                    buttons = XInputButtons(controllerId.Id);
                    axes    = PolarizedXInputAxes(controllerId.Id);
                }
                else
                {
                    buttons = InputMap <InputSource, ButtonState> .Empty;
                    axes    = InputMap <InputSource, float> .Empty;
                }
                return(new ControllerPeripheral(buttons, axes));
            }
Exemple #31
0
        /// <summary>
        /// Returns a value indicating which parts of the item's bounds can be set</summary>
        /// <param name="item">Item</param>
        /// <returns>Value indicating which parts of the item's bounds can be set</returns>
        BoundsSpecified ILayoutContext.CanSetBounds(object item)
        {
            //if (item.Is<DomNode>())// debug disallowing dragging
            //{
            //    var parent = item.Cast<DomNode>().Parent;
            //    if (parent.Is<Group>())
            //        return BoundsSpecified.None;
            //}

            // by default a group can be moved and resized
            if (Adapters.Is <Group>(item))
            {
                return(BoundsSpecified.All);
            }

            if (Adapters.Is <Element>(item))
            {
                return(BoundsSpecified.Location);
            }

            if (Adapters.Is <Annotation>(item))
            {
                return(BoundsSpecified.All);
            }

            return(BoundsSpecified.None);
        }
Exemple #32
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddAuthentication(options =>
            {
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = Configuration["token:issuer"],
                    ValidAudience    = Configuration["token:audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["token:key"])),
                    ClockSkew        = TimeSpan.Zero // remove delay of token when expire
                };
            });

            services.AddAuthorization();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title       = "Zenit Payroll API V1",
                    Version     = "v1",
                    Description = "Zenit Payroll Web API written in ASP.NET Core Web API",
                    Contact     = new Contact {
                        Name = "Qinisela Molefe", Email = "*****@*****.**", Url = "https://www.codeassembly.co.za"
                    },
                });

                //// Set the comments path for the Swagger JSON and UI.
                //var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                //var xmlPath = Path.Combine(basePath, "dotnetcore-file-upload.xml");
                //c.IncludeXmlComments(xmlPath);
            });

            services.AddCors(options =>
            {
                options.AddPolicy("all_origins", policy => policy.WithOrigins("http://localhost:4300")
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials()
                                  );
            });

            services.AddDbContext <PayrollContext>(options => options.UseNpgsql(Configuration.GetConnectionString("Payroll_DB_Local")), ServiceLifetime.Transient);
            services.AddTransient <IUnitOfWork, UnitOfWork>();

            Adapters.Initialise(services);
            Builders.Initialise(services);
            BusinessRules.Initialise(services);
            Services.Initialise(services);

            services.AddScoped <LoginProvider>();
        }
 public override void Verify(Adapters.IContainerAdapter container)
 {
     if (Complex1.Instances != this.LoopCount
         || Complex2.Instances != this.LoopCount
         || Complex3.Instances != this.LoopCount)
     {
         throw new Exception(string.Format("Complex count must be {0}", this.LoopCount));
     }
 }
 public override void Verify(Adapters.IContainerAdapter container)
 {
     if (Transient1.Instances != this.LoopCount
         || Transient2.Instances != this.LoopCount
         || Transient3.Instances != this.LoopCount)
     {
         throw new Exception(string.Format("Transient count must be {0}", this.LoopCount));
     }
 }
        public override void Verify(Adapters.IContainerAdapter container)
        {
            if (!container.SupportsPropertyInjection)
            {
                return;
            }

            if (ComplexPropertyObject1.Instances != this.LoopCount
                || ComplexPropertyObject2.Instances != this.LoopCount
                || ComplexPropertyObject3.Instances != this.LoopCount)
            {
                throw new Exception(string.Format("ComplexPropertyObject count must be {0}", this.LoopCount));
            }
        }
        public override void Verify(Adapters.IContainerAdapter container)
        {
            if (!container.SupportsConditional)
            {
                return;
            }

            if (ImportConditionObject1.Instances != this.LoopCount
                || ImportConditionObject2.Instances != this.LoopCount
                || ImportConditionObject3.Instances != this.LoopCount)
            {
                throw new Exception(string.Format("ImportConditionObject count must be {0}", this.LoopCount));
            }
        }
        public override void Verify(Adapters.IContainerAdapter container)
        {
            if (!container.SupportsChildContainer)
            {
                return;
            }

            if (ScopedCombined1.Instances != this.LoopCount
                || ScopedCombined2.Instances != this.LoopCount
                || ScopedCombined3.Instances != this.LoopCount)
            {
                throw new Exception(string.Format("ScopedCombined count must be {0}", this.LoopCount));
            }
        }
        public override void Verify(Adapters.IContainerAdapter container)
        {
            if (!container.SupportsInterception)
            {
                return;
            }

            if (Calculator1.Instances != this.LoopCount
                || Calculator2.Instances != this.LoopCount
                || Calculator3.Instances != this.LoopCount)
            {
                throw new Exception(string.Format("Calculator count must be {0}", this.LoopCount));
            }
        }
        public override void Verify(Adapters.IContainerAdapter container)
        {
            if (!container.SupportGeneric)
            {
                return;
            }

            if (ImportGeneric<int>.Instances != this.LoopCount
                || ImportGeneric<float>.Instances != this.LoopCount
                || ImportGeneric<object>.Instances != this.LoopCount)
            {
                throw new Exception(string.Format("ImportGeneric count must be {0}", this.LoopCount));
            }
        }
        public override void Verify(Adapters.IContainerAdapter container)
        {
            if (!container.SupportsMultiple)
            {
                return;
            }

            if (ImportMultiple1.Instances != this.LoopCount
                || ImportMultiple2.Instances != this.LoopCount
                || ImportMultiple3.Instances != this.LoopCount)
            {
                throw new Exception(string.Format("ImportMultiple count must be {0}", this.LoopCount));
            }
        }
        public override void Verify(Adapters.IContainerAdapter container)
        {
            if (Combined1.Instances != this.LoopCount
                || Combined2.Instances != this.LoopCount
                || Combined3.Instances != this.LoopCount)
            {
                throw new Exception(string.Format("Combined count must be {0}", this.LoopCount));
            }

            if (Transient1.Instances != this.LoopCount
                || Transient2.Instances != this.LoopCount
                || Transient3.Instances != this.LoopCount)
            {
                throw new Exception(string.Format("Transient count must be {0}", this.LoopCount));
            }

            if (Singleton1.Instances > 1 || Singleton2.Instances > 1 || Singleton2.Instances > 1)
            {
                throw new Exception("Singleton instance count must be 1. Container: " + container.Name);
            }
        }
		protected override object DoOperation(Adapters.SchemaObjectOperationContext context)
		{
			SchemaObjectAdapter.Instance.Update(this._Object);

			return this._Object;
		}
		protected override object DoOperation(Adapters.SchemaObjectOperationContext context)
		{
			int replacedCount = 0;

			//取父级的权限定义
			var aclMembers = Adapters.SCAclAdapter.Instance.LoadByContainerID(((SchemaObjectBase)(this._Parent)).ID, DateTime.MinValue);

			InSqlClauseBuilder inBuilder = new InSqlClauseBuilder("ID");
			inBuilder.AppendItem((from acl in aclMembers select acl.MemberID).ToArray());

			WhereSqlClauseBuilder where = new WhereSqlClauseBuilder();
			where.AppendItem("Status", (int)SchemaObjectStatus.Normal);

			if (inBuilder.IsEmpty)
				where.AppendItem("1", "2");

			var memberObjects = Adapters.SchemaObjectAdapter.Instance.Load(new ConnectiveSqlClauseCollection(inBuilder, where), DateTime.MinValue);

			if (this._Candidates.Count > 0)
			{
				ProcessProgress.Current.MaxStep = this._Candidates.Count;
				ProcessProgress.Current.CurrentStep = 0;

				ProcessProgress.Current.Output.WriteLine("正在替换子对象ACL");

				foreach (SchemaObjectBase candidate in this._Candidates)
				{
					string objName = candidate.Properties.GetValue("Name", string.Empty);

					try
					{
						Debug.Assert(this._Parent != null, "容器对象为null");

						var oldItems = SCAclAdapter.Instance.LoadByContainerID(candidate.ID, DateTime.MinValue);

						var container = new SCAclContainer(candidate);

						foreach (var item in aclMembers)
							if (item.Status == SchemaObjectStatus.Normal)
								container.Members.Add(item.ContainerPermission, memberObjects[item.MemberID]);


						if (oldItems != null)
						{
							container.Members.MergeChangedItems(oldItems);
						}

						SCObjectOperations.Instance.UpdateObjectAcl(container);

						if (SCDataOperationLockContext.Current.Lock != null && (replacedCount) % 5 == 0)
							SCDataOperationLockContext.Current.ExtendLock();

						replacedCount++;

						ProcessProgress.Current.StatusText = string.Format("已替换\"{0}\"的Acl", objName);
						ProcessProgress.Current.Increment();
						ProcessProgress.Current.Response();
					}
					catch (System.Exception ex)
					{
						throw new ApplicationException(string.Format("替换对象{0}({1})的Acl出错: {2}", objName, candidate.ID, ex.Message));
					}
				}
			}
			else
			{
				ProcessProgress.Current.Output.WriteLine("当前对象没有子对象ACL");
				ProcessProgress.Current.CurrentStep = ProcessProgress.Current.MaxStep = 1;
			}

			ProcessProgress.Current.StatusText = string.Format("总共替换了{0:#,##0}个对象的Acl", replacedCount);
			ProcessProgress.Current.Response();

			return this._Parent;
		}
 public ContainerAdapterInfo(Adapters.IContainerAdapter container)
 {
     this.Name = container.Name;
     this.Url = container.Url;
     this.Version = container.Version;
 }