Example #1
0
        private bool SaveUpdate(ITransaction transaction)
        {
            SchemaObject schemaObject = Schema.Schema.GetSchemaObject(GetType());

            IUpdateQuery updateQuery = SQLProviderFactory.GetUpdateQuery();

            updateQuery.Table = new Table(schemaObject.SchemaName, schemaObject.ObjectName);

            foreach (Schema.Field field in schemaObject.GetFields().Where(f => f != schemaObject.PrimaryKeyField))
            {
                FieldValue fieldValue = new FieldValue();
                fieldValue.FieldName = field.FieldName;
                fieldValue.Value     = field.GetValue(this);
                updateQuery.FieldValueList.Add(fieldValue);
            }

            updateQuery.Condition = new Condition()
            {
                Left          = (Base.Data.Operand.Field)schemaObject.PrimaryKeyField.FieldName,
                ConditionType = Condition.ConditionTypes.Equal,
                Right         = new Literal(schemaObject.PrimaryKeyField.GetValue(this))
            };

            updateQuery.Execute(transaction);

            return(true);
        }
Example #2
0
        public V2SwaggerRouteDataBuilder Response(string code, string response_model, bool isarray = false, string description = null)
        {
            description = description ?? Enum.GetName(typeof(HttpStatusCode), Convert.ToInt32(code));

            var obj = new SchemaObject {
                Ref = "#/definitions/" + response_model
            };

            ResponseObject response_object;

            if (isarray)
            {
                response_object = new ResponseObject {
                    Description = description,
                    Schema      = new SchemaList {
                        Type = "array", Items = obj
                    }
                };
            }
            else
            {
                response_object = new ResponseObject {
                    Description = description,
                    Schema      = obj
                };
            }


            IDictionary <string, ResponseObject> responses =
                ((RouteOperationModel)Data.Operations[CurrentMethod]).Responses;

            responses.Add(Convert.ToString(code), response_object);

            return(this);
        }
Example #3
0
        private static void CheckStringType(SchemaObject propertySchemaObject, KeyValuePair <string, object> kv,
                                            TestMessageResult testMessageResult)
        {
            if (kv.Value != null)
            {
                var notGuid     = (!Guid.TryParse(kv.Value.ToString(), out _));
                var notDateTime = (!DateTime.TryParse(kv.Value.ToString(), out _));

                if (propertySchemaObject.Format != null)
                {
                    var format = propertySchemaObject.GetFormat();
                    // Validate specific string formats
                    if (format == Format.DateTime && notDateTime)
                    {
                        AddFormatError(testMessageResult, kv.Value.ToString(), kv.Key, Format.DateTime);
                    }
                }
                if (notGuid && propertySchemaObject.Reference == "Guid")
                {
                    AddFormatError(testMessageResult, kv.Value.ToString(), kv.Key, Format.Guid);
                }
            }
            else if (kv.Value == null && propertySchemaObject.Reference == "Guid")
            {
                AddFormatError(testMessageResult, null, kv.Key, Format.Guid);
            }
        }
Example #4
0
        private bool SaveInsert(ITransaction transaction)
        {
            SchemaObject schemaObject = Schema.Schema.GetSchemaObject(GetType());

            IInsertQuery insertQuery = SQLProviderFactory.GetInsertQuery();

            insertQuery.Table = new Table(schemaObject.SchemaName, schemaObject.ObjectName);

            foreach (Schema.Field field in schemaObject.GetFields())
            {
                if (field == schemaObject.PrimaryKeyField)
                {
                    continue;
                }

                FieldValue fieldValue = new FieldValue();
                fieldValue.FieldName = field.FieldName;
                fieldValue.Value     = field.GetValue(this);
                insertQuery.FieldValueList.Add(fieldValue);
            }

            long?primaryKey = insertQuery.Execute(transaction);

            if (primaryKey != null)
            {
                schemaObject.PrimaryKeyField.SetPrivateDataCallback(this, primaryKey);
                return(true);
            }

            return(false);
        }
Example #5
0
            public PhpOperation(Method m)
            {
                var name = "_" + m.Name + "_operation";

                Property = PHP.Property(new ClassName(MicrosoftRestOperationInterface), name);

                var thisProperty = PHP.This.Arrow(Property);

                ConstructorStatements = OperationInfoInit(thisProperty, m);

                var parameters = m.Parameters
                                 .Where(p => !p.IsConstant &&
                                        !p.IsApiVersion() &&
                                        p.SerializedName != "subscriptionId");

                var call = PHP.Return(thisProperty.Call(
                                          CallFunction,
                                          PHP.CreateArray(parameters.Select(p => PHP.KeyValue(
                                                                                p.SerializedName,
                                                                                new ObjectName(p.SerializedName).Ref())))));

                Function = PHP.Function(
                    name: m.Name,
                    description: m.Description,
                    @return: m.ReturnType.Body == null ? null : SchemaObject.Create(m.ReturnType.Body).ToPhpType(),
                    parameters: parameters.Select(p => {
                    var phpType = SchemaObject.Create(p.ModelType).ToPhpType();
                    return(PHP.Parameter(
                               p.IsRequired ? phpType : new Nullable(phpType),
                               new ObjectName(p.SerializedName)));
                }),
                    body: PHP.Statements(call));
            }
