internal static void BuildMapping_EntitySet(SchemaMapping mapping, Schema conceptual, Schema storage)
        {
            mapping.EntityContainerMapping.EntitySetMappings.ForEach(x =>
            {
                // SET Entity Set
                var conceptualSet = conceptual.EntityContainer.Index_EntitySets_Name[x.Name];
                x.ConceptualSet = conceptualSet;

                x.EntityTypeMappings.ForEach(y =>
                {
                    if (y.MappingFragment != null)
                    {
                        var isGenericType = y.TypeName.StartsWith("IsTypeOf(");

                        var typeName = isGenericType ? y.TypeName.SubstringLastIndexOf(".").Replace(")", "") : y.TypeName.SubstringLastIndexOf(".");
                        var entityType = conceptual.Index_EntityTypes_Name[typeName];
                        y.EntityType = entityType;
                        entityType.EntityTypeMapping = y;

                        if (isGenericType)
                        {
                            entityType.GenericEntitySetMapping = y;
                        }

                        var storeEntitySet = storage.EntityContainer.Index_EntitySets_Name[y.MappingFragment.StoreEntitySetName];
                        y.MappingFragment.StoreEntitySet = storeEntitySet;
                    }
                });
            });
        }
Exemple #2
0
 public CRUDSubscriptionEvent(EventType type, Schema schema, Row row, DataTimeStamp version)
 {
     Type = type;
       Schema = schema;
       Row = row;
       Version = version;
 }
        public byte[] Encrypt(byte[] plainBytes, string password, Schema schemaVersion)
        {
            this.configureSettings (schemaVersion);

            PayloadComponents components = new PayloadComponents();
            components.schema = new byte[] {(byte)schemaVersion};
            components.options = new byte[] {(byte)this.options};
            components.salt = this.generateRandomBytes (Cryptor.saltLength);
            components.hmacSalt = this.generateRandomBytes (Cryptor.saltLength);
            components.iv = this.generateRandomBytes (Cryptor.ivLength);

            byte[] key = this.generateKey (components.salt, password);

            switch (this.aesMode) {
                case AesMode.CTR:
                    components.ciphertext = this.encryptAesCtrLittleEndianNoPadding(plainBytes, key, components.iv);
                    break;

                case AesMode.CBC:
                    components.ciphertext = this.encryptAesCbcPkcs7(plainBytes, key, components.iv);
                    break;
            }

            components.hmac = this.generateHmac(components, password);

            List<byte> binaryBytes = new List<byte>();
            binaryBytes.AddRange (this.assembleHeader(components));
            binaryBytes.AddRange (components.ciphertext);
            binaryBytes.AddRange (components.hmac);

            return binaryBytes.ToArray();
        }
Exemple #4
0
        public object Execute(Schema schema, string query, object root = null,
            Inputs inputs = null, string operationName = "")
        {
            var source = new Source(query ?? "", "GraphQL Request");

            return string.Empty;
        }
        public override void OnTradeAddItem(Schema.Item schemaItem, Inventory.Item inventoryItem)
        {
            // USELESS DEBUG MESSAGES -------------------------------------------------------------------------------
            SendTradeMessage("Object AppID: {0}", inventoryItem.AppId);
            SendTradeMessage("Object ContextId: {0}", inventoryItem.ContextId);

            switch (inventoryItem.AppId)
            {
                case 440:
                    SendTradeMessage("TF2 Item Added.");
                    SendTradeMessage("Name: {0}", schemaItem.Name);
                    SendTradeMessage("Quality: {0}", inventoryItem.Quality);
                    SendTradeMessage("Level: {0}", inventoryItem.Level);
                    SendTradeMessage("Craftable: {0}", (inventoryItem.IsNotCraftable ? "No" : "Yes"));
                    break;

                case 753:
                    GenericInventory.ItemDescription tmpDescription = OtherSteamInventory.getDescription(inventoryItem.Id);
                    SendTradeMessage("Steam Inventory Item Added.");
                    SendTradeMessage("Type: {0}", tmpDescription.type);
                    SendTradeMessage("Marketable: {0}", (tmpDescription.marketable ? "Yes" : "No"));
                    break;

                default:
                    SendTradeMessage("Unknown item");
                    break;
            }
            // ------------------------------------------------------------------------------------------------------
        }
		protected override IEnumerable<DbParameter> CoreGetColumnParameters(Type connectionType, string dataSourceTag, Server server, Database database, Schema schema, Table table)
		{
			if ((object)connectionType == null)
				throw new ArgumentNullException(nameof(connectionType));

			if ((object)dataSourceTag == null)
				throw new ArgumentNullException(nameof(dataSourceTag));

			if ((object)server == null)
				throw new ArgumentNullException(nameof(server));

			if ((object)database == null)
				throw new ArgumentNullException(nameof(database));

			if ((object)schema == null)
				throw new ArgumentNullException(nameof(schema));

			if ((object)table == null)
				throw new ArgumentNullException(nameof(table));

			if (dataSourceTag.SafeToString().ToLower() == ODBC_SQL_SERVER_DATA_SOURCE_TAG)
			{
				return new DbParameter[]
						{
							//DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.ReflectionFascadeLegacyInstance.CreateParameter(connectionType, null,ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P1", server.ServerName),
							//DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.ReflectionFascadeLegacyInstance.CreateParameter(connectionType, null,ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P2", database.DatabaseName),
							DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P3", schema.SchemaName),
							DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P4", table.TableName)
						};
			}

			throw new ArgumentOutOfRangeException(string.Format("dataSourceTag: '{0}'", dataSourceTag));
		}
Exemple #7
0
        static CategoriesQueryTests()
        {
            repository = new Repository("CategoriesQueryTests");

            categorySchema = new Schema(repository, "category");
            categorySchema.AddColumn(new Column() { Name = "title", DataType = DataType.String, Length = 256 });

            categoryFolder = new TextFolder(repository, "category") { SchemaName = categorySchema.Name };

            newsSchema = new Schema(repository, "news");
            newsSchema.AddColumn(new Column()
            {
                Name = "Title",
                DataType = DataType.String,
                Length = 256
            });
            newsSchema.AddColumn(new Column()
            {
                Name = "Comments",
                DataType = DataType.Int
            });

            newsFolder = new TextFolder(repository, "news") { SchemaName = newsSchema.Name, CategoryFolders = new[] { categoryFolder.Name } };

            ProviderFactory providerFactory = new ProviderFactory();
            Providers.DefaultProviderFactory = providerFactory;
            providerFactory.GetProvider<IRepositoryProvider>().Add(repository);
            providerFactory.GetProvider<ISchemaProvider>().Add(categorySchema);
            providerFactory.GetProvider<ISchemaProvider>().Add(newsSchema);
            providerFactory.GetProvider<ITextFolderProvider>().Add(newsFolder);
            providerFactory.GetProvider<ITextFolderProvider>().Add(categoryFolder);
            InitializeData();
        }
		/// <summary>
		/// Создать <see cref="DdeCustomTable"/>.
		/// </summary>
		/// <param name="schema">Схема бизнес-объекта.</param>
		public DdeCustomTable(Schema schema)
		{
			if (schema == null)
				throw new ArgumentNullException(nameof(schema));

			Init(schema, schema.Name);
		}
        public Schema ImportDbml(Stream stream)
        {
            if(stream == null) 
                throw new ArgumentNullException("stream");

            var typeToTableMapping = new Dictionary<string, ITableDefinition>();

            var document = new XmlDocument();
            document.Load(stream);

            var schema = new Schema();

            foreach(XmlNode tableNode in document.SelectNodes("dbml:Database/dbml:Table", namespaceManager))
            {
                var name = tableNode.Attributes["Name"].Value.Split('.');

                ISchemaDefinition schemaDefinition = schema.GetSchema(name[0]);// new SchemaDefinition(name[0]);
                var tableDefinition = new TableDefinition(name[1], schemaDefinition);

                schema.AddSchema(schemaDefinition);
                //schemaDefinition.

                //Console.WriteLine(tableNode.Name);
            } // foreach

            return schema;
        }
Exemple #10
0
        public void BuildUsingAdHockSchema()
        {
            var schema = new Schema("TEZT",
                           new Schema.FieldDef("ID", typeof(int), new List<FieldAttribute>{ new FieldAttribute(required: true, key: true)}),
                           new Schema.FieldDef("Description", typeof(string), new List<FieldAttribute>{ new FieldAttribute(required: true)})
            );

            var tbl = new Table(schema);

            for(var i=0; i<1000; i++)
            {
                 var row =  new DynamicRow(tbl.Schema);

                 row["ID"] = i;
                 row["Description"] = "Item-{0}".Args(i);

                 tbl.Insert( row );
            }

            Assert.AreEqual(1000, tbl.Count);

            var match = tbl.FindByKey(178);
            Assert.IsNotNull( match );
            Assert.AreEqual("Item-178", match["Description"]);
        }
        public SchemaTableDetail_HelperTable(Schema schema)
            : base(schema)
        {
            ID = StaticID;
            Name = "Конфигурация.Таблица.Деталь";

            SchemaTableColumn c;

            c = new SchemaTableColumn();
            c.Name = "ID";
            c.DataType = new GuidDataType() { Column = c };
            c.ColumnRoles.Add(RoleConst.Таблица_Ключ);
            c.IsNotNullable = true;
            c.Table = this;
            Columns.Add(c);

            c = new SchemaTableColumn();
            c.Name = "Имя";
            c.DataType = new StringDataType() { Column = c, MaxSize = 128 };
            c.IsNotNullable = false;
            c.Table = this;
            Columns.Add(c);

            c = new SchemaTableColumn();
            c.Name = "Таблица";
            c.DataType = new ForeingKeyDataType() { Column = c, RefTableID = SchemaTable_HelperTable.StaticID };
            c.IsNotNullable = false;
            c.Table = this;
            Columns.Add(c);
        }
Exemple #12
0
        static ParentQueryTests()
        {
            repository = new Repository("ParentQueryTests");

            commentSchema = new Schema(repository, "comments");
            commentSchema.AddColumn(new Column() { Name = "title", DataType = Kooboo.Data.DataType.String, Length = 256 });


            newsSchema = new Schema(repository, "news") { ChildSchemas = new[] { commentSchema.Name } };
            newsSchema.AddColumn(new Column()
            {
                Name = "Title",
                DataType = Kooboo.Data.DataType.String,
                Length = 256
            });
            newsSchema.AddColumn(new Column()
            {
                Name = "Comments",
                DataType = Kooboo.Data.DataType.Int
            });

            newsFolder = new TextFolder(repository, "news") { SchemaName = newsSchema.Name };

            ProviderFactory providerFactory = new ProviderFactory();
            Providers.DefaultProviderFactory = providerFactory;
            providerFactory.GetProvider<IRepositoryProvider>().Add(repository);
            providerFactory.GetProvider<ISchemaProvider>().Add(commentSchema);
            providerFactory.GetProvider<ISchemaProvider>().Add(newsSchema);
            providerFactory.GetProvider<ITextFolderProvider>().Add(newsFolder);
            InitializeData();
        }
Exemple #13
0
        public virtual TextContent Bind(Schema schema, TextContent textContent, System.Collections.Specialized.NameValueCollection values, bool update, bool thorwViolationException)
        {
            List<RuleViolation> violations = new List<RuleViolation>();
            schema = schema.AsActual();
            //do not to create a new content instance
            //it will interrupt the object state for ravendb.
            //textContent = new TextContent(textContent);

            foreach (Column column in ((ISchema)(schema.AsActual())).Columns.Where(it => !string.IsNullOrEmpty(it.ControlType)))
            {
                var value = values[column.Name];
                //IControl control = column.GetControlType();
                ////
                //if (control != null)
                //{
                //    value = control.GetValue(textContent[column.Name], value);
                //}
                // Update content will keep the old values;
                if (value == null && update == true)
                {
                    continue;
                }
                //postedData[column.Name] = value;

                ParseColumnValue(textContent, ref violations, column, value);

                ValidateColumn(schema, textContent, ref violations, column, update);
            }
            if (thorwViolationException && violations.Count > 0)
            {
                throw new RuleViolationException(textContent, violations);
            }
            return textContent;
        }
        public ExecutionContext BuildExecutionContext(
            Schema schema,
            object root,
            Document document,
            string operationName,
            Inputs inputs)
        {
            var context = new ExecutionContext();
            context.Schema = schema;
            context.RootObject = root;

            var operation = !string.IsNullOrWhiteSpace(operationName)
                ? document.Operations.WithName(operationName)
                : document.Operations.FirstOrDefault();

            if (operation == null)
            {
                context.Errors.Add(new ExecutionError("Unknown operation name: {0}".ToFormat(operationName)));
                return context;
            }

            context.Operation = operation;
            context.Variables = GetVariableValues(schema, operation.Variables, inputs);
            context.Fragments = document.Fragments;

            return context;
        }
Exemple #15
0
 public TextContentBinderTests()
 {
     schema = new Schema() { IsDummy = false };
     schema.AddColumn(new Column()
     {
         Name = "Title",
         DataType = DataType.String,
         ControlType = "TextBox",
         Validations = new ColumnValidation[] { new RequiredValidation() { ErrorMessage = "The field is requried" } }
     });
     schema.AddColumn(new Column()
         {
             Name = "Body",
             DataType = DataType.String,
             ControlType = "TextBox"
         });
     schema.AddColumn(new Column()
     {
         Name = "Comments",
         DataType = DataType.Int,
         ControlType = "TextBox"
     });
     schema.AddColumn(new Column()
     {
         Name = "PostDate",
         DataType = DataType.DateTime,
         ControlType = "TextBox"
     });
 }
        public virtual void GenerateLogicFromEntities()
        {
            CurrentSchema = Schema.Current;

            GetSolutionInfo(out SolutionFolder, out SolutionName);

            string projectFolder = GetProjectFolder();

            if (!Directory.Exists(projectFolder))
                throw new InvalidOperationException("{0} not found. Override GetProjectFolder".FormatWith(projectFolder));

            bool? overwriteFiles = null;

            foreach (var mod in GetModules())
            {
                string str = WriteFile(mod);

                string fileName = Path.Combine(projectFolder, GetFileName(mod));

                FileTools.CreateParentDirectory(fileName);

                if (!File.Exists(fileName) || SafeConsole.Ask(ref overwriteFiles, "Overwrite {0}?".FormatWith(fileName)))
                {
                    File.WriteAllText(fileName, str);
                }
            }
        }
        public DocumentValidatorTests()
        {
            var testSchema = new Schema()
            {
                new Property { Name = "wrongType", Type = typeof(string) },
                new Property
                {
                    Name = "required",
                    Type = typeof(string),
                    Options = new ValidationOptions(required: true)
                },
                new Property
                {
                    Name = "unique",
                    Type = typeof(string),
                    Options = new ValidationOptions(unique: true)
                },
                new Property
                {
                    Name = "pattern",
                    Type = typeof(string),
                    Options = new ValidationOptions(pattern: "test")
                },
                new Property
                {
                    Name = "patternNotString",
                    Type = typeof(int),
                    Options = new ValidationOptions(pattern: "test")
                }
            };
            var mongoDatabaseMock = new Mocks.MongoDatabase("DATABASENAME");
            var collection = new Collection("COLLECTIONNAME", mongoDatabaseMock);

            DocumentValidator = new DocumentValidator(testSchema, collection);
        }
        /// <summary>
        /// Adds the saved configuration from document to the map.
        /// </summary>
        /// <param name="document">The document storing the saved configuration.</param>
        public void AddSavedConfigurations(Document document)
        {
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }

            if (m_schema != null)
            {
                foreach (DataStorage storedSetup in GetSavedConfigurations(document))
                {
                    Entity configEntity = storedSetup.GetEntity(m_schema);
                    IFCExportConfiguration configuration = IFCExportConfiguration.CreateDefaultConfiguration();
                    configuration.Name = configEntity.Get<String>(s_setupName);
                    //configuration.Description = configEntity.Get<String>(s_setupDescription);
                    configuration.IFCVersion = (IFCVersion)configEntity.Get<int>(s_setupVersion);
                    configuration.IFCFileType = (IFCFileFormat)configEntity.Get<int>(s_setupFileFormat);
                    configuration.SpaceBoundaries = configEntity.Get<int>(s_setupSpaceBoundaries);
                    configuration.ExportBaseQuantities = configEntity.Get<bool>(s_setupQTO);
                    configuration.SplitWallsAndColumns = configEntity.Get<bool>(s_splitWallsAndColumns);
                    configuration.Export2DElements = configEntity.Get<bool>(s_setupExport2D);
                    configuration.ExportInternalRevitPropertySets = configEntity.Get<bool>(s_setupExportRevitProps);
                    configuration.Use2DRoomBoundaryForVolume = configEntity.Get<bool>(s_setupUse2DForRoomVolume);
                    configuration.UseFamilyAndTypeNameForReference = configEntity.Get<bool>(s_setupUseFamilyAndTypeName);
                    configuration.ExportPartsAsBuildingElements = configEntity.Get<bool>(s_setupExportPartsAsBuildingElements);

                    Add(configuration);
                } 
            }   
        }
Exemple #19
0
        public void AbstractRecursive()
        {
            var xsd = XsdFactory.xmlSchemaSetFromUri("Formula.xsd");

            var els = xsd.GlobalElements.Values.OfType<XmlSchemaElement>();
            var form = els.Single(x => x.Name == "Formula");
            var and = els.Single(x => x.Name == "And");
            var seq = (XmlSchemaSequence)((XmlSchemaComplexType)and.ElementSchemaType).ContentTypeParticle;
            var formRef = (XmlSchemaElement)seq.Items[0];
            Assert.IsTrue(form.IsAbstract);
            Assert.IsTrue(form.RefName.IsEmpty);
            Assert.IsFalse(form.QualifiedName.IsEmpty);

            Assert.IsFalse(formRef.IsAbstract); // Notice this
            Assert.AreEqual(form.QualifiedName, formRef.QualifiedName);
            Assert.AreEqual(formRef.QualifiedName, formRef.RefName);

            Assert.AreSame(form.ElementSchemaType, formRef.ElementSchemaType);

            var schema = new Schema(xsd);

            var gen = schema.Arbitrary(new XmlQualifiedName("Formula")).Generator;
            var samples = gen.Sample(5, 500);

            samples.ToList().ForEach(Console.WriteLine);
            var allvalid = samples.All(x => schema.Validate(x).IsSuccess);
            Assert.IsTrue(allvalid);
        }