Example #6
0
        private static void CheckIntegerType(SchemaObject propertySchemaObject, KeyValuePair <string, object> kv,
                                             TestMessageResult testMessageResult)
        {
            var isInt32 = int.TryParse(kv.Value.ToString(), out _);
            var isInt64 = long.TryParse(kv.Value.ToString(), out _);

            // Validate integer data type
            if (!isInt32 && !isInt64)
            {
                AddTypeError(testMessageResult, kv.Value.ToString(), kv.Key, propertySchemaObject.Type);
            }

            if (propertySchemaObject.Format != null)
            {
                // Validate specific integer formats
                if (propertySchemaObject.Format.EqualsCaseInsensitive("int32") && !isInt32)
                {
                    AddFormatError(testMessageResult, kv.Value.ToString(), kv.Key, Format.Int32);
                }
                else if (propertySchemaObject.Format.EqualsCaseInsensitive("int64") && !isInt64)
                {
                    AddFormatError(testMessageResult, kv.Value.ToString(), kv.Key, Format.Int64);
                }
            }
        }
Example #7
0
        public void ShouldParseReferenceName()
        {
            const string reference = "#/Test";
            var          result    = SchemaObject.ParseReferenceName(reference);

            result.ShouldBe("Test");
        }
Example #8
0
        /// <summary>
        /// Creates a new SchemaObject as ObjectTypes.ComplexType
        /// </summary>
        /// <param name="complexType">The XSD complext ype that the new SchemaObject should be based on</param>
        private SchemaObject InitializeComplexType(XmlSchemaComplexType complexType)
        {
            SchemaObject newSimpleObject = new SchemaObject(this, complexType)
            {
                Name     = this.GetName(complexType.QualifiedName, null),
                DataType = complexType.BaseXmlSchemaType != null && !string.IsNullOrEmpty(complexType.BaseXmlSchemaType.Name) ?
                           this.GetName(complexType.BaseXmlSchemaType.QualifiedName, null) :
                           string.Empty,
                Type = ObjectTypes.ComplexType
            };

            // TODO: More complicated logic to determine if a restriction is being applied
            if (this.complexTypes.Count(y => y.Name == newSimpleObject.Name) > 0)
            {
                return(this.complexTypes.SingleOrDefault(y => y.Name == newSimpleObject.Name));
            }

            if (IsRecurring(newSimpleObject))
            {
                return(null);
            }

            if (!this.initializing || newSimpleObject.Depth <= maxInitialDepth)
            {
                newSimpleObject.InitializeChildren(newSimpleObject, complexType);
            }

            this.complexTypes.Add(newSimpleObject);

            return(newSimpleObject);
        }
Example #9
0
        public override void ToString(StringBuilder buf, int indent)
        {
            SchemaObject.ToString(buf, indent);

            if (Alias != null)
            {
                buf.Append(" AS ");
                Alias.ToString(buf);
            }

            if (TableHints.Count > 0)
            {
                buf.Append(" WITH (");

                for (var i = 0; i < TableHints.Count; i++)
                {
                    if (i > 0)
                    {
                        buf.Append(", ");
                    }

                    TableHints[i].ToString(buf);
                }

                buf.Append(") ");
            }
        }
Example #10
0
            public FunctionGenerator(EmissionsGenerator egen, TypeBuilder dcType, SchemaObject funcInfo, string methodName, MethodAttributes accessibility)
            {
                Type resultType;

                this.EGen         = egen;
                this.DCType       = dcType;
                this.FunctionInfo = funcInfo;
                if (funcInfo is TableFunction)
                {
                    this.ResultType = egen._tableTypes[funcInfo.DotNetName];
                }
                else
                {
                    if (funcInfo.ReturnInfo == null)
                    {
                        return;
                    }
                    this.ResultType = funcInfo.ReturnInfo.ClrType;
                }
                if (funcInfo is TableFunction)
                {
                    resultType = typeof(IQueryable <>).MakeGenericType(new Type[] { this.ResultType });
                }
                else
                {
                    resultType = this.ResultType;
                }
                this.Method = dcType.DefineMethod(methodName, accessibility, resultType, (from p in funcInfo.Parameters select p.ClrType).ToArray <Type>());
            }
        private void FillNewRow(SchemaObject schemaObject, Func <SchemaObject, BaseRow> rowConstructor)
        {
            CategoryRow categoryRow = null;

            if (!string.IsNullOrEmpty(schemaObject.ParentPath))
            {
                categoryRow =
                    PropertyGridControl.GetRowByName(schemaObject.ParentPath) as CategoryRow;
            }
            if (categoryRow != null)
            {
                var row = rowConstructor(schemaObject);
                if (row != null)
                {
                    categoryRow.ChildRows.Add(row);
                }
            }
            else
            {
                var row = rowConstructor(schemaObject);
                if (row != null)
                {
                    PropertyGridControl.Rows.Add(row);
                }
            }
        }