Exemple #20
0
        static SimpleQueryTests()
        {
            repository = new Repository("SimpleQueryTests");
            schema = new Schema(repository, "news");
            schema.AddColumn(new Column()
            {
                Name = "Title",
                DataType = DataType.String,
                Length = 256
            });
            schema.AddColumn(new Column()
            {
                Name = "Comments",
                DataType = DataType.Int
            });

            folder = new TextFolder(repository, "news");
            folder.SchemaName = schema.Name;

            ProviderFactory providerFactory = new ProviderFactory();
            Providers.DefaultProviderFactory = providerFactory;
            providerFactory.GetProvider<IRepositoryProvider>().Add(repository);
            providerFactory.GetProvider<ISchemaProvider>().Add(schema);
            providerFactory.GetProvider<ITextFolderProvider>().Add(folder);

            InitializeData();
        }
Exemple #21
0
        public int ResetSchema(Repository repository, Schema[] schemas)
        {
            var root = SchemaPath.GetBaseDir(repository);
            var paths = schemas.Select(it => Path.Combine(root, it.Name));

            return ResetSchema(repository, schemas, paths);
        }
Exemple #22
0
        public void TestAdd()
        {
            Schema schema = new Schema(repository, "news") { IsDummy = false };

            schema.AddColumn(new Column()
            {
                Name = "Title",
                DataType = DataType.String,
                Length = 100
            });

            //add
            SchemaManager.Add(schema);

            Schema newSchema = new Schema(repository, "news") { IsDummy = false };

            newSchema.AddColumn(new Column()
            {
                Name = "Title",
                DataType = DataType.String,
                Length = 100
            });

            newSchema.AddColumn(new Column()
            {
                Name = "Body",
                DataType = DataType.String,
                Length = 256
            });
            newSchema.AddColumn(new Column()
            {
                Name = "Comments",
                DataType = DataType.Int
            });
            //add column
            SchemaManager.Update(newSchema, schema);

            //remove column
            Schema lastSchema = new Schema(repository, "news") { IsDummy = false };

            lastSchema.AddColumn(new Column()
            {
                Name = "Title",
                DataType = DataType.String,
                Length = 100
            });

            lastSchema.AddColumn(new Column()
            {
                Name = "Body",
                DataType = DataType.String,
                Length = 256
            });

            //add column
            SchemaManager.Update(lastSchema, newSchema);

            SchemaManager.Delete(lastSchema);

        }
        public override bool ShouldBuy(Inventory.Item inventoryItem, Schema.Item schemaItem, out string reason)
        {
            int count = getNumItems(inventoryItem.Defindex, inventoryItem.Quality);

            foreach (ulong id in Trade.OtherOfferedItems)
            {
                Inventory.Item otherItem = Trade.OtherInventory.GetItem(id);
                if (otherItem.Defindex == inventoryItem.Defindex)
                {
                    count++;
                }
            }
            if (count >= 4)
            {
                reason = "I have too many of that item.";
                return false;
            }
            if (IsGifted(inventoryItem))
            {
                reason = "Item is gifted.";
                return false;
            }
            if (inventoryItem.Quality != "3")
            {
                reason = "Item is not vintage.";
                return false;
            }
            reason = null;
            return true;
        }
        internal void SetReferences(Schema schema, BizTalkArtifacts artifacts, Microsoft.BizTalk.ExplorerOM.Schema omSchema)
        {
            schema.Application = artifacts.Applications[omSchema.Application.Id()];
            schema.ParentAssembly = artifacts.Assemblies[omSchema.BtsAssembly.Id()];

            if (_schema == null || _schema.Name == null || !_schema.Name.Equals(schema.Name, StringComparison.Ordinal))
            {
                var source = new XmlDocument();
                source.LoadXml(omSchema.GetXmlContent());

                var mgr = new XmlNamespaceManager(source.NameTable);
                mgr.AddNamespace("b", "http://schemas.microsoft.com/BizTalk/2003");
                mgr.AddNamespace("x", "http://www.w3.org/2001/XMLSchema");

                SetSchemaType(schema, source, mgr);
                SetSchemaImports(schema, source, mgr, artifacts);

                if (omSchema.Properties != null)
                {
                    foreach (DictionaryEntry property in omSchema.Properties)
                    {
                        schema.Properties.Add(new KeyValuePair<string, string>(property.Key.ToString(),
                                                                               property.Value.ToString()));
                    }
                }

                _schema = schema;
            }
            else
            {
                schema.Properties = _schema.Properties;
                schema.SchemaType = _schema.SchemaType;
                schema.ReferencedSchemas = _schema.ReferencedSchemas;
            }
        }
        protected override IEnumerable<IDataParameter> CoreGetColumnParameters(IUnitOfWorkContext unitOfWorkContext, string dataSourceTag, Database database, Schema schema, Table table)
        {
            if ((object)unitOfWorkContext == null)
                throw new ArgumentNullException("unitOfWorkContext");

            if ((object)dataSourceTag == null)
                throw new ArgumentNullException("dataSourceTag");

            if ((object)database == null)
                throw new ArgumentNullException("database");

            if ((object)schema == null)
                throw new ArgumentNullException("schema");

            if ((object)table == null)
                throw new ArgumentNullException("table");

            if (dataSourceTag.SafeToString().ToLower() == "net.sqlserver" ||
                dataSourceTag.SafeToString().ToLower() == "net.sqlce")
            {
                return new IDataParameter[]
                       {
                           unitOfWorkContext.CreateParameter(ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@SchemaName", schema.SchemaName),
                           unitOfWorkContext.CreateParameter(ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@TableOrViewName", table.TableName)
                       };
            }

            throw new ArgumentOutOfRangeException(string.Format("dataSourceTag: '{0}'", dataSourceTag));
        }
        public async Task<ExecutionResult> ExecuteAsync(Schema schema, object root, string query, string operationName, Inputs inputs = null)
        {
            var document = _documentBuilder.Build(query);
            var result = new ExecutionResult();

            var validationResult = _documentValidator.IsValid(schema, document, operationName);

            if (validationResult.IsValid)
            {
                var context = BuildExecutionContext(schema, root, document, operationName, inputs);

                if (context.Errors.Any())
                {
                    result.Errors = context.Errors;
                    return result;
                }

                result.Data = await ExecuteOperation(context);
                result.Errors = context.Errors;
            }
            else
            {
                result.Data = null;
                result.Errors = validationResult.Errors;
            }

            return result;
        }
        public override Price OtherValue(Inventory.Item inventoryItem, Schema.Item schemaItem)
        {
            Price value = Pricelist.Get(inventoryItem.Defindex, inventoryItem.Quality, false);
            //int highValue = ToScrap(Pricelist.getHighPrice(inventoryItem.Defindex, inventoryItem.Quality));

            if (value <= Pricelist.Scrap * 3)
                return value - Pricelist.Scrap * 1;
            if (value <= Pricelist.Scrap * 6)
                return value - Pricelist.Scrap * 2;
            if (value <= Pricelist.Refined * 2)
                return value - Pricelist.Scrap * 3;
            if (value <= Pricelist.Refined * 2.33)
                return Pricelist.Refined * 1.66;
            if (value <= Pricelist.Refined * 3.66)
                return value - Pricelist.Scrap * 6;
            if (value <= Pricelist.Refined * 4)
                return Pricelist.Refined * 3;
            if (value <= Pricelist.Refined * 5.33)
                return value - Pricelist.Refined * 1;
            if (value <= Pricelist.Refined * 5.66)
                return Pricelist.Refined * 4.33;
            if (value <= Pricelist.Refined * 6.33)
                return value - Pricelist.Refined * 1.33;
            else
                return Pricelist.Refined * 5;
        }
        /// <summary>
        /// Gets the raw string (xml) from the broker db by URL
        /// </summary>
        /// <param name="Url">URL of the page</param>
        /// <returns>String with page xml or empty string if no page was found</returns>
        public string GetContentByUrl(string Url)
        {
            Page page = new Page();
            page.Title = Randomizer.AnyString(15);
            page.Id = Randomizer.AnyUri(64);
            page.Filename = Randomizer.AnySafeString(8) + ".html";

            PageTemplate pt = new PageTemplate();
            pt.Title = Randomizer.AnyString(20);
            Field ptfieldView = new Field();
            ptfieldView.Name = "view";
            ptfieldView.Values.Add("Standard");
            pt.MetadataFields = new FieldSet();
            pt.MetadataFields.Add(ptfieldView.Name, ptfieldView);

            page.PageTemplate = pt;

            Schema schema = new Schema();
            schema.Title = Randomizer.AnyString(10);

            Component component = new Component();
            component.Title = Randomizer.AnyString(30);
            component.Id = Randomizer.AnyUri(16);
            component.Schema = schema;

            Field field1 = Randomizer.AnyTextField(6, 120, true);
            Field field2 = Randomizer.AnyTextField(8, 40, false);

            FieldSet fieldSet = new FieldSet();
            fieldSet.Add(field1.Name, field1);
            fieldSet.Add(field2.Name, field2);
            component.Fields = fieldSet;

            ComponentTemplate ct = new ComponentTemplate();
            ct.Title = Randomizer.AnyString(20);
            Field fieldView = new Field();
            fieldView.Name = "view";
            fieldView.Values.Add("DefaultComponentView");
            ct.MetadataFields = new FieldSet();
            ct.MetadataFields.Add(fieldView.Name, fieldView);

            ComponentPresentation cp = new ComponentPresentation();
            cp.Component = component;
            cp.ComponentTemplate = ct;

            page.ComponentPresentations = new List<ComponentPresentation>();
            page.ComponentPresentations.Add(cp);

            FieldSet metadataFields = new FieldSet();
            page.MetadataFields = metadataFields;

            var serializer = new XmlSerializer(typeof(Page));
            StringBuilder builder = new StringBuilder();
            StringWriter writer = new StringWriter(builder);
            //XmlTextWriter writer = new XmlTextWriter(page.Filename, Encoding.UTF8);
            //serializer.Serialize(writer, page);
            serializer.Serialize(writer, page);
            string pageAsString = builder.ToString();
            return pageAsString;
        }
Exemple #29
0
        public virtual ActionResult Create(Schema schema, bool? finish)
        {
            JsonResultEntry resultEntry = new JsonResultEntry(ModelState);
            try
            {
                if (ModelState.IsValid)
                {
                    Manager.Add(Repository, schema);

                    this.ResetAllForm(schema.Name);

                    if (finish.Value == true)
                    {
                        resultEntry.RedirectUrl = this.Url.Action("Index", Request.RequestContext.AllRouteValues().Merge("schemaName", schema.Name));
                    }
                    else
                    {
                        resultEntry.RedirectUrl = this.Url.Action("Templates", Request.RequestContext.AllRouteValues().Merge("schemaName", schema.Name));
                    }
                }

            }
            catch (Exception e)
            {
                resultEntry.AddException(e);
            }
            return Json(resultEntry);
        }
        /// <summary>
        /// Gets schema from reader taking Query.ResultRowType in consideration
        /// </summary>
        public static Schema GetSchemaForQuery(string target, Query query, MySqlDataReader reader, QuerySource qSource, out Schema.FieldDef[] toLoad)
        {
            Schema schema;
              var rtp = query.ResultRowType;

              if (rtp != null && typeof(TypedRow).IsAssignableFrom(rtp))
                schema = Schema.GetForTypedRow(query.ResultRowType);
              else
                schema = GetSchemaFromReader(query.Name, qSource, reader);

              //determine what fields to load
              toLoad = new Schema.FieldDef[reader.FieldCount];
              for (int i = 0; i < reader.FieldCount; i++)
              {
                var name = reader.GetName(i);
                var fdef = schema[name];

              //todo A gde GetBackendNameFor target?
                if (fdef==null) continue;
                var attr =  fdef[target];
                if (attr!=null)
                {
                  if (attr.StoreFlag!=StoreFlag.LoadAndStore && attr.StoreFlag!=StoreFlag.OnlyLoad) continue;
                }
                toLoad[i] = fdef;
              }

              return schema;
        }
 protected override BinaryPredictionTransformer <IPredictorWithFeatureWeights <float> > MakeTransformer(IPredictorWithFeatureWeights <float> model, Schema trainSchema)
 => new BinaryPredictionTransformer <IPredictorWithFeatureWeights <float> >(Host, model, trainSchema, FeatureColumn.Name);
Exemple #32
0
 /// <summary>
 /// Constructs a generic reader for the given schemas using the DefaultReader. If the
 /// reader's and writer's schemas are different this class performs the resolution.
 /// </summary>
 /// <param name="writerSchema">The schema used while generating the data</param>
 /// <param name="readerSchema">The schema desired by the reader</param>
 public GenericReader(Schema writerSchema, Schema readerSchema)
     : this(new DefaultReader(writerSchema, readerSchema))
 {
 }
Exemple #33
0
        /// <summary>
        /// Deserializes a enum. Uses CreateEnum to construct the new enum object.
        /// </summary>
        /// <param name="reuse">If appropirate, uses this instead of creating a new enum object.</param>
        /// <param name="writerSchema">The schema the writer used while writing the enum</param>
        /// <param name="readerSchema">The schema the reader is using</param>
        /// <param name="d">The decoder for deserialization.</param>
        /// <returns>An enum object.</returns>
        protected virtual object ReadEnum(object reuse, EnumSchema writerSchema, Schema readerSchema, Decoder d)
        {
            EnumSchema es = readerSchema as EnumSchema;

            return(CreateEnum(reuse, readerSchema as EnumSchema, writerSchema[d.ReadEnum()]));
        }
Exemple #34
0
 /// <summary>
 /// A generic function to read primitive types
 /// </summary>
 /// <typeparam name="S">The .NET type to read</typeparam>
 /// <param name="tag">The Avro type tag for the object on the stream</param>
 /// <param name="readerSchema">A schema compatible to the Avro type</param>
 /// <param name="reader">A function that can read the avro type from the stream</param>
 /// <returns>The primitive type just read</returns>
 protected S Read <S>(Schema.Type tag, Schema readerSchema, Reader <S> reader)
 {
     return(reader());
 }
Exemple #35
0
 /// <summary>
 /// Deserializes a null from the stream.
 /// </summary>
 /// <param name="readerSchema">Reader's schema, which should be a NullSchema</param>
 /// <param name="d">The decoder for deserialization</param>
 /// <returns></returns>
 protected virtual object ReadNull(Schema readerSchema, Decoder d)
 {
     d.ReadNull();
     return(null);
 }
Exemple #36
0
        public object Read(object reuse, Schema writerSchema, Schema readerSchema, Decoder d)
        {
            if (readerSchema.Tag == Schema.Type.Union && writerSchema.Tag != Schema.Type.Union)
            {
                readerSchema = findBranch(readerSchema as UnionSchema, writerSchema);
            }

            /*
             * if (!readerSchema.CanRead(writerSchema))
             * {
             *  throw new AvroException("Schema mismatch. Reader: " + readerSchema + ", writer: " + writerSchema);
             * }
             */
            switch (writerSchema.Tag)
            {
            case Schema.Type.Null:
                return(ReadNull(readerSchema, d));

            case Schema.Type.Boolean:
                return(Read <bool>(writerSchema.Tag, readerSchema, d.ReadBoolean));

            case Schema.Type.Int:
            {
                int i = Read <int>(writerSchema.Tag, readerSchema, d.ReadInt);
                switch (readerSchema.Tag)
                {
                case Schema.Type.Long:
                    return((long)i);

                case Schema.Type.Float:
                    return((float)i);

                case Schema.Type.Double:
                    return((double)i);

                default:
                    return(i);
                }
            }

            case Schema.Type.Long:
            {
                long l = Read <long>(writerSchema.Tag, readerSchema, d.ReadLong);
                switch (readerSchema.Tag)
                {
                case Schema.Type.Float:
                    return((float)l);

                case Schema.Type.Double:
                    return((double)l);

                default:
                    return(l);
                }
            }

            case Schema.Type.Float:
            {
                float f = Read <float>(writerSchema.Tag, readerSchema, d.ReadFloat);
                switch (readerSchema.Tag)
                {
                case Schema.Type.Double:
                    return((double)f);

                default:
                    return(f);
                }
            }

            case Schema.Type.Double:
                return(Read <double>(writerSchema.Tag, readerSchema, d.ReadDouble));

            case Schema.Type.String:
                return(Read <string>(writerSchema.Tag, readerSchema, d.ReadString));

            case Schema.Type.Bytes:
                return(Read <byte[]>(writerSchema.Tag, readerSchema, d.ReadBytes));

            case Schema.Type.Error:
            case Schema.Type.Record:
                return(ReadRecord(reuse, (RecordSchema)writerSchema, readerSchema, d));

            case Schema.Type.Enumeration:
                return(ReadEnum(reuse, (EnumSchema)writerSchema, readerSchema, d));

            case Schema.Type.Fixed:
                return(ReadFixed(reuse, (FixedSchema)writerSchema, readerSchema, d));

            case Schema.Type.Array:
                return(ReadArray(reuse, (ArraySchema)writerSchema, readerSchema, d));

            case Schema.Type.Map:
                return(ReadMap(reuse, (MapSchema)writerSchema, readerSchema, d));

            case Schema.Type.Union:
                return(ReadUnion(reuse, (UnionSchema)writerSchema, readerSchema, d));

            default:
                throw new AvroException("Unknown schema type: " + writerSchema);
            }
        }
Exemple #37
0
 /// <summary>
 /// Constructs the default reader for the given schemas using the DefaultReader. If the
 /// reader's and writer's schemas are different this class performs the resolution.
 /// This default implemenation maps Avro types to .NET types as follows:
 /// </summary>
 /// <param name="writerSchema">The schema used while generating the data</param>
 /// <param name="readerSchema">The schema desired by the reader</param>
 public DefaultReader(Schema writerSchema, Schema readerSchema)
 {
     this.ReaderSchema = readerSchema;
     this.WriterSchema = writerSchema;
 }
Exemple #38
0
        public async Task ExecuteStitchedQueryBuilderWithLocalSchema()
        {
            // arrange
            IHttpClientFactory clientFactory = CreateRemoteSchemas();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(clientFactory);
            serviceCollection.AddStitchedSchema(builder =>
                                                builder.AddSchemaFromHttp("contract")
                                                .AddSchemaFromHttp("customer")
                                                .AddSchema("hello",
                                                           Schema.Create(
                                                               "type Query { hello: String! }",
                                                               c => c.BindResolver(ctx => "Hello World")
                                                               .To("Query", "hello")))
                                                .RenameField("customer",
                                                             new FieldReference("Customer", "name"), "foo")
                                                .RenameType("SomeOtherContract", "Other")
                                                .RenameType("LifeInsuranceContract", "Life")
                                                .AddExtensionsFromString(
                                                    FileResource.Open("StitchingExtensions.graphql"))
                                                .AddSchemaConfiguration(c =>
                                                                        c.RegisterType <PaginationAmountType>()));

            IServiceProvider services =
                serviceCollection.BuildServiceProvider();

            IQueryExecutor executor = services
                                      .GetRequiredService <IQueryExecutor>();
            IExecutionResult result = null;

            // act
            using (IServiceScope scope = services.CreateScope())
            {
                var request = new QueryRequest(@"
                query a($id: ID!) {
                    a: customer2(customerId: $id) {
                        bar: foo
                        contracts {
                            id
                            ... life
                            ... on Other {
                                expiryDate
                            }
                        }
                    }
                    hello
                }

                fragment life on Life
                {
                    premium
                }

                ");
                request.VariableValues = new Dictionary <string, object>
                {
                    { "id", "Q3VzdG9tZXIteDE=" }
                };
                request.Services = scope.ServiceProvider;

                result = await executor.ExecuteAsync(request);
            }

            // assert
            Snapshot.Match(result);
        }
Exemple #39
0
 protected override RegressionPredictionTransformer <FastTreeRegressionModelParameters> MakeTransformer(FastTreeRegressionModelParameters model, Schema trainSchema)
 => new RegressionPredictionTransformer <FastTreeRegressionModelParameters>(Host, model, trainSchema, FeatureColumn.Name);
Exemple #40
0
            private static int[] BuildOutputToInputMap(IEnumerable <string> selectedColumns,
                                                       bool keepColumns,
                                                       bool keepHidden,
                                                       Schema inputSchema)
            {
                var outputToInputMapping = new List <int>();
                var columnCount          = inputSchema.Count;

                if (keepColumns)
                {
                    // With KeepColumns, the order that is specified is preserved in the mapping.
                    // For example if a given input has the columns of ABC and the select columns are
                    // specified as CA, then the output will be CA.

                    // In order to account for keeping hidden columns, build a dictionary of
                    // column name-> list of column indices. This dictionary is used for
                    // building the final mapping.
                    var columnDict = new Dictionary <string, List <int> >();
                    for (int colIdx = 0; colIdx < inputSchema.Count; ++colIdx)
                    {
                        if (!keepHidden && inputSchema[colIdx].IsHidden)
                        {
                            continue;
                        }

                        var columnName = inputSchema[colIdx].Name;
                        if (columnDict.TryGetValue(columnName, out List <int> columnList))
                        {
                            columnList.Add(colIdx);
                        }
                        else
                        {
                            columnList = new List <int>();
                            columnList.Add(colIdx);
                            columnDict.Add(columnName, columnList);
                        }
                    }

                    // Since the ordering matters, iterate through the selected columns
                    // finding the associated index that should be used.
                    foreach (var columnName in selectedColumns)
                    {
                        if (columnDict.TryGetValue(columnName, out List <int> columnList))
                        {
                            foreach (var colIdx in columnList)
                            {
                                outputToInputMapping.Add(colIdx);
                            }
                        }
                    }
                }
                else
                {
                    // Handles the drop case, removing any columns specified from the input
                    // In the case of drop, the order of the output is modeled after the input
                    // given an input of ABC and dropping column B will result in AC.
                    // In drop mode, we drop all columns with the specified names and keep all the rest,
                    // ignoring the keepHidden argument.
                    for (int colIdx = 0; colIdx < inputSchema.Count; colIdx++)
                    {
                        if (selectedColumns.Contains(inputSchema[colIdx].Name))
                        {
                            continue;
                        }

                        outputToInputMapping.Add(colIdx);
                    }
                }

                return(outputToInputMapping.ToArray());
            }
        /// <summary>
        /// ENUM 값에 드롭박스 적용
        /// </summary>
        private void ApplyDropboxOnEnumCells(Excel.Worksheet worksheet, Schema schema, object[,] tableDatas)
        {
            int rowCount = tableDatas.GetLength(0);
            int colCount = tableDatas.GetLength(1);

            if (rowCount <= 1 || colCount == 0)
            {
                return;
            }

            int startRowIdx = MarginRowCount + 1 /* FieldName */;

            bool hasRef = schema.Fields.Any(prop => !string.IsNullOrEmpty(prop.RefTableName) || prop.Type == FieldType.Bool);

            if (!hasRef)
            {
                return;
            }

            Field[]     fields     = schema.Fields.ToArray();
            Excel.Range sheetCells = worksheet.Cells;

            Excel.Worksheet enumSheet = GetWorksheet(RefTableSheetName);
            if (enumSheet == null)
            {
                enumSheet = AddWorksheet(RefTableSheetName);
            }
            else
            {
                enumSheet.Cells.Clear();
            }

            Dictionary <string, string> enumRangeAddrs = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            if (fields.Any(field => field.Type == FieldType.Bool))
            {
                Excel.Range startCell = (Excel.Range)enumSheet.Cells[1, 1];
                Excel.Range endCell   = (Excel.Range)enumSheet.Cells[3, 1];
                Excel.Range enumRange = enumSheet.Range[startCell, endCell];

                object[,] boolTable = new object[3, 1]
                {
                    { BooleanTableName },
                    { "TRUE" },
                    { "FALSE" }
                };

                enumRange.Cells.Value2 = boolTable;
                enumRange = enumSheet.Range[startCell.Offset[1], endCell];

                enumRangeAddrs.Add(BooleanTableName, $"={enumSheet.Name}!{enumRange.Address}");
            }

            for (int fieldIdx = 0; fieldIdx < fields.Length; ++fieldIdx)
            {// 이 테이블에 사용되는 Enum 셀을 생성 후 주소를 기억
                Field field = fields[fieldIdx];
                if (string.IsNullOrEmpty(field.RefTableName))
                {// 참조 프로퍼티가 Flat화 되면서 String으로 되기에 일단 이렇게 했음. 추후에 방식 수정 필요
                    continue;
                }

                string refTablePropName = $"{field.RefTableName}({field.RefFieldName})";

                if (enumRangeAddrs.ContainsKey(refTablePropName))
                {
                    continue;
                }

                if (!linker.HasTable(field.RefTableName))
                {
                    continue;
                }

                Table refTable = linker.GetTable(field.RefTableName);

                int refPropIndex = refTable.Schema.GetFieldIndex(field.RefFieldName);
                if (refPropIndex == -1)
                {
                    continue;
                }

                if (refTable.RowCount == 0)
                {
                    continue;
                }

                object[,] enumValueNames = new object[refTable.RowCount + 1, 1];
                enumValueNames[0, 0]     = refTablePropName;

                for (int rowIdx = 0; rowIdx != refTable.RowCount; ++rowIdx)
                {
                    enumValueNames[rowIdx + 1, 0] = refTable[rowIdx][refPropIndex];
                }

                int enumRangeColumnIdx = 1 + enumRangeAddrs.Count;

                Excel.Range startCell = enumSheet.Cells[1, enumRangeColumnIdx] as Excel.Range;
                Excel.Range endCell   = enumSheet.Cells[1 + refTable.RowCount, enumRangeColumnIdx] as Excel.Range;
                Excel.Range enumRange = enumSheet.Range[startCell, endCell];

                enumRange.Value2 = enumValueNames;

                enumRange = enumSheet.Range[startCell.Offset[1], endCell];

                enumRangeAddrs.Add(refTablePropName, $"={enumSheet.Name}!{enumRange.Address}");
            }

            // 테이블 레코드에 필터로 넣음
            for (int fieldIdx = 0; fieldIdx < fields.Length; ++fieldIdx)
            {
                Field field = fields[fieldIdx];

                string refTableFieldName;

                if (!string.IsNullOrEmpty(field.RefTableName))
                {// 참조 프로퍼티가 Flat화 되면서 String으로 되기에 일단 이렇게 했음. 추후에 방식 수정 필요
                    refTableFieldName = $"{field.RefTableName}({field.RefFieldName})";
                }
                else if (field.Type == FieldType.Bool)
                {
                    refTableFieldName = BooleanTableName;
                }
                else
                {
                    refTableFieldName = string.Empty;
                }

                if (!enumRangeAddrs.TryGetValue(refTableFieldName, out string enumRangeAddr))
                {
                    continue;
                }

                Excel.Range startCell = (Excel.Range)sheetCells.Cells[startRowIdx + 1 /* 첫 데이터 행 위치 */, MarginColumnCount + 1 + fieldIdx];
                Excel.Range endCell   = (Excel.Range)sheetCells.Cells[startRowIdx + rowCount - 1, MarginColumnCount + 1 + fieldIdx];
                Excel.Range range     = sheetCells.Range[startCell, endCell];

                Excel.Validation valid = range.Validation;
                if (valid != null)
                {
                    valid.Delete();
                }

                valid.Add(
                    Excel.XlDVType.xlValidateList,
                    Excel.XlDVAlertStyle.xlValidAlertWarning,
                    Excel.XlFormatConditionOperator.xlBetween,
                    enumRangeAddr,
                    Type.Missing);
                valid.InCellDropdown = true;
            }
        }
            private BoundColumn MakeColumn(Schema inputSchema, int iinfo)
            {
                Contracts.AssertValue(inputSchema);
                Contracts.Assert(0 <= iinfo && iinfo < _parent._columns.Length);

                ColumnType itemType = null;

                int[] sources = new int[_parent._columns[iinfo].Inputs.Count];
                // Go through the columns, and establish the following:
                // - indices of input columns in the input schema. Throw if they are not there.
                // - output type. Throw if the types of inputs are not the same.
                // - how many slots are there in the output vector (or variable). Denoted by totalSize.
                // - total size of CategoricalSlotRanges metadata, if present. Denoted by catCount.
                // - whether the column is normalized.
                //      It is true when ALL inputs are normalized (and of numeric type).
                // - whether the column has slot names.
                //      It is true if ANY input is a scalar, or has slot names.
                // - whether the column has categorical slot ranges.
                //      It is true if ANY input has this metadata.
                int  totalSize       = 0;
                int  catCount        = 0;
                bool isNormalized    = true;
                bool hasSlotNames    = false;
                bool hasCategoricals = false;

                for (int i = 0; i < _parent._columns[iinfo].Inputs.Count; i++)
                {
                    var(srcName, srcAlias) = _parent._columns[iinfo].Inputs[i];
                    if (!inputSchema.TryGetColumnIndex(srcName, out int srcCol))
                    {
                        throw _host.ExceptSchemaMismatch(nameof(inputSchema), "input", srcName);
                    }
                    sources[i] = srcCol;

                    var curType = inputSchema.GetColumnType(srcCol);
                    if (itemType == null)
                    {
                        itemType  = curType.ItemType;
                        totalSize = curType.ValueCount;
                    }
                    else if (curType.ItemType.Equals(itemType))
                    {
                        // If any one input is variable length, then the output is variable length.
                        if (totalSize == 0 || curType.ValueCount == 0)
                        {
                            totalSize = 0;
                        }
                        else
                        {
                            totalSize += curType.ValueCount;
                        }
                    }
                    else
                    {
                        throw _host.ExceptSchemaMismatch(nameof(inputSchema), "input", srcName, itemType.ToString(), curType.ToString());
                    }

                    if (isNormalized && !inputSchema.IsNormalized(srcCol))
                    {
                        isNormalized = false;
                    }

                    if (MetadataUtils.TryGetCategoricalFeatureIndices(inputSchema, srcCol, out int[] typeCat))
Exemple #43
0
    protected void UpdateSalaryCC(Schema me, H3.SmartForm.SubmitSmartFormResponse response, string 工序名称, string 任务类别)
    {
        //JGJL=加工记录
        //var 工序名称 = "粗车";

        var ID      = me.PostValue("ID");
        var scmJGJL = new Schema(me.Engine, "加工任务记录");
        var rows    = scmJGJL.ClearFilter()
                      .And("ID", "=", ID)
                      .And("工序名称", "=", 工序名称)
                      .And("检验结果", "=", "合格")
                      .GetList();

        foreach (var row in rows)
        {
            scmJGJL.CurrentRow = row;
            var 单件拟定工时 = Convert.ToDouble(scmJGJL.Cell("单件拟定工时"));
            var 加工数量   = Convert.ToDouble(scmJGJL.Cell("加工数量"));
            var 工价     = 28;
            var 加工难度   = 1;
            var 加工人员   = scmJGJL.Cell("加工人员");
            var 设备名称   = scmJGJL.Cell("设备名称");
            var 部门名称   = scmJGJL.Cell("部门名称");
            var 检验结果   = scmJGJL.Cell("检验结果");
            var 任务名称   = scmJGJL.Cell("任务名称");

            var 总工时 = 单件拟定工时 * 加工数量;
            var 总工资 = 总工时 * 工价 * 加工难度;

            var 分配比例  = 1.0;
            var smRow = scmJGJL.ClearFilter()
                        .And("ID", "=", ID)
                        .And("工序名称", "=", 工序名称)
                        .And("任务名称", "=", "四面见光")
                        .GetFirst();
            if (smRow != null)
            {
                分配比例 = 0.8;
            }

            var 工艺下屑重量 = Convert.ToDouble(scmJGJL.Cell("工艺下屑重量"));
            var 总下屑量   = 工艺下屑重量 * 加工数量 * 分配比例;
            var 外径     = Convert.ToDouble(scmJGJL.Cell("外径"));
            var 补助标准   = 外径 >= 0 && 外径 < 4000 ? 18 : (外径 >= 4000 && 外径 < 5000 ? 23 : (外径 >= 5000 && 外径 < 6000 ? 30 : 30));
            var 补刀金额   = 补助标准 * 总下屑量 / 1000;

            var 总工作量 = 0;

            var scmGZ = new Schema(me.Engine, "任务绩效表");
            scmGZ.GetNew();


            scmGZ.CellAny("工序名称", 工序名称);
            scmGZ.CellAny("任务名称", 任务名称);

            scmGZ.CellAny("ID", ID);
            scmGZ.CellAny("检验结果", 检验结果);
            scmGZ.CellAny("加工人员", 加工人员);
            scmGZ.CellAny("部门名称", 部门名称);
            scmGZ.CellAny("设备名称", 设备名称);
            scmGZ.CellAny("单件拟定工时", 单件拟定工时);
            scmGZ.CellAny("总工时", 总工时);
            scmGZ.CellAny("加工数量", 加工数量);
            scmGZ.CellAny("工价", 工价);
            scmGZ.CellAny("总工资", 总工资);
            scmGZ.CellAny("工艺下屑重量", 工艺下屑重量);
            scmGZ.CellAny("总下屑量", 总下屑量);
            scmGZ.CellAny("总工作量", 总工作量);
            scmGZ.CellAny("补刀金额", 补刀金额);
            scmGZ.Create(true);
        }
    }
Exemple #44
0
        async static Task Main(string[] args)
        {
            var provider = new ServiceCollection()
                           .AddTypesenseClient(config =>
            {
                config.ApiKey = "Hu52dwsas2AdxdE";
                config.Nodes  = new List <Node> {
                    new Node {
                        Host = "localhost", Port = "8108", Protocol = "http"
                    }
                };
            }).BuildServiceProvider();

            var typesenseClient = provider.GetService <ITypesenseClient>();

            var schema = new Schema
            {
                Name   = "Addresses",
                Fields = new List <Field>
                {
                    new Field("id", "string", false),
                    new Field("houseNumber", "int32", false),
                    new Field("accessAddress", "string", false, true),
                },
                DefaultSortingField = "houseNumber"
            };

            var createCollectionResponse = await typesenseClient.CreateCollection(schema);

            Console.WriteLine($"Created collection: {JsonSerializer.Serialize(createCollectionResponse)}");

            var retrieveCollection = await typesenseClient.RetrieveCollection("Addresses");

            Console.WriteLine($"Retrieve collection: {JsonSerializer.Serialize(retrieveCollection)}");

            var retrieveCollections = await typesenseClient.RetrieveCollections();

            Console.WriteLine($"Retrieve collections: {JsonSerializer.Serialize(retrieveCollections)}");

            var addressOne = new Address
            {
                HouseNumber   = 2,
                AccessAddress = "Smedgade 25B"
            };

            var addressTwo = new Address
            {
                HouseNumber   = 66,
                AccessAddress = "Smedgade 67B"
            };

            var addressThree = new Address
            {
                HouseNumber   = 33,
                AccessAddress = "Medad 55A"
            };

            // Example to show optional AccessAddress
            var addressFour = new Address
            {
                HouseNumber = 3,
            };

            var houseOneResponse = await typesenseClient.CreateDocument <Address>("Addresses", addressOne);

            Console.WriteLine($"Created document: {JsonSerializer.Serialize(houseOneResponse)}");
            var houseTwoResponse = await typesenseClient.CreateDocument <Address>("Addresses", addressTwo);

            Console.WriteLine($"Created document: {JsonSerializer.Serialize(addressTwo)}");
            var houseThreeResponse = await typesenseClient.CreateDocument <Address>("Addresses", addressThree);

            Console.WriteLine($"Created document: {JsonSerializer.Serialize(houseThreeResponse)}");
            var houseFourResponse = await typesenseClient.CreateDocument <Address>("Addresses", addressFour);

            Console.WriteLine($"Created document: {JsonSerializer.Serialize(houseFourResponse)}");

            var exportResult = await typesenseClient.ExportDocuments <Address>("Addresses");

            Console.WriteLine($"Export result: {JsonSerializer.Serialize(exportResult)}");

            var upsertHouseOne = await typesenseClient.UpsertDocument <Address>("Addresses", addressOne);

            Console.WriteLine($"Upserted document: {JsonSerializer.Serialize(upsertHouseOne)}");

            var addresses = new List <Address>
            {
                new Address {
                    AccessAddress = "Sulstreet 4", Id = "5", HouseNumber = 223
                },
                new Address {
                    AccessAddress = "Sulstreet 24", Id = "6", HouseNumber = 321
                }
            };

            var importDocuments = await typesenseClient.ImportDocuments <Address>("Addresses", addresses, 40, ImportType.Create);

            Console.WriteLine($"Import documents: {JsonSerializer.Serialize(importDocuments)}");

            addressFour.HouseNumber = 1;
            var updateDocumentResult = await typesenseClient.UpdateDocument <Address>("Addresses", "4", addressFour);

            Console.WriteLine($"Updated document: ${JsonSerializer.Serialize(updateDocumentResult)}");

            var query = new SearchParameters
            {
                Text    = "Sul",
                QueryBy = "accessAddress"
            };

            var searchResult = await typesenseClient.Search <Address>("Addresses", query);

            Console.WriteLine($"Search result: {JsonSerializer.Serialize(searchResult)}");

            var retrievedDocument = await typesenseClient.RetrieveDocument <Address>("Addresses", "1");

            Console.WriteLine($"Retrieved document: {JsonSerializer.Serialize(retrievedDocument)}");

            var deleteResult = await typesenseClient.DeleteDocument <Address>("Addresses", "2");

            Console.WriteLine($"Deleted document {JsonSerializer.Serialize(deleteResult)}");

            var deleteFilterResult = await typesenseClient.DeleteDocuments("Addresses", "houseNumber:>=3", 100);

            Console.WriteLine($"Deleted amount: {deleteFilterResult.NumberOfDeleted}");

            var deleteCollectionResult = await typesenseClient.DeleteCollection("Addresses");

            Console.WriteLine($"Deleted collection: {JsonSerializer.Serialize(deleteCollectionResult)}");
        }
Exemple #45
0
    protected void UpdateSalaryZK(Schema me, H3.SmartForm.SubmitSmartFormResponse response, string 工序名称, string 任务类别)
    {
        //JGJL=加工记录
        //var 工序名称 = "钻孔";

        var ID      = me.PostValue("ID");
        var scmJGJL = new Schema(me.Engine, "加工任务记录");
        var rows    = scmJGJL.ClearFilter()
                      .And("ID", "=", ID)
                      .And("工序名称", "=", 工序名称)
                      .And("任务类别", "=", 任务类别)
                      .And("检验结果", "=", "合格")
                      .GetList();

        foreach (var row in rows)
        {
            scmJGJL.CurrentRow = row;
            var 单件拟定工时 = Convert.ToDouble(scmJGJL.Cell("单件拟定工时"));
            var 加工数量   = Convert.ToDouble(scmJGJL.Cell("加工数量"));
            var 工价     = 39;
            var 加工难度   = 1;
            var 加工人员   = scmJGJL.Cell("加工人员");
            var 设备名称   = scmJGJL.Cell("设备名称");
            var 部门名称   = scmJGJL.Cell("部门名称");
            var 检验结果   = scmJGJL.Cell("检验结果");
            var 任务名称   = scmJGJL.Cell("任务名称");

            var 总工时  = 单件拟定工时 * 加工数量;
            var 计件工资 = 总工时 * 工价 * 加工难度;

            var 工艺下屑重量 = Convert.ToDouble(scmJGJL.Cell("工艺下屑重量"));
            var 总下屑量   = 工艺下屑重量 * 加工数量; //* 分配比例;

            var 片厚    = Convert.ToDouble(scmJGJL.Cell("片厚"));
            var 孔数    = Convert.ToDouble(scmJGJL.Cell("孔数"));
            var 产品小类  = scmJGJL.Cell("产品小类");
            var 工作量系数 = 产品小类 == "深孔钻顶法兰" ? 3 : 产品小类 == "大孔径产品" ? 2 : 1;
            var 总工作量  = 片厚 * 孔数 * 加工数量 * 工作量系数;
            var 补刀金额  = 0;

            var scmGZ = new Schema(me.Engine, "任务绩效表");
            scmGZ.GetNew();

            scmGZ.CellAny("工序名称", 工序名称);
            scmGZ.CellAny("任务名称", 任务名称);

            scmGZ.CellAny("ID", ID);
            scmGZ.CellAny("检验结果", 检验结果);
            scmGZ.CellAny("加工人员", 加工人员);
            scmGZ.CellAny("部门名称", 部门名称);
            scmGZ.CellAny("设备名称", 设备名称);
            scmGZ.CellAny("单件拟定工时", 单件拟定工时);
            scmGZ.CellAny("加工数量", 加工数量);
            scmGZ.CellAny("总工时", 总工时);
            scmGZ.CellAny("工价", 工价);
            scmGZ.CellAny("计件工资", 计件工资);
            scmGZ.CellAny("工艺下屑重量", 工艺下屑重量);
            scmGZ.CellAny("总下屑量", 总下屑量);
            scmGZ.CellAny("总工作量", 总工作量);
            scmGZ.CellAny("补刀金额", 补刀金额);
            scmGZ.Create(true);
        }
    }
        public IActionResult GetUser(string schemaCode)
        {
            var schema = new Schema {
                Name = "PricingSchema"
            };

            schema.Sections = new List <SchemaSection> {
                new SchemaSection {
                    Name    = "ClientInfo",
                    IsArray = false,
                    Fields  = new List <SchemaField> {
                        new SchemaField {
                            Name = "ClientName", DataType = "text", Label = "Client Name", IsRequired = true
                        },
                        new SchemaField {
                            Name = "ClientIndustry", DataType = "options", Label = "Client Industry", Lookup = "CLIENTINDUSTRIES", RelatedField = "ClientIndustryText", IsRequired = true
                        },
                        new SchemaField {
                            Name = "ClientIndustryText", DataType = "hidden"
                        },
                        new SchemaField {
                            Name = "PriorYearPrice", DataType = "number", Label = "Prior Year Price (US$)", IsRequired = true
                        },
                        new SchemaField {
                            Name = "AGRCHours", DataType = "number", Label = "AGRC (Hours)", IsRequired = true
                        },
                        new SchemaField {
                            Name = "DataAnalyticsCharge", DataType = "number", Label = "Data & Analytics Charge (US$)", IsRequired = true
                        },
                        new SchemaField {
                            Name = "AGCNCharge", DataType = "number", Label = "AGCN Charge (Per RAN, US$)", IsRequired = true
                        },
                    }
                },
                new SchemaSection {
                    Name    = "InsuranceSchedule",
                    IsArray = true,
                    Fields  = new List <SchemaField> {
                        new SchemaField  {
                            Name = "BusinessLine", DataType = "options", Label = "Line of Business", Lookup = "BUSINESSLINES", RelatedField = "BusinessLineText", IsRequired = true
                        },
                        new SchemaField  {
                            Name = "BusinessLineText", DataType = "hidden"
                        },
                        new SchemaField  {
                            Name = "Premium", DataType = "number", Label = "Premium Amount (US$)", IsRequired = true
                        },
                        new SchemaField  {
                            Name = "PolicyCount", DataType = "number", Label = "Number of Policies", IsRequired = true
                        },
                        new SchemaField  {
                            Name = "RemunerationType", DataType = "options", Label = "Remuneration Type", Lookup = "REMUNERATIONTYPES", RelatedField = "RemunerationTypeText", IsRequired = true
                        },
                        new SchemaField  {
                            Name = "RemunerationTypeText", DataType = "hidden"
                        },
                        new SchemaField  {
                            Name = "BrokingCenter", DataType = "options", Label = "Broking Center", Lookup = "BROKINGCENTERS", RelatedField = "BrokingCenterText"
                        },
                        new SchemaField  {
                            Name = "BrokingCenterText", DataType = "hidden"
                        }
                    }
                }
            };

            return(this.Ok(schema));
        }
Exemple #47
0
 protected override MulticlassPredictionTransformer <OvaPredictor> MakeTransformer(OvaPredictor model, Schema trainSchema)
 => new MulticlassPredictionTransformer <OvaPredictor>(Host, model, trainSchema, FeatureColumn.Name, LabelColumn.Name);
Exemple #48
0
    protected void UpdateSalary(Schema me, H3.SmartForm.SubmitSmartFormResponse response, string 任务名称)
    {
        var 工序名称 = me.PostValue("当前工序");
        //var 任务名称 = me.PostValue("任务名称");
        var 订单号  = me.PostValue("订单号");
        var 产品编号 = me.PostValue("订单规格号");
        var 规格号  = 产品编号.Split('-')[1];
        var 工件号  = me.PostValue("工件号");
        var 轧制方式 = me.PostValue("轧制方式");

        var 加工者  = me.PostValue("第一加工者");
        var 加工设备 = me.PostValue("第一设备");
        var 设备类型 = me.PostValue("设备类型1");
        var 加工数量 = Convert.ToDouble(me.PostValue("加工量1"));


        var pro  = new ProductTime(me.Engine);
        var 拟定工时 = pro.GetTime(订单号, 规格号, 工件号, 设备类型, "粗车", 轧制方式);
        var 工价   = 28.0;
        var 粗车工资 = 拟定工时 * 加工数量 * 工价 * 1.0;

        var slyScm = new Schema(me.Engine, "任务绩效表");
        var smRow  = slyScm.ClearFilter()
                     .And("产品编号", "=", 产品编号)
                     .And("工件号", "=", 工件号)
                     .And("工序名称", "=", 工序名称)
                     .And("任务名称", "=", "四面见光")
                     .GetFirst();
        var 分配比例 = 1.0;

        if (smRow != null)
        {
            分配比例 = 0.8;
        }

        var 工艺下屑重量 = pro.Dust;
        var 实际下屑重量 = 工艺下屑重量 * 加工数量 * 分配比例;
        var 实际用时   = 拟定工时 * 加工数量;

        var 外径   = pro.OutsideDiameter;
        var 补助标准 = 外径 >= 0 && 外径 < 4000 ? 18 : (外径 >= 4000 && 外径 < 5000 ? 23 : (外径 >= 5000 && 外径 < 6000 ? 30 : 30));
        var 补刀金额 = 补助标准 * 实际下屑重量 / 1000; //粗车补刀金额

        var existRow = slyScm.ClearFilter()
                       .And("产品编号", "=", 产品编号)
                       .And("工件号", "=", 工件号)
                       .And("工序名称", "=", 工序名称)
                       .And("任务名称", "=", 任务名称)
                       .GetFirst();

        if (existRow == null)
        {
            slyScm.GetNew();
        }

        slyScm.Cell("工序名称", 工序名称);
        slyScm.Cell("任务名称", 任务名称);
        slyScm.Cell("产品编号", 产品编号);
        slyScm.Cell("工件号", 工件号);

        slyScm.Cell("加工者", 加工者);
        slyScm.Cell("加工设备", 加工设备);
        slyScm.CellAny("拟定工时", 拟定工时);
        slyScm.CellAny("实际用时", 实际用时);

        slyScm.CellAny("加工数量", 加工数量);
        slyScm.CellAny("工价", 工价);
        slyScm.CellAny("工资", 粗车工资);
        slyScm.CellAny("工艺下屑重量", 工艺下屑重量);
        slyScm.CellAny("实际下屑重量", 实际下屑重量);
        slyScm.CellAny("补刀金额", 补刀金额);
        if (existRow == null)
        {
            slyScm.Create(true);
        }
        else
        {
            slyScm.Update(true);
        }

        //switch (工价)
        //{
        //    case 分配比例:
        //        break;
        //    default:
        //        break;
        //}
    }
 public void TestQuoteObjectName_DoesNotAddMoreQuotesWhenAlreadyQuoted()
 {
     Assert.AreEqual(@"""my_table""", Schema.QuoteObjectName(@"""my_table"""));
 }
Exemple #50
0
 /// <summary>
 /// Retrieves a cell value by field name.
 /// </summary>
 public object this[string name] => this[Schema.GetFieldIndex(name)];
        public void TestIdentityIsFalseWhenItShouldBe()
        {
            var column = Schema.FindTable("manufact").FindColumn("manu_code");

            Assert.IsFalse(column.IsIdentity);
        }
        public void TestColumns()
        {
            var table = Schema.FindTable("stock");

            Assert.AreEqual(1, table.Columns.Count(c => c.ActualName == "unit_price"));
        }
Exemple #53
0
        private static async Task <Schema> GetSchemaForEndpoint(IApiClient apiClient, Schema schema, Endpoint?endpoint)
        {
            if (endpoint == null)
            {
                return(schema);
            }

            if (endpoint.ShouldGetStaticSchema)
            {
                return(await endpoint.GetStaticSchemaAsync(apiClient, schema));
            }

            var recordsListRaw = await endpoint.ReadRecordsAsync(apiClient, null, null, true).Take(100).ToListAsync();

            var recordsList = recordsListRaw
                              .Select(r => JsonConvert.DeserializeObject <Dictionary <string, object> >(r.DataJson))
                              .ToList();

            var types = GetPropertyTypesFromRecords(recordsList);

            var record = recordsList.FirstOrDefault();

            var properties = new List <Property>();

            if (record != null)
            {
                foreach (var recordKey in record.Keys)
                {
                    var property = new Property
                    {
                        Id              = recordKey,
                        Name            = recordKey,
                        Type            = types[recordKey],
                        IsKey           = endpoint.PropertyKeys.Contains(recordKey),
                        IsCreateCounter = false,
                        IsUpdateCounter = false,
                        TypeAtSource    = await endpoint.IsCustomProperty(apiClient, recordKey)
                            ? Constants.CustomProperty
                            : "",
                        IsNullable = true
                    };

                    properties.Add(property);
                }
            }

            schema.Properties.Clear();
            schema.Properties.AddRange(properties);

            if (schema.Properties.Count == 0)
            {
                schema.Description = Constants.EmptySchemaDescription;
            }

            return(schema);
        }
 public void TestQuoteObjectName_AddsQuotesWhenNotAlreadyQuoted()
 {
     Assert.AreEqual(@"""my_table""", Schema.QuoteObjectName("my_table"));
 }
Exemple #55
0
        public static bool StoreConfiguration(Document doc, KeynoteConfiguration config)
        {
            bool stored = false;

            try
            {
                if (null == configSchema)
                {
                    configSchema = CreateConfigSchema();
                }

                if (null != configSchema)
                {
                    IList <DataStorage> savedStorage = GetStorage(doc, configSchema);
                    if (savedStorage.Count > 0)
                    {
                        using (Transaction trans = new Transaction(doc))
                        {
                            trans.Start("Delete Storage");
                            try
                            {
                                var storageIds = from storage in savedStorage select storage.Id;
                                if (storageIds.Count() > 0)
                                {
                                    foreach (ElementId storageId in storageIds)
                                    {
                                        doc.Delete(storageId);
                                    }
                                }
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.RollBack();
                                string message = ex.Message;
                            }
                        }
                    }

                    using (Transaction trans = new Transaction(doc))
                    {
                        trans.Start("Store Storage");
                        try
                        {
                            DataStorage dStorage = DataStorage.Create(doc);
                            Entity      entity   = new Entity(configSchemaId);
                            entity.Set <string>(s_ProjectId, config.ProjectId);
                            entity.Set <string>(s_KeynoteSetId, config.KeynoteSetId);
                            dStorage.SetEntity(entity);

                            trans.Commit();
                        }
                        catch (Exception ex)
                        {
                            trans.RollBack();
                            string message = ex.Message;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to store configuration.\n" + ex.Message, "Store Configuration", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(stored);
        }
        public void TestIdentityIsTrueWhenItShouldBe()
        {
            var column = Schema.FindTable("customer").FindColumn("customer_num");

            Assert.IsTrue(column.IsIdentity);
        }
 private protected override IRowMapper MakeRowMapper(Schema inputSchema) => new Mapper(this, inputSchema);
 public EditSchemaViewModel(int id)
 {
     TheSchema          = Context.Schemas.FirstOrDefault(x => x.SchemaId == id);
     TheSchema.JSONData = TheSchema.JSONData ?? "{ }";
     BookmarkTitle      = TheSchema.DisplayName;
 }
 // Factory method for SignatureLoadRowMapper.
 private static IRowMapper Create(IHostEnvironment env, ModelLoadContext ctx, Schema inputSchema)
 => Create(env, ctx).MakeRowMapper(inputSchema);
            public Mapper(OnnxTransformer parent, Schema inputSchema) :
                base(Contracts.CheckRef(parent, nameof(parent)).Host.Register(nameof(Mapper)), inputSchema, parent)
            {
                _parent            = parent;
                _inputColIndices   = new int[_parent.Inputs.Length];
                _isInputVector     = new bool[_parent.Inputs.Length];
                _inputTensorShapes = new OnnxShape[_parent.Inputs.Length];
                _inputOnnxTypes    = new System.Type[_parent.Inputs.Length];

                var model = _parent.Model;

                for (int i = 0; i < _parent.Inputs.Length; i++)
                {
                    var idx = model.InputNames.IndexOf(_parent.Inputs[i]);
                    if (idx < 0)
                    {
                        throw Host.Except($"Column {_parent.Inputs[i]} doesn't match input node names of model");
                    }

                    var inputNodeInfo = model.ModelInfo.InputsInfo[idx];

                    var shape     = inputNodeInfo.Shape;
                    var inputType = OnnxUtils.OnnxToMlNetType(inputNodeInfo.Type);

                    var inputShape = AdjustDimensions(inputNodeInfo.Shape);
                    _inputTensorShapes[i] = inputShape.ToList();
                    _inputOnnxTypes[i]    = inputNodeInfo.Type;

                    var col = inputSchema.GetColumnOrNull(_parent.Inputs[i]);
                    if (!col.HasValue)
                    {
                        throw Host.ExceptSchemaMismatch(nameof(inputSchema), "input", _parent.Inputs[i]);
                    }
                    _inputColIndices[i] = col.Value.Index;

                    var type       = inputSchema[_inputColIndices[i]].Type;
                    var vectorType = type as VectorType;
                    _isInputVector[i] = vectorType != null;

                    if (vectorType != null && vectorType.Size == 0)
                    {
                        throw Host.Except($"Variable length input columns not supported");
                    }

                    if (type.GetItemType() != inputType)
                    {
                        throw Host.ExceptSchemaMismatch(nameof(inputSchema), "input", _parent.Inputs[i], inputType.ToString(), type.ToString());
                    }

                    // If the column is one dimension we make sure that the total size of the Onnx shape matches.
                    // Compute the total size of the known dimensions of the shape.
                    int valCount = inputShape.Where(x => x > 0).Aggregate((x, y) => x * y);
                    // The column length should be divisible by this, so that the other dimensions can be integral.
                    int typeValueCount = type.GetValueCount();
                    if (typeValueCount % valCount != 0)
                    {
                        throw Contracts.Except($"Input shape mismatch: Input '{_parent.Inputs[i]}' has shape {String.Join(",", inputShape)}, but input data is of length {typeValueCount}.");
                    }

                    //Host.Assert(_outputItemRawType == _outputColType.ItemType.RawType);
                }
            }