Example #12
0
        public override object Evaluate(Dictionary <string, object> parameters)
        {
            string[] parts      = field.Split('.');
            string   objectName = parts[0];

            if (!parameters.ContainsKey(objectName))
            {
                throw new KeyNotFoundException("Object with name " + objectName + " not found");
            }

            object latestObject = parameters[objectName];

            for (int i = 1; i < parts.Length; i++)
            {
                SchemaObject schemaObject = Schema.Schema.GetSchemaObject(latestObject.GetType());
                Field        field        = schemaObject.GetField(parts[i]);

                if (field != null)
                {
                    return(field.GetValue((DataObject)latestObject));
                }

                Relationship relationship = schemaObject.GetRelationship(parts[i]);
                if (relationship == null)
                {
                    throw new ArgumentException("Could not determine path during Object Expression evaluation");
                }

                latestObject = relationship.GetPrivateDataCallback(latestObject);
            }

            return(null);
        }
Example #13
0
        private static void TryParseStringArray(SchemaObject propertySchemaObject, KeyValuePair <string, object> kv, dynamic itemArray, TestMessageResult testMessageResult, bool itemIsGuid)
        {
            var itemFormat = propertySchemaObject.Items.GetFormat();

            if (itemFormat == Format.DateTime)
            {
                foreach (var item in itemArray)
                {
                    if (!DateTime.TryParse(item.ToString(), out DateTime _))
                    {
                        AddItemTypeError(testMessageResult, kv.Key, DataType.String, Format.DateTime);
                        break;
                    }
                }
            }
            else if (itemIsGuid)
            {
                foreach (var item in itemArray)
                {
                    if (!Guid.TryParse(item.ToString(), out Guid _))
                    {
                        AddItemTypeError(testMessageResult, kv.Key, DataType.String, Format.Guid);
                        break;
                    }
                }
            }
        }
Example #14
0
        public DataObject GetUntypedEditable(ITransaction transaction, IEnumerable <string> readOnlyFields = null)
        {
            SchemaObject     thisSchemaObject = Schema.Schema.GetSchemaObject(DataObjectType);
            HashSet <string> fields           = thisSchemaObject.GetFields().Select(f => f.FieldName).ToHashSet();

            if (readOnlyFields != null)
            {
                fields.AddRange(readOnlyFields);
            }

            fields.Add(thisSchemaObject.PrimaryKeyField.FieldName);

            Dictionary <string, Tuple <ISelectQuery, Dictionary <string, string> > > queries = GetBaseQueries(thisSchemaObject, fields);

            queries[""].Item1.PageSize = 1;

            DataTable table = queries[""].Item1.Execute(transaction);

            if (table.Rows.Count < 1)
            {
                return(null);
            }

            DataObject dataObject      = (DataObject)Activator.CreateInstance(DataObjectType);
            FieldInfo  isEditableField = typeof(DataObject).GetField("isEditable", BindingFlags.NonPublic | BindingFlags.Instance);

            isEditableField.SetValue(dataObject, true);
            FieldInfo isInsertField = typeof(DataObject).GetField("isInsert", BindingFlags.NonPublic | BindingFlags.Instance);

            isInsertField.SetValue(dataObject, false);

            dataObject.SetData(fields, queries, table.Rows[0]);

            return(dataObject);
        }
Example #15
0
        public IEnumerable <DataObject> GetUntypedEditableReader(ITransaction transaction, IEnumerable <string> readOnlyFields = null)
        {
            SchemaObject schemaObject = Schema.Schema.GetSchemaObject(DataObjectType);

            HashSet <string> fields = new HashSet <string>();

            foreach (Schema.Field field in schemaObject.GetFields())
            {
                fields.Add(field.FieldName);
            }

            if (readOnlyFields != null)
            {
                fields.AddRange(readOnlyFields);
            }

            Dictionary <string, Tuple <ISelectQuery, Dictionary <string, string> > > selectQueries = GetBaseQueries(schemaObject, fields);

            DataTable table           = selectQueries[""].Item1.Execute(transaction);
            FieldInfo isEditableField = typeof(DataObject).GetField("isEditable", BindingFlags.NonPublic | BindingFlags.Instance);
            FieldInfo isInsertField   = typeof(DataObject).GetField("isInsert", BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (DataRow row in table.Rows)
            {
                DataObject dataObject = (DataObject)Activator.CreateInstance(DataObjectType);
                isEditableField.SetValue(dataObject, true);
                isInsertField.SetValue(dataObject, false);

                dataObject.SetData(fields, selectQueries, row);

                yield return(dataObject);
            }
        }
Example #16
0
        private static void TryParseNumberArray(SchemaObject propertySchemaObject, KeyValuePair <string, object> kv, dynamic itemArray, TestMessageResult testMessageResult)
        {
            var itemFormat = propertySchemaObject.Items.GetFormat();

            foreach (var item in itemArray)
            {
                var isFloat  = float.TryParse(item.ToString(), out float _);
                var isDouble = double.TryParse(item.ToString(), out double _);

                // Validate integer data type, which is int32.
                if (itemFormat == null && !isFloat)
                {
                    AddItemTypeError(testMessageResult, kv.Key, DataType.Number);
                    break;
                }

                if (itemFormat != null)
                {
                    // Validate specific integer formats
                    if (itemFormat == Format.Float && !isFloat)
                    {
                        AddItemTypeError(testMessageResult, kv.Key, DataType.Number, Format.Float);
                        break;
                    }

                    if (itemFormat == Format.Double && !isDouble)
                    {
                        AddItemTypeError(testMessageResult, kv.Key, DataType.Number, Format.Double);
                        break;
                    }
                }
            }
        }
Example #17
0
        public static DDLActionEnum ValidateVersion(SchemaObject schemaObj, Version lowVersion, Version highVersion)
        {
            Debug.Assert(lowVersion <= highVersion);

            if (lowVersion == Version.MINVERSION && highVersion == Version.MAXVERSION)
            {
                return(DDLActionEnum.CREATE);
            }

            Version objLowVersion  = new Version(schemaObj.FirstMajorVersion, schemaObj.FirstMinorVersion);
            Version objHighVersion = new Version(schemaObj.LastMajorVersion, schemaObj.LastMinorVersion);       // current version

            Debug.Assert(objLowVersion <= objHighVersion);

            if ((lowVersion > objHighVersion) || (objHighVersion >= highVersion))
            {
                return(DDLActionEnum.NONE);
            }

            if (objLowVersion == objHighVersion)
            {
                return(DDLActionEnum.CREATE);
            }
            else
            {
                return(DDLActionEnum.MODIFY);
            }
        }
Example #18
0
        private static void CheckNumberType(SchemaObject propertySchemaObject, KeyValuePair <string, object> kv,
                                            TestMessageResult testMessageResult)
        {
            var stringVal = kv.Value.ToString();
            var isDouble  = double.TryParse(stringVal, out var doubleVal) && double.IsFinite(doubleVal);
            var isFloat   = float.TryParse(stringVal, out var floatVal) && float.IsFinite(floatVal);

            // Validate number data type
            if (!isDouble && !isFloat)
            {
                AddTypeError(testMessageResult, stringVal, kv.Key, propertySchemaObject.Type);
            }

            if (propertySchemaObject.Format != null)
            {
                var format = propertySchemaObject.GetFormat();
                // Validate specific number formats
                if (format == Format.Float && !isFloat)
                {
                    AddFormatError(testMessageResult, stringVal, kv.Key, Format.Float);
                }
                else if (format == Format.Double && !isDouble)
                {
                    AddFormatError(testMessageResult, stringVal, kv.Key, Format.Double);
                }
            }
        }
Example #19
0
        public override bool Evaluate(DataObject dataObject)
        {
            SchemaObject schemaObject = Schema.Schema.GetSchemaObject(dataObject.GetType());
            Field        schemaField  = schemaObject.GetField(field);

            return(schemaField.GetValue(dataObject) != null);
        }
Example #20
0
        public void ShouldPopulateReferencesDefinedSeparately()
        {
            var contractDictionary = new CaseInsensitiveDictionary <SchemaObject>
            {
                { "Contract", new SchemaObject {
                      Type = "Object"
                  } },
                { "Custom", new SchemaObject {
                      Type = "String", Example = "Custom example"
                  } }
            };

            contractDictionary["Contract"].Properties = new CaseInsensitiveDictionary <SchemaObject>
            {
                { "Test", new SchemaObject {
                      Reference = "#/Custom"
                  } },
            };

            var result = SchemaObject.PopulateReferences(contractDictionary);

            result.HasReferenceError.ShouldBeFalse();
            result.SchemaDictionary["Contract"].Properties["Test"].Type.ShouldBe("String");
            result.SchemaDictionary["Contract"].Properties["Test"].Example.ShouldBe("Custom example");
        }
Example #21
0
        public ActionXmlSet Read()
        {
            ScriptObject script = ServerApiInvoker.Get_Script(scriptId);

            ActionXmlSet xmlset = new ActionXmlSet()
            {
                XmlAction = script.Script,
                SchemaSet = new ActionSchemaSet()
            };

            Schema schema = null;

            if (Convert.ToInt32(schemaId) > 0)
            {
                schema = ServerApiInvoker.GetSchema(schemaId);
            }

            SchemaObject sco = null;

            if (Convert.ToInt32(schemaObjectId) > 0)
            {
                sco = ServerApiInvoker.GetSchemaObject(schemaObjectId);
            }
            if (schema != null)
            {
                xmlset.SchemaSet = new ActionSchemaSet(schema.DisplayName, schema.JsonObject, sco.JsonValue);
            }
            return(xmlset);
        }
Example #22
0
        public List <SchemaObject> GetDerivedTypes(string type)
        {
            if (string.IsNullOrEmpty(type) || type == "ANY")
            {
                return(this.ComplexTypes);
            }

            SchemaObject simpleComplexType = this.ComplexTypes.SingleOrDefault(y => y.Name.ToLower() == type.ToLower());

            if (simpleComplexType == null)
            {
                return(null);
            }

            XmlSchemaComplexType complexType  = simpleComplexType.XmlObject as XmlSchemaComplexType;
            List <SchemaObject>  derivedTypes = new List <SchemaObject>();

            complexType = this.Schema.SchemaTypes[complexType.QualifiedName] as XmlSchemaComplexType;

            foreach (XmlSchemaType globalType in this.Schema.SchemaTypes.Values)
            {
                if (XmlSchemaType.IsDerivedFrom(globalType, complexType, XmlSchemaDerivationMethod.None))
                {
                    string name = Helper.GetDataTypeName(this.Schema.TargetNamespace, globalType.Name);
                    derivedTypes.Add(this.ComplexTypes.Single(y => y.Name == name));
                }
            }

            return(derivedTypes);
        }
Example #23
0
        private void CheckObjectType(SchemaObject propertySchemaObject, KeyValuePair <string, object> kv,
                                     TestMessageResult testMessageResult, bool allowSubset)
        {
            CaseInsensitiveDictionary <object> innerObject = null;

            try
            {
                var json = JsonConvert.SerializeObject(kv.Value);
                innerObject = JsonConvert.DeserializeObject <CaseInsensitiveDictionary <object> >(json);
            }
            catch (Exception)
            {
                AddTypeError(testMessageResult, kv.Value.ToString(), kv.Key, "Object");
            }
            if (propertySchemaObject.Properties != null)
            {
                foreach (var innerProperty in propertySchemaObject.Properties)
                {
                    if (innerObject != null && innerObject.ContainsKey(innerProperty.Key))
                    {
                        ChecksForMessage(innerProperty.Value,
                                         new KeyValuePair <string, object>($"{kv.Key}{ParentOfSymbol}{innerProperty.Key}",
                                                                           innerObject[innerProperty.Key]), testMessageResult, allowSubset);
                    }
                    else
                    {
                        if (!allowSubset)
                        {
                            AddNotFoundError(testMessageResult, $"{kv.Key}{ParentOfSymbol}{innerProperty.Key}");
                        }
                    }
                }
            }
        }
Example #24
0
        /// <summary>
        /// Initializes an element within the schema.
        /// </summary>
        /// <remarks>Detects if the element is recurring. If so, does not continue.</remarks>
        /// <param name="parent">The parent schema object that the new schemaobject (derived from the element parameter) should be attached to.</param>
        /// <param name="element">The XSD element that the new schema object should be created based on.</param>
        /// <returns>The newly created schema object, which is already attached as a child to the parent (or the document as a whole if no parent is specified)</returns>
        protected SchemaObject InitializeElement(SchemaObject parent, XmlSchemaElement element, bool update = false)
        {
            List <SchemaObject> siblings = parent == null ? this.Children : parent.Children;

            SchemaObject newSimpleObject = new SchemaObject(this, element)
            {
                Parent   = parent,
                Name     = this.GetName(element.QualifiedName, element.RefName),
                DataType = element.ElementSchemaType != null && !string.IsNullOrEmpty(element.ElementSchemaType.Name) ?
                           this.GetName(element.ElementSchemaType.QualifiedName, null) :
                           null,
                Type = ObjectTypes.Element
            };

            // Make sure the element doesn't already exist
            var foundExisting = siblings.SingleOrDefault(y => y.Name == newSimpleObject.Name);

            if (update && foundExisting != null)
            {
                var foundExistingIndex = siblings.IndexOf(foundExisting);
                siblings.Remove(foundExisting);
                siblings.Insert(foundExistingIndex, newSimpleObject);
            }
            else
            {
                siblings.Add(newSimpleObject);
            }

            if (this.initializing && newSimpleObject.Depth <= maxInitialDepth)
            {
                newSimpleObject.InitializeChildren(newSimpleObject, element);
            }

            return(newSimpleObject);
        }
Example #25
0
        private SchemaObject DeriveSchemaForType(Type type)
        {
            var sc = new SchemaObject();

            sc.Type       = "object";
            sc.Properties = new Dictionary <string, SchemaObjectOrReference>();
            foreach (PropertyInfo prop in type.GetProperties())
            {
                sc.Properties[prop.Name] = BuildSchemaForType(prop.PropertyType);
            }
            var required = new List <string>();

            foreach (PropertyInfo prop in type.GetProperties())
            {
                if (IsRequiredProperty(prop))
                {
                    required.Add(ToCamelCase(prop.Name));
                }
            }
            if (required.Count > 0)
            {
                sc.Required = required;
            }
            return(sc);
        }
Example #26
0
        private void ChecksForMessage(SchemaObject propertySchemaObject, KeyValuePair <string, object> kv,
                                      TestMessageResult testMessageResult, bool allowSubset)
        {
            var dataType = propertySchemaObject.GetDataType();

            if (dataType == DataType.Integer)
            {
                CheckIntegerType(propertySchemaObject, kv, testMessageResult);
            }

            if (dataType == DataType.Number)
            {
                CheckNumberType(propertySchemaObject, kv, testMessageResult);
            }

            if (dataType == DataType.Boolean)
            {
                CheckBooleanType(propertySchemaObject, kv, testMessageResult);
            }

            if (dataType == DataType.String)
            {
                CheckStringType(propertySchemaObject, kv, testMessageResult);
            }

            if (dataType == DataType.Array)
            {
                CheckArrayType(propertySchemaObject, kv, testMessageResult);
            }

            if (dataType == DataType.Object)
            {
                CheckObjectType(propertySchemaObject, kv, testMessageResult, allowSubset);
            }
        }
Example #27
0
        private static void TryParseIntegerArray(SchemaObject propertySchemaObject, KeyValuePair <string, object> kv, dynamic itemArray, TestMessageResult testMessageResult)
        {
            var itemFormat = propertySchemaObject.Items.GetFormat();

            foreach (var item in itemArray)
            {
                var isInt32 = int.TryParse(item.ToString(), out int _);
                var isInt64 = long.TryParse(item.ToString(), out long _);

                // Validate integer data type, which is int32.
                if (itemFormat == null && !isInt32)
                {
                    AddItemTypeError(testMessageResult, kv.Key, DataType.Integer);
                    break;
                }

                if (itemFormat != null)
                {
                    // Validate specific integer formats
                    if (itemFormat == Format.Int32 && !isInt32)
                    {
                        AddItemTypeError(testMessageResult, kv.Key, DataType.Integer, Format.Int32);
                        break;
                    }

                    if (itemFormat == Format.Int64 && !isInt64)
                    {
                        AddItemTypeError(testMessageResult, kv.Key, DataType.Integer, Format.Int64);
                        break;
                    }
                }
            }
        }
 private void loadSchemaToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (openFileDialogSchema.ShowDialog() == DialogResult.OK)
     {
         schemaObject = SchemaManager.LoadSchemaXMLFile(openFileDialogSchema.FileName);
         updateGrids();
     }
 }
Example #29
0
 public SchemaObject(SchemaObject parentInfo, string name, string caption, dynamic value, dynamic objectSchema)
 {
     Parent       = parentInfo;
     Name         = name;
     Value        = value;
     Caption      = caption;
     ObjectSchema = objectSchema;
 }
Example #30
0
        internal void SerializeToSchemaObject(SchemaObject inObj)
        {
            var handler = new SchemaEntitySerializer(inObj, components);

            foreach (var pair in components)
            {
                Dynamic.ForComponent(pair.Key, handler);
            }
        }
        private static void CreateSchema()
        {
            SchemaObject so = new SchemaObject();

            so.ServiceInstanceName = "DynamicADSO";
            so.ServiceInstanceDisplayName = "DynamicADSO";
            so.ServiceInstanceDescription = "DynamicADSO";

            //Standard Inputs
            List<string> inputProp = new List<string>();
            List<string> reqProp = new List<string>();
            List<string> retProp = new List<string>();

            so.AddProperty("sAMAccountName", "sAMAccountName", "AD Schema Property", "DirectoryString", SoType.Text);
            so.AddProperty("displayName", "Display Name", "AD Display Name Property", "DirectoryString", SoType.Text);
            so.AddProperty("cn", "Common Name", "AD Common Name Property", "DirectoryString", SoType.Text);
            so.AddProperty("userPrincipleName", "userPrincipleName", "AD Schema Property", "DirectoryString", SoType.Text);
            so.AddProperty("givenName", "givenName", "AD Schema Property", "DirectoryString", SoType.Text);
            so.AddProperty("initials", "initials", "AD Schema Property", "DirectoryString", SoType.Text);
            so.AddProperty("sn", "sn", "AD Schema Property", "DirectoryString", SoType.Text);
            so.AddProperty("userPassword", "userPassword", "AD Schema Property", "DirectoryString", SoType.Text);
            so.AddProperty("mail", "mail", "AD Schema Property", "DirectoryString", SoType.Text);
            so.AddProperty("WhenCreated", "WhenCreated", "AD Schema Property", "DirectoryString", SoType.Text);
            so.AddProperty("WhenUpdated", "WhenUpdated", "AD Schema Property", "DirectoryString", SoType.Text);

            reqProp = new List<string>();

            //Hard Coded Properties

            so.AddProperty("SubStringSearchInput", "SubString Search Input", "User/Group Common Name SubString Search Input","DirectoryString", SoType.Text);
            so.AddProperty("Domain", "Domain", "Specify Domain to use for action [Coded Property]", "DirectoryString", SoType.Text);
            so.AddProperty("MaxSearchResultSize", "MaxSearchResultSize", "Specify the maximun number of records to return - default is 2000 - *=Unlimited [Coded Property]", "DirectoryString", SoType.Text);
            so.AddProperty("OrganisationalUnit", "OrganisationalUnit", "Specify OU, for multilevel OU pass delimited string ie America|HR [Coded Property]", "DirectoryString", SoType.Text);
            so.AddProperty("UAC_AccountDisabled", "UAC_AccountDisabled", "User Account Disabled [Coded Property]", "bool", SoType.YesNo);
            so.AddProperty("UAC_PasswordCannotChange", "UAC_PasswordCannotChange", "User Cannot Change password [Coded Property]", "bool", SoType.YesNo);
            so.AddProperty("UAC_PasswordNeverExpired", "UAC_PasswordNeverExpired", "User password never expires [Coded Property]", "bool", SoType.YesNo);
            so.AddProperty("UAC_PasswordExpired", "UAC_PasswordExpired", "User password expired [Coded Property]", "bool", SoType.YesNo);
            so.AddProperty("transactionStatus", "Transaction Status", "Status of last operation","DirectoryString", SoType.Text);
            so.AddProperty("transactionMessage", "Transaction Message", "Error message from last operation","DirectoryString", SoType.Text);

            //CreateUser
            reqProp.Add("sAMAccountName");

            inputProp.Add("sAMAccountName");
            inputProp.Add("givenName");
            inputProp.Add("initials");
            inputProp.Add("userPassword");
            inputProp.Add("sn");
            inputProp.Add("mail");

            inputProp.Add("OrganisationalUnit");
            inputProp.Add("UAC_AccountDisabled");
            inputProp.Add("UAC_PasswordCannotChange");
            inputProp.Add("UAC_PasswordNeverExpired");
            inputProp.Add("UAC_PasswordExpired");

            retProp.Add("WhenCreated");
            retProp.Add("transactionStatus");
            retProp.Add("transactionMessage");

            so.AddMethod("CreateUser", "CreateUser", "Create a User in Active Directory", MethodType.Create, inputProp, reqProp, retProp);

            //UpdateUser
            inputProp = new List<string>();
            reqProp = new List<string>();
            retProp = new List<string>();

            reqProp.Add("sAMAccountName");

            inputProp.Add("sAMAccountName");
            inputProp.Add("givenName");
            inputProp.Add("initials");
            inputProp.Add("userPassword");
            inputProp.Add("sn");
            inputProp.Add("mail");

            inputProp.Add("OrganisationalUnit");
            inputProp.Add("UAC_AccountDisabled");
            inputProp.Add("UAC_PasswordCannotChange");
            inputProp.Add("UAC_PasswordNeverExpired");
            inputProp.Add("UAC_PasswordExpired");

            retProp.Add("WhenUpdated");
            retProp.Add("transactionStatus");
            retProp.Add("transactionMessage");

            so.AddMethod("UpdateUser", "UpdateUser", "Update a User in Active Directory", MethodType.Update, inputProp, reqProp, retProp);


            //Read User
            inputProp = new List<string>();
            reqProp = new List<string>();
            retProp = new List<string>();

            reqProp.Add("sAMAccountName");

            inputProp.Add("sAMAccountName");

            retProp.Add("sAMAccountName");
            retProp.Add("givenName");
            retProp.Add("initials");
            retProp.Add("sn");
            retProp.Add("mail");
            retProp.Add("OrganisationalUnit");
            retProp.Add("transactionStatus");
            retProp.Add("transactionMessage");

            so.AddMethod("ReadUser", "ReadUser", "Read a Users details from Active Directory", MethodType.Read, inputProp, reqProp, retProp);


            //GetUsers
            inputProp = new List<string>();
            reqProp = new List<string>();
            retProp = new List<string>();

            inputProp.Add("givenName");
            inputProp.Add("initials");
            inputProp.Add("sn");
            inputProp.Add("mail");
            inputProp.Add("MaxSearchResultSize");
            inputProp.Add("OrganisationalUnit");

            retProp.Add("sAMAccountName");
            retProp.Add("givenName");
            retProp.Add("initials");
            retProp.Add("sn");
            retProp.Add("mail");
            retProp.Add("MaxSearchResultSize");
            retProp.Add("OrganisationalUnit");
            retProp.Add("transactionStatus");
            retProp.Add("transactionMessage");
            
            so.AddMethod("GetUsers", "GetUsers", "Get a list of users details from Active Directory", MethodType.List, inputProp, reqProp, retProp);

            //MoveUserOU
            inputProp = new List<string>();
            reqProp = new List<string>();
            retProp = new List<string>();

            reqProp.Add("sAMAccountName");
            reqProp.Add("OrganisationalUnit");
            retProp.Add("transactionStatus");
            retProp.Add("transactionMessage");
            inputProp.Add("OrganisationalUnit");
            inputProp.Add("sAMAccountName");
            so.AddMethod("MoveUserOU", "Move User OU", "Move a user to a different OU in Active Directory", MethodType.Execute, inputProp, reqProp, retProp);

            //AddUserToGRoups / RemoveUserFRomGroups
            inputProp = new List<string>();
            reqProp = new List<string>();
            retProp = new List<string>();

            reqProp.Add("sAMAccountName");
            reqProp.Add("memberOf");
            retProp.Add("transactionStatus");
            retProp.Add("transactionMessage");
            inputProp.Add("sAMAccountName");
            inputProp.Add("memberOf");
            so.AddMethod("AddUserToGroups", "Add User To Groups", "Add User To Active Directory Groups", MethodType.Execute, inputProp, reqProp, retProp);
            so.AddMethod("RemoveUserFromGroups", "Remove User From Groups", "Remove a user from Active Directory Groups", MethodType.Execute, inputProp, reqProp, retProp);

            //Search Users By SubString / Search Groups By SubString
            inputProp = new List<string>();
            reqProp = new List<string>();
            retProp = new List<string>();

            retProp.Add("sAMAccountName");
            retProp.Add("SubStringSearchInput");
            retProp.Add("displayName");
            retProp.Add("cn");
            retProp.Add("transactionStatus");
            retProp.Add("transactionMessage");

            reqProp.Add("SubStringSearchInput");

            inputProp.Add("sAMAccountName");
            inputProp.Add("SubStringSearchInput");
            inputProp.Add("displayName");
            inputProp.Add("cn");

            so.AddMethod("SearchUsersBySubString", "Search Users By SubString", "Search for users by Selected Properties", MethodType.List, inputProp, reqProp, retProp);
            so.AddMethod("SearchGroupsBySubString", "Search Groups By SubString", "Search for groups by Selected Properties", MethodType.List, inputProp, reqProp, retProp);

            SchemaManager.SaveSchemaXMLFile(so, string.Empty);
            
        }
		static void Main(string[] args)
		{
			for (int i = 0; i < args.Length; i++)
			{
				switch (args[i].ToUpperInvariant())
				{
					case "-SERVER":
						Server = args[++i];
						break;

					case "-DATABASE":
						Database = args[++i];
						break;
					
					case "-SKIPTO":
						Skip = Int32.Parse(args[++i]) - 1;
						break;

					case "-TAKE":
						Take = Int32.Parse(args[++i]);
						break;

					case "-CLEAN":
						Clean = true;
						break;

					case "-FILTER":
						TypeFilter = (SchemaObjectType)Enum.Parse(typeof(SchemaObjectType), args[++i]);
						break;

					case "-SMO":
						SMOTest = true;
						break;

					case "-SCRIPT":
						ScriptOnly = true;
						break;

					default:
						if (Filename == null)
							Filename = args[i];
						break;
				}				
			}

			// set up the connection string
			ConnectionString.InitialCatalog = Database;
			ConnectionString.DataSource = Server;
			ConnectionString.IntegratedSecurity = true;

			// drop the database if starting clean
			if (Clean)
				SchemaInstaller.DropDatabase(ConnectionString.ConnectionString);

			// make sure we are always working with an empty database
			if (!CreateDatabase())
				return;

			// load the schema
			SchemaObjectCollection schema = LoadSchema();

			try
			{
				// install the schema as is
				using (SqlConnection connection = new SqlConnection(ConnectionString.ConnectionString))
				{
					connection.Open();

					// install it the first time
					SchemaInstaller installer = new SchemaInstaller(connection);
					installer.Install("Test", schema);
					schema.Verify(connection);

					// script the result through SMO
					Console.WriteLine("Scripting database");
					List<string> originalScript = null;
					if (SMOTest)
					{
						originalScript = ScriptDatabaseWithSMO().ToList();
						originalScript.Sort();
					}

					//  run test cases that modify each of the elements
					for (int i = Skip; i < schema.Count; i++)
					{
						if (Take-- <= 0)
							return;

						// if a type filter is defined, then filter by that type
						if (TypeFilter.HasValue && schema[i].SchemaObjectType != TypeFilter.Value)
							continue;

						// if the type can't be modified, then don't test it
						if (!schema[i].CanModify(connection))
						{
							Console.WriteLine();
							Console.WriteLine("Not testing modification of {0} {1}", schema[i].SchemaObjectType, schema[i].SqlName.FullName);
							continue;
						}

						// make sure all of the objects are there
						try
						{
							Console.Write('\r');
							Console.Write(new String(' ', Console.WindowWidth - 1));
							Console.Write('\r');
							Console.Write("Testing modifications {0}/{1}", (i + 1), schema.Count);

							// modify the schema and re-install it
							schema[i] = new SchemaObject(schema[i].Sql + " -- MODIFIED");

							if (ScriptOnly)
								Console.WriteLine(installer.ScriptChanges("Test", schema));
							else
								installer.Install("Test", schema);

							// make sure all of the objects are there
							if (SMOTest)
							{
								// script the whole database
								var updatedScript = ScriptDatabaseWithSMO().ToList();
								updatedScript.Sort();
								MatchScripts(originalScript, updatedScript);
							}
							else
							{
								// just verify the dependencies
								schema.Verify(connection);
							}
						}
						catch (Exception e)
						{
							Console.WriteLine();
							Console.WriteLine("ERROR While modifying:");
							Console.WriteLine(schema[i].Name);
							Console.WriteLine(e.ToString());

							throw;
						}
					}

					Console.WriteLine();
				}
			}
			finally
			{
				Console.WriteLine("Dropping database");
				SchemaInstaller.DropDatabase(ConnectionString.ConnectionString);
			}
		}
Example #33
0
 static string TypeToString(SchemaObject.SchemaObjectType type)
 {
     switch (type)
     {
         case SchemaObject.SchemaObjectType.Unknown:
             return "";
         case SchemaObject.SchemaObjectType.StoredProcedure:
             return "P";
         case SchemaObject.SchemaObjectType.Function:
             return "FN";
         case SchemaObject.SchemaObjectType.TableFunction:
             return "TF";
         case SchemaObject.SchemaObjectType.InlineTableFunction:
             return "IF";
         case SchemaObject.SchemaObjectType.Table:
             return "U";
         case SchemaObject.SchemaObjectType.View:
             return "V";
         default:
             return "";
     }
 }
Example #34
0
 public BodyParameter(string name, SchemaObject schema)
     : base(name, ParameterLocation.Body)
 {
     this.Schema = schema;
 }
Example #35
0
        public SqlQuery QueryVersions(DatasetInfo baseTable, DatasetInfo versionedTable, Expression expression)
        {
            var sql = new SqlBuilder(adapter);

            var v = new SchemaObject(versionedTable.Name, "v");

            var a = new SchemaObject(baseTable.Name, "a");

            sql.Append("SELECT ");

            sql.WriteColumns(versionedTable.Members, prefix: "v"); // mutable values, primary keys, ...

            sql.Append(", ");

            sql.WriteColumns(baseTable.Members.Where(m => !m.IsVersion && !m.IsKey && !m.IsMutable), prefix: "a"); // immutable values from base table

            sql.From(v); // SELECT from v

            var keyName = baseTable.PrimaryKey[0].Name;

            // join the base (immutable) values with the versioned values
            sql.InnerJoin(
                baseTable       : v,        // versioned values
                joinedTable     : a,        // base values
                baseColumn      : keyName, 
                joinedColumn    : keyName
            );

            sql.Where(Expand(expression, baseTable)); 

            return new SqlQuery(sql.ToString(), sql.Parameters);
        }