Inheritance: System.Enum, System.IComparable, System.IFormattable, System.IConvertible
Exemple #1
0
 public IndexField(string fieldName, object value, FieldType type, IndexFieldValueType valueType)
 {
     this.fieldName = fieldName;
     this.value = value;
     this.type = type;
     this.valueType = valueType;
 }
        public static List<string> GetFieldList(FieldType fieldType, object obj)
        {
            var list = new List<string>();
            Type type = obj.GetType();

            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                var attribute = (ValidateFieldAttribute)property.GetCustomAttributes(typeof(ValidateFieldAttribute), true)
                    .FirstOrDefault(r => ((ValidateFieldAttribute)r).Type == fieldType);

                if (attribute == null)
                    continue;

                object value = property.GetValue(obj, null);

                if (value is string)
                {
                    if (string.IsNullOrEmpty((string)value))
                        list.Add(attribute.Name);
                }
            }

            return list;
        }
 // Constructors
 internal QField(int fieldId, string value, FieldType type, IQRecord record)
 {
     FieldId = fieldId;
     Type = type;
     Record = record; // needs to be before Value.
     Value = value;
 }
 public TextFieldParser(Stream stream)
 {
     this.m_CommentTokens = new string[0];
     this.m_LineNumber = 1L;
     this.m_EndOfData = false;
     this.m_ErrorLine = "";
     this.m_ErrorLineNumber = -1L;
     this.m_TextFieldType = FieldType.Delimited;
     this.m_WhitespaceCodes = new int[] { 
         9, 11, 12, 0x20, 0x85, 160, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 
         0x2009, 0x200a, 0x200b, 0x2028, 0x2029, 0x3000, 0xfeff
      };
     this.m_WhiteSpaceRegEx = new Regex(@"\s", RegexOptions.CultureInvariant);
     this.m_TrimWhiteSpace = true;
     this.m_Position = 0;
     this.m_PeekPosition = 0;
     this.m_CharsRead = 0;
     this.m_NeedPropertyCheck = true;
     this.m_Buffer = new char[0x1000];
     this.m_HasFieldsEnclosedInQuotes = true;
     this.m_MaxLineSize = 0x989680;
     this.m_MaxBufferSize = 0x989680;
     this.m_LeaveOpen = false;
     this.InitializeFromStream(stream, Encoding.UTF8, true);
 }
 public BondFieldMappingAttribute(BondField field_, Focus focus_=Focus.None, FieldType fieldType_=FieldType.None, CellColourScheme colourScheme_=CellColourScheme.None)
 {
   Field = field_;
   Focus = focus_;
   FieldType = fieldType_;
   ColourScheme = colourScheme_;
 }
 public AddFieldDialog Type(FieldType type)
 {
     var element = FindElement("field-type");
     var select = new SelectElement(element);
     select.SelectByValue(type.ToText());
     return this;
 }
Exemple #7
0
        public Field(XmlElement elField)
        {
            String typeName = elField.GetAttribute("type");
            string lbStr = elField.GetAttribute("lower-bound");
            string ubStr = elField.GetAttribute("upper-bound");
            string fieldTypeStr = elField.GetAttribute("fieldtype");
            string valueStr = elField.InnerText;

            type = ClassTypes.GetType(typeName);
            fieldType = ParseTypeString(fieldTypeStr);

            if (!Formal)
            {
                value = ParseFieldValue(type, valueStr);
            }
            else
            {
                if (lbStr != null)
                {
                    lowerBound = (IComparable) ParseFieldValue(type, lbStr);
                }
                if (ubStr != null)
                {
                    upperBound = (IComparable) ParseFieldValue(type, ubStr);
                }
            }
        }
 public FieldBase(FieldType Type, FieldBase Base)
 {
     this.Type = Type;
     this.Name = Type.Name;
     this.TenantID = Configure.GetTenantResolutionProvider().GetTenantID();
     LoadUpValues(Base);
 }
        /// <summary>
        /// Gets a list of all <see cref="Rock.Model.FieldType">FieldTypes</see> (all items that implement the <see cref="Rock.Field.IFieldType"/> interface) and registers the 
        /// <see cref="Rock.Model.FieldType">FieldTypes</see> that have not been previously registered.
        /// </summary>
        /// <param name="physWebAppPath">A <see cref="System.String"/> representing the physical path of the web application.</param>
        public static void RegisterFieldTypes( string physWebAppPath )
        {
            var fieldTypes = new Dictionary<string, EntityType>();

            var rockContext = new RockContext();
            var fieldTypeService = new FieldTypeService( rockContext );

            var existingFieldTypes = fieldTypeService.Queryable().ToList();

            foreach ( var type in Rock.Reflection.FindTypes( typeof( Rock.Field.IFieldType ) ) )
            {
                string assemblyName = type.Value.Assembly.GetName().Name;
                string className = type.Value.FullName;

                if ( !existingFieldTypes.Where( f =>
                    f.Assembly == assemblyName &&
                    f.Class == className ).Any() )
                {
                    string fieldTypeName = type.Value.Name.SplitCase();
                    if (fieldTypeName.EndsWith(" Field Type"))
                    {
                        fieldTypeName = fieldTypeName.Substring( 0, fieldTypeName.Length - 11 );
                    }
                    var fieldType = new FieldType();
                    fieldType.Name = fieldTypeName;
                    fieldType.Assembly = assemblyName;
                    fieldType.Class = className;
                    fieldType.IsSystem = false;
                    fieldTypeService.Add( fieldType );
                }
            }

            rockContext.SaveChanges();
        }
Exemple #10
0
 /// <summary>
 /// DBField Constructor
 /// </summary>
 /// <param name="name">The name of the field</param>
 /// <param name="type">The data type of the field</param>
 /// <param name="primaryKey">true if this field is part of a primary key, false otherwise</param>
 /// <param name="identity">true if this field is an identity, false otherwise</param>
 public DBField(string name, FieldType type, bool primaryKey, bool identity)
 {
     m_fieldName = name;
     m_fieldType = type;
     m_primaryKey = primaryKey;
     m_identity = identity;
 }
 public StructField(string name, FieldType type)
 {
     VarLength = -1;
     VarArrayLength = 0;
     Name = name;
     _type = type;
 }
 private void AppendFormat(StringBuilder sb, string tableName, string elementName, string fieldName, FieldType fieldType, ScriptItem item)
 {
     switch (fieldType) {
     case FieldType.Boolean:
         sb.AppendFormat("{0}[\"{1}\"].{2} = {3}",
                         tableName,
                         DialogueLua.StringToTableIndex(elementName),
                         DialogueLua.StringToTableIndex(fieldName),
                         (item.booleanValue == BooleanType.True) ? "true" : "false");
         break;
     case FieldType.Number:
         if (item.valueSetMode == ValueSetMode.To) {
             sb.AppendFormat("{0}[\"{1}\"].{2} = {3}",
                             tableName,
                             DialogueLua.StringToTableIndex(elementName),
                             DialogueLua.StringToTableIndex(fieldName),
                             item.floatValue);
         } else {
             sb.AppendFormat("{0}[\"{1}\"].{2} = {0}[\"{1}\"].{2} + {3}",
                             tableName,
                             DialogueLua.StringToTableIndex(elementName),
                             DialogueLua.StringToTableIndex(fieldName),
                             item.floatValue);
         }
         break;
     default:
         sb.AppendFormat("{0}[\"{1}\"].{2} = \"{3}\"",
                         tableName,
                         DialogueLua.StringToTableIndex(elementName),
                         DialogueLua.StringToTableIndex(fieldName),
                         item.stringValue);
         break;
     }
 }
Exemple #13
0
 public Field(string var, string label, FieldType type)
     : this()
 {
     this.Type	= type;
     this.Var	= var;
     this.Label	= label;
 }
        public static object Read(this BinaryReader reader, FieldType fieldType)
        {
            if (reader == null) throw new ArgumentNullException("reader");
            switch (fieldType)
            {
            case FieldType.UInt8:
                return reader.ReadByte();
            case FieldType.UInt16:
                return reader.ReadUInt16();
            case FieldType.UInt32:
                return reader.ReadUInt32();
            case FieldType.UInt64:
                return reader.ReadUInt64();

            case FieldType.Int8:
                return reader.ReadSByte();
            case FieldType.Int16:
                return reader.ReadInt16();
            case FieldType.Int32:
                return reader.ReadInt32();
            case FieldType.Int64:
                return reader.ReadInt64();

            case FieldType.Float:
                return reader.ReadSingle();
            case FieldType.Double:
                return reader.ReadDouble();

            case FieldType.NetDecimal:
                return reader.ReadDecimal();

            default:
                throw new ArgumentOutOfRangeException("Reading FieldType '{0}' from the stream failed, the type is not supported.".Formatted(fieldType));
            }
        }
        public Field(string name, FieldType type)
        {
            if (name == null) throw new ArgumentNullException(nameof(name));

            this.Name = name;
            this.Type = type;
        }
Exemple #16
0
 public void SetDataName(string DataName, FieldType type)
 {
     if (this.Type == type)
     {
         this.Dataname = DataName;
     }
 }
Exemple #17
0
        public static string GetName(FieldType type)
        {
            string result = String.Empty;

            switch (type)
            {
                case FieldType.Auto:
                    result = "auto";
                    break;
                case FieldType.String:
                    result = "string";
                    break;
                case FieldType.Int:
                    result = "int";
                    break;
                case FieldType.Float:
                    result = "float";
                    break;
                case FieldType.Boolean:
                    result = "boolean";
                    break;
                case FieldType.Date:
                    result = "date";
                    break;
            }

            return result;
        }
Exemple #18
0
        public DataType OGRTypeToBufferType(FieldType OGRFieldType)
        {
            DataType BufferDataType;

            switch (OGRFieldType)
            {
                //case FieldType.OFTBinary:
                //    BufferDataType = DataType.DT_IMAGE;
                //    break;
                case FieldType.OFTDate:
                    BufferDataType = DataType.DT_DBDATE;
                    break;
                case FieldType.OFTDateTime:
                    BufferDataType = DataType.DT_DBTIMESTAMP;
                    break;
                case FieldType.OFTInteger:
                    BufferDataType = DataType.DT_I4;
                    break;
                case FieldType.OFTReal:
                    BufferDataType = DataType.DT_R8;
                    break;
                case FieldType.OFTString:
                    BufferDataType = DataType.DT_WSTR;
                    break;
                case FieldType.OFTTime:
                    BufferDataType = DataType.DT_DBTIME;
                    break;
                default:
                    BufferDataType = DataType.DT_NTEXT;
                    break;
            }

            return BufferDataType;
        }
 public DBF_Field(string Name, FieldType Type, int Size, int Precision, bool AllowNull)
 {
     this.Name = Name;
     this.Type = Type;
     this.Size = Size;
     this.Precision = Precision;
     this.AllowNull = AllowNull;
 }
 internal FieldDefinition(int index, string fieldName, FieldType type, int factoryId, int classId)
 {
     _classId = classId;
     _type = type;
     _fieldName = fieldName;
     _index = index;
     _factoryId = factoryId;
 }
 public ColumnDescriptor(string fieldName, FieldType columnType, string displayName, string groupName, Guid columnId)
 {
     _fieldName = fieldName;
     _columnType = columnType;
     _displayName = displayName;
     _groupName = groupName;
     _columnId = columnId;
 }
 public void addField(string fieldName, FieldType fieldType, string fieldValue)
 {
     List<object> field = new List<object>();
     field.Add(fieldName);
     field.Add(fieldType);
     field.Add(fieldValue);
     fieldTypeValues.Add(field);
 }
 internal QColumn(int columnId, string columnName, FieldType columnType, bool columnVirtual, bool columnLookup, bool isHidden)
     : this(columnName, columnType)
 {
     ColumnVirtual = columnVirtual;
     ColumnLookup = columnLookup;
     IsHidden = isHidden;
     ColumnId = columnId;
 }
Exemple #24
0
 public Field(Password password, int id, string name, FieldType type, object value, short order)
     : base(id, name)
 {
     this.Password = password;
     this.Type = type;
     if (IsString) ChangeSecureString(value, false); else this.value = value;
     this.Order = order;
 }
		public FieldAttribute(FieldType type, FieldRelationship relationship, string foreignParentFieldName, FieldCascades cascades)
		{
			this.location = FieldLocation.Foreign;
			this.type = type;
			this.relationship = relationship;
			this.foreignParentFieldName = foreignParentFieldName;
			this.cascades = cascades;
		}
		public FieldAttribute(FieldType type, FieldRelationship relationship, int ordinal, FieldConstraints constraints)
		{
			this.location = FieldLocation.Local;
			this.type = type;
			this.relationship = relationship;
			this.ordinal = ordinal;
			this.constraints = constraints;
		}
 public FieldDescriptor(BinaryReader b)
 {
     this.hash = b.ReadUInt32();
     this.type = (FieldType)b.ReadUInt16();
     this.reference = b.ReadUInt16();
     this.offset = b.ReadUInt32();
     this.secondaryOffset = b.ReadUInt32();
 }
 internal FieldDefinition(int index, string fieldName, FieldType type, int factoryId, int classId)
 {
     this.classId = classId;
     this.type = type;
     this.fieldName = fieldName;
     this.index = index;
     this.factoryId = factoryId;
 }
Exemple #29
0
 public Field(string name, FieldIndex index, FieldType type)
 {
     Name_ = name;
     Index_ = index;
     Type_ = type;
     DefaultPreference_ = Preference.None;
     Progression_ = FieldProgression.Unknown;
 }
Exemple #30
0
 public Field(Type type, IComparable lowerBound, IComparable upperBound)
 {
     value = null;
     this.type = type;
     this.lowerBound = lowerBound;
     this.upperBound = upperBound;
     fieldType = FieldType.FORMAL;
 }
Exemple #31
0
 /// <summary>
 /// Represents a 32-bit integer value.
 /// </summary>
 /// <param name="Thing">Reference to the thing to which the field belongs.</param>
 /// <param name="Timestamp">Timestamp of field value.</param>
 /// <param name="Name">Field Name.</param>
 /// <param name="Value">Field Value.</param>
 /// <param name="Type">Field Type flags.</param>
 /// <param name="QoS">Quality of Service flags.</param>
 public Int32Field(ThingReference Thing, DateTime Timestamp, string Name, int Value, FieldType Type, FieldQoS QoS)
     : base(Thing, Timestamp, Name, Type, QoS)
 {
     this.value = Value;
 }
Exemple #32
0
 /// <summary>
 /// Represents a 32-bit integer value.
 /// </summary>
 /// <param name="Thing">Reference to the thing to which the field belongs.</param>
 /// <param name="Timestamp">Timestamp of field value.</param>
 /// <param name="Name">Field Name.</param>
 /// <param name="Value">Field Value.</param>
 /// <param name="Type">Field Type flags.</param>
 /// <param name="QoS">Quality of Service flags.</param>
 /// <param name="Writable">If the field is writable, i.e. corresponds to a control parameter.</param>
 /// <param name="Module">Language Module for localization purposes.</param>
 /// <param name="StringIdSteps">String ID steps.</param>
 public Int32Field(ThingReference Thing, DateTime Timestamp, string Name, int Value, FieldType Type, FieldQoS QoS, bool Writable, string Module, params LocalizationStep[] StringIdSteps)
     : base(Thing, Timestamp, Name, Type, QoS, Writable, Module, StringIdSteps)
 {
     this.value = Value;
 }
Exemple #33
0
 /// <summary>
 /// Represents a 32-bit integer value.
 /// </summary>
 /// <param name="Thing">Reference to the thing to which the field belongs.</param>
 /// <param name="Timestamp">Timestamp of field value.</param>
 /// <param name="Name">Field Name.</param>
 /// <param name="Value">Field Value.</param>
 /// <param name="Type">Field Type flags.</param>
 /// <param name="QoS">Quality of Service flags.</param>
 /// <param name="Module">Language Module for localization purposes.</param>
 /// <param name="StringIds">String IDs.</param>
 public Int32Field(ThingReference Thing, DateTime Timestamp, string Name, int Value, FieldType Type, FieldQoS QoS, string Module,
                   params int[] StringIds)
     : base(Thing, Timestamp, Name, Type, QoS, Module, StringIds)
 {
     this.value = Value;
 }
 public SCField CreateFieldFromElement(SCField scField, Guid destFieldId, string convertedValue, FieldType fieldType)
 {
     return(new SCField()
     {
         Created = DateTime.UtcNow,
         Updated = DateTime.UtcNow,
         ItemId = scField.ItemId,
         Language = scField.Language,
         Version = scField.Version,
         Type = fieldType,
         Value = convertedValue,
         FieldId = destFieldId,
         Id = Guid.NewGuid()
     });
 }
Exemple #35
0
        public virtual void DoTestLongPostingsNoPositions(IndexOptions options)
        {
            // Don't use TestUtil.getTempDir so that we own the
            // randomness (ie same seed will point to same dir):
            Directory dir = NewFSDirectory(CreateTempDir("longpostings" + "." + Random().NextLong()));

            int NUM_DOCS = AtLeast(2000);

            if (VERBOSE)
            {
                Console.WriteLine("TEST: NUM_DOCS=" + NUM_DOCS);
            }

            string s1 = GetRandomTerm(null);
            string s2 = GetRandomTerm(s1);

            if (VERBOSE)
            {
                Console.WriteLine("\nTEST: s1=" + s1 + " s2=" + s2);

                /*
                 * for(int idx=0;idx<s1.Length();idx++) {
                 * System.out.println("  s1 ch=0x" + Integer.toHexString(s1.charAt(idx)));
                 * }
                 * for(int idx=0;idx<s2.Length();idx++) {
                 * System.out.println("  s2 ch=0x" + Integer.toHexString(s2.charAt(idx)));
                 * }
                 */
            }

            FixedBitSet isS1 = new FixedBitSet(NUM_DOCS);

            for (int idx = 0; idx < NUM_DOCS; idx++)
            {
                if (Random().NextBoolean())
                {
                    isS1.Set(idx);
                }
            }

            IndexReader r;

            if (true)
            {
                IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.CREATE).SetMergePolicy(NewLogMergePolicy());
                iwc.SetRAMBufferSizeMB(16.0 + 16.0 * Random().NextDouble());
                iwc.SetMaxBufferedDocs(-1);
                RandomIndexWriter riw = new RandomIndexWriter(Random(), dir, iwc);

                FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
                ft.IndexOptions = options;
                for (int idx = 0; idx < NUM_DOCS; idx++)
                {
                    Document doc   = new Document();
                    string   s     = isS1.Get(idx) ? s1 : s2;
                    Field    f     = NewField("field", s, ft);
                    int      count = TestUtil.NextInt(Random(), 1, 4);
                    for (int ct = 0; ct < count; ct++)
                    {
                        doc.Add(f);
                    }
                    riw.AddDocument(doc);
                }

                r = riw.Reader;
                riw.Dispose();
            }
            else
            {
#pragma warning disable 162
                r = DirectoryReader.Open(dir);
#pragma warning restore 162
            }

            /*
             * if (VERBOSE) {
             * System.out.println("TEST: terms");
             * TermEnum termEnum = r.Terms();
             * while(termEnum.Next()) {
             *  System.out.println("  term=" + termEnum.Term() + " len=" + termEnum.Term().Text().Length());
             *  Assert.IsTrue(termEnum.DocFreq() > 0);
             *  System.out.println("    s1?=" + (termEnum.Term().Text().equals(s1)) + " s1len=" + s1.Length());
             *  System.out.println("    s2?=" + (termEnum.Term().Text().equals(s2)) + " s2len=" + s2.Length());
             *  final String s = termEnum.Term().Text();
             *  for(int idx=0;idx<s.Length();idx++) {
             *    System.out.println("      ch=0x" + Integer.toHexString(s.charAt(idx)));
             *  }
             * }
             * }
             */

            Assert.AreEqual(NUM_DOCS, r.NumDocs);
            Assert.IsTrue(r.DocFreq(new Term("field", s1)) > 0);
            Assert.IsTrue(r.DocFreq(new Term("field", s2)) > 0);

            int num = AtLeast(1000);
            for (int iter = 0; iter < num; iter++)
            {
                string term;
                bool   doS1;
                if (Random().NextBoolean())
                {
                    term = s1;
                    doS1 = true;
                }
                else
                {
                    term = s2;
                    doS1 = false;
                }

                if (VERBOSE)
                {
                    Console.WriteLine("\nTEST: iter=" + iter + " doS1=" + doS1 + " term=" + term);
                }

                DocsEnum docs;
                DocsEnum postings;

                if (options == IndexOptions.DOCS_ONLY)
                {
                    docs     = TestUtil.Docs(Random(), r, "field", new BytesRef(term), null, null, DocsFlags.NONE);
                    postings = null;
                }
                else
                {
                    docs = postings = TestUtil.Docs(Random(), r, "field", new BytesRef(term), null, null, DocsFlags.FREQS);
                    Debug.Assert(postings != null);
                }
                Debug.Assert(docs != null);

                int docID = -1;
                while (docID < DocIdSetIterator.NO_MORE_DOCS)
                {
                    int what = Random().Next(3);
                    if (what == 0)
                    {
                        if (VERBOSE)
                        {
                            Console.WriteLine("TEST: docID=" + docID + "; do next()");
                        }
                        // nextDoc
                        int expected = docID + 1;
                        while (true)
                        {
                            if (expected == NUM_DOCS)
                            {
                                expected = int.MaxValue;
                                break;
                            }
                            else if (isS1.Get(expected) == doS1)
                            {
                                break;
                            }
                            else
                            {
                                expected++;
                            }
                        }
                        docID = docs.NextDoc();
                        if (VERBOSE)
                        {
                            Console.WriteLine("  got docID=" + docID);
                        }
                        Assert.AreEqual(expected, docID);
                        if (docID == DocIdSetIterator.NO_MORE_DOCS)
                        {
                            break;
                        }

                        if (Random().Next(6) == 3 && postings != null)
                        {
                            int freq = postings.Freq;
                            Assert.IsTrue(freq >= 1 && freq <= 4);
                        }
                    }
                    else
                    {
                        // advance
                        int targetDocID;
                        if (docID == -1)
                        {
                            targetDocID = Random().Next(NUM_DOCS + 1);
                        }
                        else
                        {
                            targetDocID = docID + TestUtil.NextInt(Random(), 1, NUM_DOCS - docID);
                        }
                        if (VERBOSE)
                        {
                            Console.WriteLine("TEST: docID=" + docID + "; do advance(" + targetDocID + ")");
                        }
                        int expected = targetDocID;
                        while (true)
                        {
                            if (expected == NUM_DOCS)
                            {
                                expected = int.MaxValue;
                                break;
                            }
                            else if (isS1.Get(expected) == doS1)
                            {
                                break;
                            }
                            else
                            {
                                expected++;
                            }
                        }

                        docID = docs.Advance(targetDocID);
                        if (VERBOSE)
                        {
                            Console.WriteLine("  got docID=" + docID);
                        }
                        Assert.AreEqual(expected, docID);
                        if (docID == DocIdSetIterator.NO_MORE_DOCS)
                        {
                            break;
                        }

                        if (Random().Next(6) == 3 && postings != null)
                        {
                            int freq = postings.Freq;
                            Assert.IsTrue(freq >= 1 && freq <= 4, "got invalid freq=" + freq);
                        }
                    }
                }
            }
            r.Dispose();
            dir.Dispose();
        }
Exemple #36
0
        public IEnumerable <ObjectState> GetDesiredState(SchemaConnection connection, IOutput output)
        {
            var schemaDriver  = connection.SchemaDriver;
            var sqlTranslator = new SqlTranslator(schemaDriver, null);

            HashSet <string> catalogs = new HashSet <string>(schemaDriver.DbDriver.DbStringComparer);

            foreach (var nrdoTable in codeBase.AllTables)
            {
                if (nrdoTable.ExistingName != null)
                {
                    if (nrdoTable.BeforeStatements.Any())
                    {
                        throw new ApplicationException("Table " + nrdoTable.Name + " is 'existing' but has before statements, which is no longer supported");
                    }
                    continue;
                }

                output.Verbose("Loading table " + nrdoTable.DatabaseName + " from " + nrdoTable.Type.Name);
                var table = TableType.Create(schemaName + "." + nrdoTable.DatabaseName);
                yield return(table);

                if (preserveColumnOrder)
                {
                    yield return(FieldOrderSensitivityType.Create(table.Identifier));
                }

                string sequencedPkeyFieldName = null;
                string sequenceName           = null;
                if (nrdoTable.IsPkeySequenced)
                {
                    sequencedPkeyFieldName = nrdoTable.PkeyGet.Fields.Single().Name;
                    var sequenceNameBase = getNameHashString(nrdoTable.Name) + "_" + sequencedPkeyFieldName;

                    if (schemaDriver.IsSequenceUsed)
                    {
                        sequenceName = "sq_" + sequenceNameBase;
                        yield return(SequenceType.Create(schemaName + "." + sequenceName));
                    }

                    if (schemaDriver.IsTriggerUsedForSequence)
                    {
                        var triggerName = "sqt_" + sequenceNameBase;
                        yield return(TriggerType.Create(table.Identifier, triggerName, schemaDriver.GetSequencedFieldTriggerTiming(), TriggerEvents.Insert,
                                                        schemaDriver.GetSequencedFieldTriggerBody(table.Name, sequencedPkeyFieldName, sequenceName)));
                    }
                }

                var fieldIndex = 0;
                foreach (var nrdoField in nrdoTable.Fields)
                {
                    if (nrdoField.Name == sequencedPkeyFieldName)
                    {
                        yield return(FieldType.CreateSequencedPkey(table.Identifier, nrdoField.Name, fieldIndex++, nrdoField.DbType, nrdoField.IsNullable, sequenceName));
                    }
                    else
                    {
                        yield return(FieldType.Create(table.Identifier, nrdoField.Name, fieldIndex++, nrdoField.DbType, nrdoField.IsNullable));
                    }
                }

                foreach (var nrdoIndex in nrdoTable.Indexes)
                {
                    if (nrdoIndex.IsPrimary)
                    {
                        yield return(UniqueIndexType.CreatePrimaryKey(table.Identifier, nrdoIndex.Name,
                                                                      from field in nrdoIndex.Fields select FieldType.Identifier(field), schemaDriver.DefaultPrimaryKeyCustomState));
                    }
                    else if (nrdoIndex.IsUnique)
                    {
                        yield return(UniqueIndexType.CreateUnique(table.Identifier, nrdoIndex.Name,
                                                                  from field in nrdoIndex.Fields select FieldType.Identifier(field), schemaDriver.DefaultUniqueConstraintCustomState));
                    }
                    else
                    {
                        yield return(NonUniqueIndexType.Create(table.Identifier, nrdoIndex.Name,
                                                               from field in nrdoIndex.Fields select FieldType.Identifier(field), schemaDriver.DefaultIndexCustomState));
                    }
                }

                if (nrdoTable.FulltextFields.Any() && connection.SchemaDriver.IsFulltextSupported(connection))
                {
                    var catalog = nrdoTable.FulltextCatalog ?? "NrdoFulltext";
                    if (!catalogs.Contains(catalog))
                    {
                        yield return(FulltextCatalogType.Create(catalog));

                        catalogs.Add(catalog);
                    }

                    var pkey = nrdoTable.Indexes.Where(index => index.IsPrimary).Single();
                    yield return(FulltextIndexType.Create(table.Identifier, FulltextCatalogType.Identifier(catalog), pkey.Name, nrdoTable.FulltextFields));
                }

                foreach (var nrdoFkey in nrdoTable.References)
                {
                    if (nrdoFkey.IsFkey)
                    {
                        yield return(FkeyType.Create(table.Identifier, TableType.Identifier(schemaName + "." + nrdoFkey.TargetTable.DatabaseName),
                                                     nrdoFkey.FkeyName, nrdoFkey.IsCascadingFkey,
                                                     from fjoin in nrdoFkey.Joins select new FieldPair(fjoin.From.Name, fjoin.To.Name)));
                    }
                }

                var beforeIndex = 0;
                foreach (var nrdoBefore in nrdoTable.BeforeStatements)
                {
                    yield return(BeforeStatementType.Create(table.Identifier, "0" + nrdoTable.Name, beforeIndex++, nrdoBefore.Name, nrdoBefore.Step,
                                                            nrdoBefore.Initial, nrdoBefore.Upgrade, sqlTranslator.Translate(nrdoBefore.Statement)));
                }

                foreach (var oldName in nrdoTable.RenamedFrom)
                {
                    var oldDbName = schemaName + "." + oldName.Replace(':', '_');
                    yield return(TableRenameType.Create(oldDbName, table.Name));
                }
            }

            foreach (var nrdoQuery in codeBase.AllQueries)
            {
                output.Verbose("Loading query " + nrdoQuery.DatabaseName + " from " + nrdoQuery.Type.Name);

                var queryName = schemaName + "." + nrdoQuery.DatabaseName;

                var parameters = from param in nrdoQuery.Params select new ProcParam(param.Name, param.DbType);

                if (nrdoQuery.IsStoredProc)
                {
                    yield return(QueryType.CreateProc(queryName, parameters, sqlTranslator.Translate(nrdoQuery.Sql)));

                    if (nrdoQuery.IsPreUpgradeHook)
                    {
                        yield return(PreUpgradeHookType.Create(queryName));
                    }
                }
                else if (nrdoQuery.IsStoredFunction)
                {
                    var returnType = nrdoQuery.Results.Single().DbType;
                    yield return(QueryType.CreateFunction(queryName, parameters, returnType, sqlTranslator.Translate(nrdoQuery.Sql)));
                }
                else
                {
                    yield return(QueryType.CreateUnstored(queryName));
                }

                var beforeIndex = 0;
                foreach (var nrdoBefore in nrdoQuery.BeforeStatements)
                {
                    yield return(BeforeStatementType.Create(QueryType.Identifier(queryName), "1" + nrdoQuery.Name, beforeIndex++, nrdoBefore.Name, nrdoBefore.Step,
                                                            nrdoBefore.Initial, nrdoBefore.Upgrade, sqlTranslator.Translate(nrdoBefore.Statement)));
                }
            }
        }
        protected internal virtual void AssertEquals(RandomTokenStream tk, FieldType ft, Terms terms)
        {
            Assert.AreEqual(1, terms.DocCount);
            int termCount = (new HashSet <string>(Arrays.AsList(tk.Terms))).Count;

            Assert.AreEqual(termCount, terms.Size());
            Assert.AreEqual(termCount, terms.SumDocFreq);
            Assert.AreEqual(ft.StoreTermVectorPositions, terms.HasPositions());
            Assert.AreEqual(ft.StoreTermVectorOffsets, terms.HasOffsets());
            Assert.AreEqual(ft.StoreTermVectorPayloads && tk.HasPayloads(), terms.HasPayloads());
            HashSet <BytesRef> uniqueTerms = new HashSet <BytesRef>();

            foreach (string term in tk.Freqs.Keys)
            {
                uniqueTerms.Add(new BytesRef(term));
            }
            BytesRef[] sortedTerms = uniqueTerms.ToArray(/*new BytesRef[0]*/);
            Array.Sort(sortedTerms, terms.Comparator);
            TermsEnum termsEnum = terms.Iterator(Random().NextBoolean() ? null : this.termsEnum.Value);

            this.termsEnum.Value = termsEnum;
            for (int i = 0; i < sortedTerms.Length; ++i)
            {
                BytesRef nextTerm = termsEnum.Next();
                Assert.AreEqual(sortedTerms[i], nextTerm);
                Assert.AreEqual(sortedTerms[i], termsEnum.Term());
                Assert.AreEqual(1, termsEnum.DocFreq());

                FixedBitSet bits     = new FixedBitSet(1);
                DocsEnum    docsEnum = termsEnum.Docs(bits, Random().NextBoolean() ? null : this.docsEnum.Value);
                Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsEnum.NextDoc());
                bits.Set(0);

                docsEnum = termsEnum.Docs(Random().NextBoolean() ? bits : null, Random().NextBoolean() ? null : docsEnum);
                Assert.IsNotNull(docsEnum);
                Assert.AreEqual(0, docsEnum.NextDoc());
                Assert.AreEqual(0, docsEnum.DocID());
                Assert.AreEqual(tk.Freqs[termsEnum.Term().Utf8ToString()], (int?)docsEnum.Freq());
                Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsEnum.NextDoc());
                this.docsEnum.Value = docsEnum;

                bits.Clear(0);
                DocsAndPositionsEnum docsAndPositionsEnum = termsEnum.DocsAndPositions(bits, Random().NextBoolean() ? null : this.docsAndPositionsEnum.Value);
                Assert.AreEqual(ft.StoreTermVectorOffsets || ft.StoreTermVectorPositions, docsAndPositionsEnum != null);
                if (docsAndPositionsEnum != null)
                {
                    Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsAndPositionsEnum.NextDoc());
                }
                bits.Set(0);

                docsAndPositionsEnum = termsEnum.DocsAndPositions(Random().NextBoolean() ? bits : null, Random().NextBoolean() ? null : docsAndPositionsEnum);
                Assert.AreEqual(ft.StoreTermVectorOffsets || ft.StoreTermVectorPositions, docsAndPositionsEnum != null);
                if (terms.HasPositions() || terms.HasOffsets())
                {
                    Assert.AreEqual(0, docsAndPositionsEnum.NextDoc());
                    int freq = docsAndPositionsEnum.Freq();
                    Assert.AreEqual(tk.Freqs[termsEnum.Term().Utf8ToString()], (int?)freq);
                    if (docsAndPositionsEnum != null)
                    {
                        for (int k = 0; k < freq; ++k)
                        {
                            int         position = docsAndPositionsEnum.NextPosition();
                            ISet <int?> indexes;
                            if (terms.HasPositions())
                            {
                                indexes = tk.PositionToTerms[position];
                                Assert.IsNotNull(indexes);
                            }
                            else
                            {
                                indexes = tk.StartOffsetToTerms[docsAndPositionsEnum.StartOffset()];
                                Assert.IsNotNull(indexes);
                            }
                            if (terms.HasPositions())
                            {
                                bool foundPosition = false;
                                foreach (int index in indexes)
                                {
                                    if (tk.TermBytes[index].Equals(termsEnum.Term()) && tk.Positions[index] == position)
                                    {
                                        foundPosition = true;
                                        break;
                                    }
                                }
                                Assert.IsTrue(foundPosition);
                            }
                            if (terms.HasOffsets())
                            {
                                bool foundOffset = false;
                                foreach (int index in indexes)
                                {
                                    if (tk.TermBytes[index].Equals(termsEnum.Term()) && tk.StartOffsets[index] == docsAndPositionsEnum.StartOffset() && tk.EndOffsets[index] == docsAndPositionsEnum.EndOffset())
                                    {
                                        foundOffset = true;
                                        break;
                                    }
                                }
                                Assert.IsTrue(foundOffset);
                            }
                            if (terms.HasPayloads())
                            {
                                bool foundPayload = false;
                                foreach (int index in indexes)
                                {
                                    if (tk.TermBytes[index].Equals(termsEnum.Term()) && Equals(tk.Payloads[index], docsAndPositionsEnum.Payload))
                                    {
                                        foundPayload = true;
                                        break;
                                    }
                                }
                                Assert.IsTrue(foundPayload);
                            }
                        }
                        try
                        {
                            docsAndPositionsEnum.NextPosition();
                            Assert.Fail();
                        }
                        catch (Exception e)
                        {
                            // ok
                        }
                    }
                    Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsAndPositionsEnum.NextDoc());
                }
                this.docsAndPositionsEnum.Value = docsAndPositionsEnum;
            }
            Assert.IsNull(termsEnum.Next());
            for (int i = 0; i < 5; ++i)
            {
                if (Random().NextBoolean())
                {
                    Assert.IsTrue(termsEnum.SeekExact(RandomInts.RandomFrom(Random(), tk.TermBytes)));
                }
                else
                {
                    Assert.AreEqual(SeekStatus.FOUND, termsEnum.SeekCeil(RandomInts.RandomFrom(Random(), tk.TermBytes)));
                }
            }
        }
Exemple #38
0
        public static bool GetFieldValue(MessageStructure ms, FieldType fieldType, ref string val)
        {
            bool result = false;

            switch (fieldType)
            {
            case FieldType.Int:
                val    = ms.ReadInt().ToString();
                result = true;
                break;

            case FieldType.Password:
            case FieldType.String:
                val    = ms.ReadString();
                result = true;
                break;

            case FieldType.Short:
                val    = ms.ReadShort().ToString();
                result = true;
                break;

            case FieldType.Byte:
                val    = ms.ReadByte().ToString();
                result = true;
                break;

            case FieldType.Long:
                val    = ms.ReadLong().ToString();
                result = true;
                break;

            case FieldType.Bool:
                val    = ms.ReadBool().ToString();
                result = true;
                break;

            case FieldType.Float:
                val    = ms.ReadFloat().ToString();
                result = true;
                break;

            case FieldType.Double:
                val    = ms.ReadDouble().ToString();
                result = true;
                break;

            case FieldType.DateTime:
                val    = ms.ReadDateTime().ToString();
                result = true;
                break;

            case FieldType.ULong:
                val    = ms.ReadUInt64().ToString();
                result = true;
                break;

            case FieldType.UInt:
                val    = ms.ReadUInt32().ToString();
                result = true;
                break;

            case FieldType.UShort:
                val    = ms.ReadUInt16().ToString();
                result = true;
                break;

            case FieldType.Record:
                break;

            case FieldType.End:
                break;

            case FieldType.Void:
                break;

            default:
                break;
            }

            return(result);
        }
    void AddFieldGUI(Dictionary <string, SingleField> dict)
    {
        EditorGUI.indentLevel = 1;
        isFold = EditorGUILayout.Foldout(isFold, "新增字段");
        if (isFold)
        {
            EditorGUI.indentLevel = 2;

            bool isNewType = false;

            fieldName = EditorGUILayout.TextField("字段名", fieldName);

            newType = (FieldType)EditorGUILayout.EnumPopup("字段类型", content.m_type);

            if (content.m_type != newType)
            {
                isNewType = true;
            }

            if (newType == FieldType.Enum)
            {
                int newIndex = EditorGUILayout.Popup("枚举类型", m_newTypeIndex, EditorTool.GetAllEnumType());

                if (newIndex != m_newTypeIndex)
                {
                    m_newTypeIndex = newIndex;
                    isNewType      = true;
                }
            }

            if (isNewType)
            {
                content.m_type     = newType;
                content.m_enumType = EditorTool.GetAllEnumType()[m_newTypeIndex];
                content.Reset();
            }

            content.m_content = EditorUtilGUI.FieldGUI_Type(content);

            if (!dict.ContainsKey(fieldName) && fieldName != "")
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.Space();

                if (GUILayout.Button("新增", GUILayout.Width(position.width - 60)))
                {
                    m_currentConfig.Add(fieldName, content);

                    fieldName      = "";
                    content        = new SingleField();
                    newType        = content.m_type;
                    m_newTypeIndex = 0;
                }

                EditorGUILayout.Space();
                EditorGUILayout.EndHorizontal();
            }
            else
            {
                if (dict.ContainsKey(fieldName))
                {
                    EditorGUILayout.LabelField("已存在该字段");
                }
            }
        }
    }
        public void TestRandomDiscreteMultiValueHighlighting()
        {
            String[] randomValues = new String[3 + Random.nextInt(10 * RandomMultiplier)];
            for (int i = 0; i < randomValues.Length; i++)
            {
                String randomValue;
                do
                {
                    randomValue = TestUtil.RandomSimpleString(Random);
                } while ("".Equals(randomValue, StringComparison.Ordinal));
                randomValues[i] = randomValue;
            }

            Directory         dir    = NewDirectory();
            RandomIndexWriter writer = new RandomIndexWriter(
                Random,
                dir,
                NewIndexWriterConfig(TEST_VERSION_CURRENT,
                                     new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()));

            FieldType customType = new FieldType(TextField.TYPE_STORED);

            customType.StoreTermVectors         = (true);
            customType.StoreTermVectorOffsets   = (true);
            customType.StoreTermVectorPositions = (true);

            int              numDocs   = randomValues.Length * 5;
            int              numFields = 2 + Random.nextInt(5);
            int              numTerms  = 2 + Random.nextInt(3);
            IList <Doc>      docs      = new JCG.List <Doc>(numDocs);
            IList <Document> documents = new JCG.List <Document>(numDocs);
            IDictionary <String, ISet <int> > valueToDocId = new JCG.Dictionary <String, ISet <int> >();

            for (int i = 0; i < numDocs; i++)
            {
                Document   document = new Document();
                String[][] fields   = RectangularArrays.ReturnRectangularArray <string>(numFields, numTerms); //new String[numFields][numTerms];
                for (int j = 0; j < numFields; j++)
                {
                    String[] fieldValues = new String[numTerms];
                    fieldValues[0] = getRandomValue(randomValues, valueToDocId, i);
                    StringBuilder builder = new StringBuilder(fieldValues[0]);
                    for (int k = 1; k < numTerms; k++)
                    {
                        fieldValues[k] = getRandomValue(randomValues, valueToDocId, i);
                        builder.Append(' ').Append(fieldValues[k]);
                    }
                    document.Add(new Field(F, builder.ToString(), customType));
                    fields[j] = fieldValues;
                }
                docs.Add(new Doc(fields));
                documents.Add(document);
            }
            writer.AddDocuments(documents);
            writer.Dispose();
            IndexReader reader = DirectoryReader.Open(dir);

            try
            {
                int highlightIters = 1 + Random.nextInt(120 * RandomMultiplier);
                for (int highlightIter = 0; highlightIter < highlightIters; highlightIter++)
                {
                    Console.WriteLine($"Highlighter iter: {highlightIter}");

                    String queryTerm = randomValues[Random.nextInt(randomValues.Length)];
                    int    randomHit = valueToDocId[queryTerm].First();
                    IList <StringBuilder> builders = new JCG.List <StringBuilder>();
                    foreach (String[] fieldValues in docs[randomHit].fieldValues)
                    {
                        StringBuilder builder = new StringBuilder();
                        bool          hit     = false;
                        for (int i = 0; i < fieldValues.Length; i++)
                        {
                            if (queryTerm.Equals(fieldValues[i], StringComparison.Ordinal))
                            {
                                builder.Append("<b>").Append(queryTerm).Append("</b>");
                                hit = true;
                            }
                            else
                            {
                                builder.Append(fieldValues[i]);
                            }
                            if (i != fieldValues.Length - 1)
                            {
                                builder.Append(' ');
                            }
                        }
                        if (hit)
                        {
                            builders.Add(builder);
                        }
                    }

                    FieldQuery     fq    = new FieldQuery(tq(queryTerm), true, true);
                    FieldTermStack stack = new FieldTermStack(reader, randomHit, F, fq);

                    FieldPhraseList       fpl  = new FieldPhraseList(stack, fq);
                    SimpleFragListBuilder sflb = new SimpleFragListBuilder(100);
                    FieldFragList         ffl  = sflb.CreateFieldFragList(fpl, 300);

                    SimpleFragmentsBuilder sfb = new SimpleFragmentsBuilder();
                    sfb.IsDiscreteMultiValueHighlighting = (true);
                    String[] actualFragments = sfb.CreateFragments(reader, randomHit, F, ffl, numFields);
                    assertEquals(builders.Count, actualFragments.Length);
                    for (int i = 0; i < actualFragments.Length; i++)
                    {
                        assertEquals(builders[i].ToString(), actualFragments[i]);
                    }
                }
            }
            finally
            {
                reader.Dispose();
                dir.Dispose();
            }
        }
 public override void Modify(FieldType fieldType, bool isInputType)
 {
     fieldType.Description = "Test custom description for field";
 }
Exemple #42
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="delList">是否删除明细数据(默认会删除明细)</param>
        /// <returns></returns>
        public virtual WebResponseContent Del(object[] keys, bool delList = true)
        {
            Type entityType  = typeof(T);
            var  keyProperty = entityType.GetKeyProperty();

            if (keyProperty == null || keys.Length == 0)
            {
                return(Response.Error(ResponseType.NoKeyDel));
            }

            IEnumerable <(bool, string, object)> validation = keyProperty.ValidationValueForDbType(keys);

            if (validation.Any(x => !x.Item1))
            {
                return(Response.Error(validation.Where(x => !x.Item1).Select(s => s.Item2 + "</br>").Serialize()));
            }
            string tKey = keyProperty.Name;

            if (string.IsNullOrEmpty(tKey))
            {
                return(Response.Error("没有主键不能删除"));
            }

            if (DelOnExecuting != null)
            {
                Response = DelOnExecuting(keys);
                if (!Response.Status)
                {
                    return(Response);
                }
            }

            FieldType fieldType = entityType.GetFieldType();
            string    joinKeys  = (fieldType == FieldType.Int || fieldType == FieldType.BigInt)
                 ? string.Join(",", keys)
                 : $"'{string.Join("','", keys)}'";

            string sql = $"DELETE FROM {entityType.Name } where {tKey} in ({joinKeys});";

            if (delList)
            {
                Type detailType = entityType.GetCustomAttribute <EntityAttribute>().DetailTable?[0];
                if (detailType != null)
                {
                    sql = sql + $"DELETE FROM {detailType.Name} where {tKey} in ({joinKeys});";
                }
            }
            //repository.DapperContext.ExcuteNonQuery(sql, CommandType.Text, null, true);

            //可能在删除后还要做一些其它数据库新增或删除操作,这样就可能需要与删除保持在同一个事务中处理
            //采用此方法 repository.DbContextBeginTransaction(()=>{//do delete......and other});
            //做的其他操作,在DelOnExecuted中加入委托实现
            repository.DbContextBeginTransaction(() =>
            {
                repository.ExecuteSqlCommand(sql);
                if (DelOnExecuted != null)
                {
                    Response = DelOnExecuted(keys);
                }
                return(Response);
            });
            if (Response.Status && string.IsNullOrEmpty(Response.Message))
            {
                Response.OK(ResponseType.DelSuccess);
            }
            return(Response);
        }
Exemple #43
0
        /// <summary>
        /// Adds a stored or un-stored <see cref="Int64Field"/> with the provided value.
        /// <para/>
        /// Expert: allows you to customize the <see cref="FieldType"/>.
        /// </summary>
        /// <param name="document">This <see cref="Document"/>.</param>
        /// <param name="name"> field name </param>
        /// <param name="value"> 64-bit <see cref="long"/> value </param>
        /// <param name="type"> customized field type: must have <see cref="FieldType.NumericType"/>
        ///         of <see cref="NumericType.INT64"/>. </param>
        /// <returns>The field that was added to this <see cref="Document"/>.</returns>
        /// <exception cref="ArgumentNullException"> if this <paramref name="document"/>, the field <paramref name="name"/> or <paramref name="type"/> is <c>null</c>. </exception>
        /// <exception cref="ArgumentException"> if the field type does not have a
        /// <see cref="FieldType.NumericType"/> of <see cref="NumericType.INT64"/> </exception>
        public static Int64Field AddInt64Field(this Document document, string name, long value, FieldType type)
        {
            if (document is null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            var field = new Int64Field(name, value, type);

            document.Add(field);
            return(field);
        }
Exemple #44
0
        public void SearchTypeToFieldTypeTest(ResourceId resource, SearchFilterType filterType, FieldType fieldType, SearchRequest request, PrivateApiResponseCode expectedCode, string description)
        {
            var handler  = new DefaultManager();
            var response = handler.Send <SearchResponse>(request);

            if (expectedCode == PrivateApiResponseCode.OK)
            {
                Assert.That(response, PrIs.SuccessfulResponse <SearchResponse>());
            }
            else
            {
                Assert.That(response, PrIs.ErrorResponse().And.ErrorCode((int)expectedCode).And.HttpCode(400));
            }
        }
        public void Build(FieldType contentQuery, ContentTypeDefinition contentTypeDefinition, ContentItemType contentItemType)
        {
            var serviceProvider       = _httpContextAccessor.HttpContext.RequestServices;
            var contentFieldProviders = serviceProvider.GetServices <IContentFieldProvider>().ToList();

            foreach (var part in contentTypeDefinition.Parts)
            {
                var partName = part.Name;

                // Check if another builder has already added a field for this part.
                if (contentItemType.HasField(partName))
                {
                    continue;
                }

                // This builder only handles parts with fields.
                if (!part.PartDefinition.Fields.Any())
                {
                    continue;
                }

                if (_contentOptions.ShouldSkip(part))
                {
                    continue;
                }

                if (_contentOptions.ShouldCollapse(part))
                {
                    foreach (var field in part.PartDefinition.Fields)
                    {
                        foreach (var fieldProvider in contentFieldProviders)
                        {
                            var fieldType = fieldProvider.GetField(field);

                            if (fieldType != null)
                            {
                                if (_contentOptions.ShouldSkip(fieldType.Type, fieldType.Name))
                                {
                                    continue;
                                }

                                contentItemType.AddField(fieldType);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    if (_dynamicPartFields.TryGetValue(partName, out var fieldType))
                    {
                        contentItemType.AddField(fieldType);
                    }
                    else
                    {
                        var field = contentItemType.Field(
                            typeof(DynamicPartGraphType),
                            partName.ToFieldName(),
                            description: S["Represents a {0}.", part.PartDefinition.Name],
                            resolve: context =>
                        {
                            var nameToResolve = partName;
                            var typeToResolve = context.ReturnType.GetType().BaseType.GetGenericArguments().First();

                            return(context.Source.Get(typeToResolve, nameToResolve));
                        });

                        field.ResolvedType           = new DynamicPartGraphType(_httpContextAccessor, part);
                        _dynamicPartFields[partName] = field;
                    }
                }
            }
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="fieldType">Type of the field</param>
 public FieldCreationInformation(FieldType fieldType)
 {
     FieldType = fieldType.ToString();
 }
 public FieldType CreateFieldType(FieldType ft)
 {
     return(_fieldrepository.CreateFieldType(ft));
 }
    private void OnGUI()
    {
        EditorGUILayout.LabelField("Player Preferences Editor", EditorStyles.boldLabel);
        EditorGUILayout.LabelField("by RomejanicDev");
        EditorGUILayout.Separator();

        fieldType = (FieldType)EditorGUILayout.EnumPopup("Key Type", fieldType);
        setKey    = EditorGUILayout.TextField("Key to Set", setKey);
        setVal    = EditorGUILayout.TextField("Value to Set", setVal);

        if (error != null)
        {
            EditorGUILayout.HelpBox(error, MessageType.Error);
        }

        if (GUILayout.Button("Set Key"))
        {
            if (fieldType == FieldType.Integer)
            {
                if (!int.TryParse(setVal, out int result))
                {
                    error = "Invalid input \"" + setVal + "\"";
                    return;
                }

                PlayerPrefs.SetInt(setKey, result);
            }
            else if (fieldType == FieldType.Float)
            {
                if (!float.TryParse(setVal, out float result))
                {
                    error = "Invalid input \"" + setVal + "\"";
                    return;
                }

                PlayerPrefs.SetFloat(setKey, result);
            }
            else
            {
                PlayerPrefs.SetString(setKey, setVal);
            }

            PlayerPrefs.Save();
            error = null;
        }

        if (GUILayout.Button("Get Key"))
        {
            if (fieldType == FieldType.Integer)
            {
                setVal = PlayerPrefs.GetInt(setKey).ToString();
            }
            else if (fieldType == FieldType.Float)
            {
                setVal = PlayerPrefs.GetFloat(setKey).ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                setVal = PlayerPrefs.GetString(setKey);
            }
        }

        if (GUILayout.Button("Delete Key"))
        {
            PlayerPrefs.DeleteKey(setKey);
            PlayerPrefs.Save();
        }

        if (GUILayout.Button("Delete All Keys"))
        {
            PlayerPrefs.DeleteAll();
            PlayerPrefs.Save();
        }
    }
Exemple #49
0
        public void WriteFieldNoTag(FieldType fieldType, object value)
        {
            switch (fieldType)
            {
            case FieldType.String:
                WriteStringNoTag((string)value);
                break;

            case FieldType.Message:
                WriteMessageNoTag((IMessageLite)value);
                break;

            case FieldType.Group:
                WriteGroupNoTag((IMessageLite)value);
                break;

            case FieldType.Bytes:
                WriteBytesNoTag((ByteString)value);
                break;

            case FieldType.Bool:
                WriteBoolNoTag((bool)value);
                break;

            case FieldType.Enum:
                if (value is Enum)
                {
                    WriteEnumNoTag((int)value);
                }
                else
                {
                    WriteEnumNoTag(((IEnumLite)value).Number);
                }
                break;

            case FieldType.Int32:
                WriteInt32NoTag((int)value);
                break;

            case FieldType.Int64:
                WriteInt64NoTag((long)value);
                break;

            case FieldType.UInt32:
                WriteUInt32NoTag((uint)value);
                break;

            case FieldType.UInt64:
                WriteUInt64NoTag((ulong)value);
                break;

            case FieldType.SInt32:
                WriteSInt32NoTag((int)value);
                break;

            case FieldType.SInt64:
                WriteSInt64NoTag((long)value);
                break;

            case FieldType.Fixed32:
                WriteFixed32NoTag((uint)value);
                break;

            case FieldType.Fixed64:
                WriteFixed64NoTag((ulong)value);
                break;

            case FieldType.SFixed32:
                WriteSFixed32NoTag((int)value);
                break;

            case FieldType.SFixed64:
                WriteSFixed64NoTag((long)value);
                break;

            case FieldType.Double:
                WriteDoubleNoTag((double)value);
                break;

            case FieldType.Float:
                WriteFloatNoTag((float)value);
                break;
            }
        }
Exemple #50
0
        public static ExecutionNode BuildExecutionNode(ExecutionNode parent, IGraphType graphType, Field field, FieldType fieldDefinition, string[] path = null)
        {
            path = path ?? AppendPath(parent.Path, field.Name);

            if (graphType is NonNullGraphType nonNullFieldType)
            {
                graphType = nonNullFieldType.ResolvedType;
            }

            switch (graphType)
            {
            case ListGraphType listGraphType:
                return(new ArrayExecutionNode(parent, graphType, field, fieldDefinition, path));

            case IObjectGraphType objectGraphType:
                return(new ObjectExecutionNode(parent, graphType, field, fieldDefinition, path));

            case IAbstractGraphType abstractType:
                return(new ObjectExecutionNode(parent, graphType, field, fieldDefinition, path));

            case ScalarGraphType scalarType:
                return(new ValueExecutionNode(parent, graphType, field, fieldDefinition, path));

            default:
                throw new InvalidOperationException($"Unexpected type: {graphType}");
            }
        }
Exemple #51
0
        public void WriteField(FieldType fieldType, int fieldNumber, string fieldName, object value)
        {
            switch (fieldType)
            {
            case FieldType.String:
                WriteString(fieldNumber, fieldName, (string)value);
                break;

            case FieldType.Message:
                WriteMessage(fieldNumber, fieldName, (IMessageLite)value);
                break;

            case FieldType.Group:
                WriteGroup(fieldNumber, fieldName, (IMessageLite)value);
                break;

            case FieldType.Bytes:
                WriteBytes(fieldNumber, fieldName, (ByteString)value);
                break;

            case FieldType.Bool:
                WriteBool(fieldNumber, fieldName, (bool)value);
                break;

            case FieldType.Enum:
                if (value is Enum)
                {
                    WriteEnum(fieldNumber, fieldName, (int)value, null /*not used*/);
                }
                else
                {
                    WriteEnum(fieldNumber, fieldName, ((IEnumLite)value).Number, null /*not used*/);
                }
                break;

            case FieldType.Int32:
                WriteInt32(fieldNumber, fieldName, (int)value);
                break;

            case FieldType.Int64:
                WriteInt64(fieldNumber, fieldName, (long)value);
                break;

            case FieldType.UInt32:
                WriteUInt32(fieldNumber, fieldName, (uint)value);
                break;

            case FieldType.UInt64:
                WriteUInt64(fieldNumber, fieldName, (ulong)value);
                break;

            case FieldType.SInt32:
                WriteSInt32(fieldNumber, fieldName, (int)value);
                break;

            case FieldType.SInt64:
                WriteSInt64(fieldNumber, fieldName, (long)value);
                break;

            case FieldType.Fixed32:
                WriteFixed32(fieldNumber, fieldName, (uint)value);
                break;

            case FieldType.Fixed64:
                WriteFixed64(fieldNumber, fieldName, (ulong)value);
                break;

            case FieldType.SFixed32:
                WriteSFixed32(fieldNumber, fieldName, (int)value);
                break;

            case FieldType.SFixed64:
                WriteSFixed64(fieldNumber, fieldName, (long)value);
                break;

            case FieldType.Double:
                WriteDouble(fieldNumber, fieldName, (double)value);
                break;

            case FieldType.Float:
                WriteFloat(fieldNumber, fieldName, (float)value);
                break;
            }
        }
 protected CorePropertyBase(FieldType type) : base(type)
 {
 }
Exemple #53
0
        static DocHelper()
        {
            CustomType  = new FieldType(TextField.TYPE_STORED);
            TextField1  = new Field(TEXT_FIELD_1_KEY, FIELD_1_TEXT, CustomType);
            CustomType2 = new FieldType(TextField.TYPE_STORED);
            CustomType2.StoreTermVectors         = true;
            CustomType2.StoreTermVectorPositions = true;
            CustomType2.StoreTermVectorOffsets   = true;
            TextField2            = new Field(TEXT_FIELD_2_KEY, FIELD_2_TEXT, CustomType2);
            CustomType3           = new FieldType(TextField.TYPE_STORED);
            CustomType3.OmitNorms = true;
            TextField3            = new Field(TEXT_FIELD_3_KEY, FIELD_3_TEXT, CustomType3);
            KeyField                     = new StringField(KEYWORD_FIELD_KEY, KEYWORD_TEXT, Field.Store.YES);
            CustomType5                  = new FieldType(TextField.TYPE_STORED);
            CustomType5.OmitNorms        = true;
            CustomType5.Tokenized        = false;
            NoNormsField                 = new Field(NO_NORMS_KEY, NO_NORMS_TEXT, CustomType5);
            CustomType6                  = new FieldType(TextField.TYPE_STORED);
            CustomType6.IndexOptions     = FieldInfo.IndexOptions.DOCS_ONLY;
            NoTFField                    = new Field(NO_TF_KEY, NO_TF_TEXT, CustomType6);
            CustomType7                  = new FieldType();
            CustomType7.Stored           = true;
            UnIndField                   = new Field(UNINDEXED_FIELD_KEY, UNINDEXED_FIELD_TEXT, CustomType7);
            CustomType8                  = new FieldType(TextField.TYPE_NOT_STORED);
            CustomType8.StoreTermVectors = true;
            UnStoredField2               = new Field(UNSTORED_FIELD_2_KEY, UNSTORED_2_FIELD_TEXT, CustomType8);

            UnStoredField1 = new TextField(UNSTORED_FIELD_1_KEY, UNSTORED_1_FIELD_TEXT, Field.Store.NO);
            LazyField      = new Field(LAZY_FIELD_KEY, LAZY_FIELD_TEXT, CustomType);
            TextUtfField1  = new Field(TEXT_FIELD_UTF1_KEY, FIELD_UTF1_TEXT, CustomType);
            TextUtfField2  = new Field(TEXT_FIELD_UTF2_KEY, FIELD_UTF2_TEXT, CustomType2);

            Fields = new Field[] { TextField1, TextField2, TextField3, KeyField, NoNormsField, NoTFField, UnIndField, UnStoredField1, UnStoredField2, TextUtfField1, TextUtfField2, LazyField, LazyFieldBinary, LargeLazyField };

            //Initialize the large Lazy Field
            StringBuilder buffer = new StringBuilder();

            for (int i = 0; i < 10000; i++)
            {
                buffer.Append("Lazily loading lengths of language in lieu of laughing ");
            }

            try
            {
                LAZY_FIELD_BINARY_BYTES = "These are some binary field bytes".GetBytes(IOUtils.CHARSET_UTF_8);
            }
            catch (EncoderFallbackException e)
            {
            }
            LazyFieldBinary           = new StoredField(LAZY_FIELD_BINARY_KEY, LAZY_FIELD_BINARY_BYTES);
            Fields[Fields.Length - 2] = LazyFieldBinary;
            LARGE_LAZY_FIELD_TEXT     = buffer.ToString();
            LargeLazyField            = new Field(LARGE_LAZY_FIELD_KEY, LARGE_LAZY_FIELD_TEXT, CustomType);
            Fields[Fields.Length - 1] = LargeLazyField;
            for (int i = 0; i < Fields.Length; i++)
            {
                IndexableField f = Fields[i];
                Add(All, f);
                if (f.FieldType.Indexed)
                {
                    Add(Indexed, f);
                }
                else
                {
                    Add(Unindexed, f);
                }
                if (f.FieldType.StoreTermVectors)
                {
                    Add(Termvector, f);
                }
                if (f.FieldType.Indexed && !f.FieldType.StoreTermVectors)
                {
                    Add(Notermvector, f);
                }
                if (f.FieldType.Stored)
                {
                    Add(Stored, f);
                }
                else
                {
                    Add(Unstored, f);
                }
                if (f.FieldType.IndexOptions == FieldInfo.IndexOptions.DOCS_ONLY)
                {
                    Add(NoTf, f);
                }
                if (f.FieldType.OmitNorms)
                {
                    Add(NoNorms, f);
                }
                if (f.FieldType.IndexOptions == FieldInfo.IndexOptions.DOCS_ONLY)
                {
                    Add(NoTf, f);
                }
                //if (f.isLazy()) add(lazy, f);
            }
            NameValues = new Dictionary <string, object>();
            NameValues[TEXT_FIELD_1_KEY]      = FIELD_1_TEXT;
            NameValues[TEXT_FIELD_2_KEY]      = FIELD_2_TEXT;
            NameValues[TEXT_FIELD_3_KEY]      = FIELD_3_TEXT;
            NameValues[KEYWORD_FIELD_KEY]     = KEYWORD_TEXT;
            NameValues[NO_NORMS_KEY]          = NO_NORMS_TEXT;
            NameValues[NO_TF_KEY]             = NO_TF_TEXT;
            NameValues[UNINDEXED_FIELD_KEY]   = UNINDEXED_FIELD_TEXT;
            NameValues[UNSTORED_FIELD_1_KEY]  = UNSTORED_1_FIELD_TEXT;
            NameValues[UNSTORED_FIELD_2_KEY]  = UNSTORED_2_FIELD_TEXT;
            NameValues[LAZY_FIELD_KEY]        = LAZY_FIELD_TEXT;
            NameValues[LAZY_FIELD_BINARY_KEY] = LAZY_FIELD_BINARY_BYTES;
            NameValues[LARGE_LAZY_FIELD_KEY]  = LARGE_LAZY_FIELD_TEXT;
            NameValues[TEXT_FIELD_UTF1_KEY]   = FIELD_UTF1_TEXT;
            NameValues[TEXT_FIELD_UTF2_KEY]   = FIELD_UTF2_TEXT;
        }
        public CartType(ICartAvailMethodsService cartAvailMethods)
        {
            Field(x => x.Cart.Id, nullable: true).Description("Shopping cart Id");
            Field(x => x.Cart.Name, nullable: false).Description("Shopping cart name");
            Field(x => x.Cart.Status, nullable: true).Description("Shopping cart status");
            Field(x => x.Cart.StoreId, nullable: true).Description("Shopping cart store id");
            Field(x => x.Cart.ChannelId, nullable: true).Description("Shopping cart channel id");
            Field <BooleanGraphType>("hasPhysicalProducts", resolve: context => AbstractTypeFactory <CartHasPhysicalProductsSpecification> .TryCreateInstance().IsSatisfiedBy(context.Source.Cart));
            Field(x => x.Cart.IsAnonymous, nullable: true).Description("Sign that shopping cart is anonymous");
            //Field(x => x.Customer, nullable: true).Description("Shopping cart user"); //todo: add resolver
            Field(x => x.Cart.CustomerId, nullable: true).Description("Shopping cart user id");
            Field(x => x.Cart.CustomerName, nullable: true).Description("Shopping cart user name");
            Field(x => x.Cart.OrganizationId, nullable: true).Description("Shopping cart organization id");
            Field(x => x.Cart.IsRecuring, nullable: true).Description("Sign that shopping cart is recurring");
            Field(x => x.Cart.Comment, nullable: true).Description("Shopping cart text comment");

            // Characteristics
            Field(x => x.Cart.VolumetricWeight, nullable: true).Description("Shopping cart value of volumetric weight");
            Field(x => x.Cart.WeightUnit, nullable: true).Description("Shopping cart value of weight unit");
            Field(x => x.Cart.Weight, nullable: true).Description("Shopping cart value of shopping cart weight");
            //TODO:
            //Field(x => x.MeasureUnit, nullable: true).Description("Shopping cart value of measurement unit");
            //Field(x => x.Height, nullable: true).Description("Shopping cart value of height");
            //Field(x => x.Length, nullable: true).Description("Shopping cart value of length");
            //Field(x => x.Width, nullable: true).Description("Shopping cart value of width");

            // Money
            Field <MoneyType>("total", resolve: context => context.Source.Cart.Total.ToMoney(context.Source.Currency));
            Field <MoneyType>("subTotal", resolve: context => context.Source.Cart.SubTotal.ToMoney(context.Source.Currency));
            Field <MoneyType>("subTotalWithTax", resolve: context => context.Source.Cart.SubTotalWithTax.ToMoney(context.Source.Currency));
            Field <MoneyType>("extendedPriceTotal", resolve: context => context.Source.Cart.Items.Sum(i => i.ExtendedPrice).ToMoney(context.Source.Currency));
            Field <MoneyType>("extendedPriceTotalWithTax", resolve: context => context.Source.Cart.Items.Sum(i => i.ExtendedPriceWithTax).ToMoney(context.Source.Currency));
            Field <CurrencyType>("currency", resolve: context => context.Source.Currency);
            Field <MoneyType>("taxTotal", resolve: context => context.Source.Cart.TaxTotal.ToMoney(context.Source.Currency));
            Field(x => x.Cart.TaxPercentRate, nullable: true).Description("Tax percent rate");
            Field(x => x.Cart.TaxType, nullable: true).Description("Shipping tax type");
            Field <ListGraphType <TaxDetailType> >("taxDetails", resolve: context => context.Source.Cart.TaxDetails);

            // Shipping
            Field <MoneyType>("shippingPrice", resolve: context => context.Source.Cart.ShippingTotal.ToMoney(context.Source.Currency));
            Field <MoneyType>("shippingPriceWithTax", resolve: context => context.Source.Cart.ShippingTotalWithTax.ToMoney(context.Source.Currency));
            Field <MoneyType>("shippingTotal", resolve: context => context.Source.Cart.ShippingTotal.ToMoney(context.Source.Currency));
            Field <MoneyType>("shippingTotalWithTax", resolve: context => context.Source.Cart.ShippingTotalWithTax.ToMoney(context.Source.Currency));
            //Field<ListGraphType<ShipmentType>>("shipments", resolve: context => context.Source.Cart.Shipments);
            //TODO: By this registration we support the schema types extensions. Need to move this code into extensions and replace everywhere to this version.
            var cartShipmentsField = new FieldType
            {
                Name     = "shipments",
                Type     = typeof(ListGraphType <>).MakeGenericType(GraphTypeExtenstionHelper.GetActualType <ShipmentType>()),
                Resolver = new FuncFieldResolver <CartAggregate, object>(context => context.Source.Cart.Shipments)
            };

            AddField(cartShipmentsField);

            FieldAsync <ListGraphType <ShippingMethodType> >("availableShippingMethods", resolve: async context =>
            {
                var rates = await cartAvailMethods.GetAvailableShippingRatesAsync(context.Source);
                //store the pair ShippingMethodType and cart aggregate in the user context for future usage in the ShippingMethodType fields resolvers
                if (rates != null)
                {
                    rates.Apply(x => context.UserContext[x.GetCacheKey()] = context.Source);
                }
                return(rates);
            });

            // Payment
            Field <MoneyType>("paymentPrice", resolve: context => context.Source.Cart.PaymentTotal.ToMoney(context.Source.Currency));
            Field <MoneyType>("paymentPriceWithTax", resolve: context => context.Source.Cart.PaymentTotalWithTax.ToMoney(context.Source.Currency));
            Field <MoneyType>("paymentTotal", resolve: context => context.Source.Cart.PaymentTotal.ToMoney(context.Source.Currency));
            Field <MoneyType>("paymentTotalWithTax", resolve: context => context.Source.Cart.PaymentTotalWithTax.ToMoney(context.Source.Currency));
            Field <ListGraphType <PaymentType> >("payments", resolve: context => context.Source.Cart.Payments);
            FieldAsync <ListGraphType <PaymentMethodType> >("availablePaymentMethods", resolve: async context =>
            {
                var methods = await cartAvailMethods.GetAvailablePaymentMethodsAsync(context.Source);
                //store the pair ShippingMethodType and cart aggregate in the user context for future usage in the ShippingMethodType fields resolvers
                if (methods != null)
                {
                    methods.Apply(x => context.UserContext[x.Id] = context.Source);
                }
                return(methods);
            });
            //TODO:
            //Field<ListGraphType<PaymentPlanType>>("paymentPlan", resolve: context => context.Source.PaymentPlan);

            // Extended money
            //TODO:
            //Field<MoneyType>("extendedPriceTotal", resolve: context => context.Source.ExtendedPriceTotal);
            //Field<MoneyType>("extendedPriceTotalWithTax", resolve: context => context.Source.ExtendedPriceTotalWithTax);

            // Handling totals
            Field <MoneyType>("handlingTotal", resolve: context => context.Source.Cart.HandlingTotal.ToMoney(context.Source.Currency));
            Field <MoneyType>("handlingTotalWithTax", resolve: context => context.Source.Cart.HandlingTotalWithTax.ToMoney(context.Source.Currency));

            // Discounts
            Field <MoneyType>("discountTotal", resolve: context => context.Source.Cart.DiscountTotal.ToMoney(context.Source.Currency));
            Field <MoneyType>("discountTotalWithTax", resolve: context => context.Source.Cart.DiscountTotalWithTax.ToMoney(context.Source.Currency));
            Field <ListGraphType <DiscountType> >("discounts", resolve: context => context.Source.Cart.Discounts);

            // Addresses
            Field <ListGraphType <AddressType> >("addresses", resolve: context => context.Source.Cart.Addresses);

            // Items
            Field <ListGraphType <LineItemType> >("items", resolve: context => context.Source.Cart.Items);

            Field <IntGraphType>("itemsCount", "Count of different items", resolve: context => context.Source.Cart.Items.Count);
            Field <IntGraphType>("itemsQuantity", "Quantity of items", resolve: context => context.Source.Cart.Items.Sum(x => x.Quantity));
            //TODO:
            //Field<LineItemType>("recentlyAddedItem", resolve: context => context.Source.Cart.RecentlyAddedItem);

            // Coupons
            Field <ListGraphType <CouponType> >("coupons", resolve: context => context.Source.Coupons);

            // Other
            //Field<ListGraphType<DynamicPropertyType>>("dynamicProperties", resolve: context => context.Source.DynamicProperties); //todo add dynamic properties
            //TODO:
            Field(x => x.IsValid, nullable: true).Description("Is cart valid");
            Field <ListGraphType <ValidationErrorType> >("validationErrors", resolve: context => context.Source.ValidationErrors.OfType <CartValidationError>());
            Field(x => x.Cart.Type, nullable: true).Description("Shopping cart type");
        }
Exemple #55
0
            int MakeRealObject(ITsString tssTyped)
            {
                // Figure whether owning atomic or owning collection or owning sequence. Throw if none.
                IFwMetaDataCache mdc   = m_fdoCache.MetaDataCacheAccessor;
                FieldType        iType = m_fdoCache.GetFieldType(m_flidEmptyProp);

                iType &= FieldType.kcptVirtualMask;
                ISilDataAccess sdaReal = m_fdoCache.MainCacheAccessor;
                // Make a new object of the specified class in the specified property.
                int ord = 0;

                switch (iType)
                {
                default:
                    throw new Exception("ghost string property must be owning object property");

                case FieldType.kcptOwningAtom:
                    ord = -2;
                    break;

                case FieldType.kcptOwningCollection:
                    ord = -1;
                    break;

                case FieldType.kcptOwningSequence:
                    // ord = 0 set above (inserting the first and only object at position 0).
                    break;
                }
                string sClassRaw = mdc.GetClassName((uint)m_clidDst);
                string sClass    = m_mediator.StringTbl.GetString(sClassRaw, "ClassNames");
                string sUndo     = String.Format(DetailControlsStrings.ksUndoCreate0, sClass);
                string sRedo     = String.Format(DetailControlsStrings.ksRedoCreate0, sClass);

                sdaReal.BeginUndoTask(sUndo, sRedo);
                int hvoNewObj = sdaReal.MakeNewObject((int)m_clidDst, m_hvoObj, m_flidEmptyProp, ord);
                // Set its property m_flidStringProp to tssTyped. If it is multilingual, choose based on ghostWs.
                FieldType iTypeString = m_fdoCache.GetFieldType(m_flidStringProp);

                iTypeString &= FieldType.kcptVirtualMask;
                switch (iTypeString)
                {
                default:
                    throw new Exception("ghost property must store strings!");

                case FieldType.kcptMultiString:
                case FieldType.kcptMultiBigString:
                case FieldType.kcptMultiUnicode:
                case FieldType.kcptMultiBigUnicode:
                    sdaReal.SetMultiStringAlt(hvoNewObj, m_flidStringProp, m_wsToCreate, tssTyped);
                    break;

                case FieldType.kcptString:
                case FieldType.kcptBigString:
                    sdaReal.SetString(hvoNewObj, m_flidStringProp, tssTyped);
                    break;
                }

                string ghostInitMethod = XmlUtils.GetOptionalAttributeValue(m_nodeObjProp, "ghostInitMethod");

                if (ghostInitMethod != null)
                {
                    ICmObject obj     = CmObject.CreateFromDBObject(m_fdoCache, hvoNewObj);
                    Type      objType = obj.GetType();
                    System.Reflection.MethodInfo mi = objType.GetMethod(ghostInitMethod);
                    mi.Invoke(obj, null);
                }
                // Issue PropChanged for the addition of the new object. (could destroy this).
                sdaReal.PropChanged(null, (int)PropChangeType.kpctNotifyAll, m_hvoObj, m_flidEmptyProp, 0, 1, 0);
                sdaReal.EndUndoTask();
                return(hvoNewObj);
            }
        public static void SetColumnDefaultValue(string tableName, string columnName, FieldType type, object value, bool overrideNulls)
        {
            using (var connection = DbContext.Current.CreateConnection())
            {
                var defVal = ConvertDefaultValue(type, value);
                if (value != null && overrideNulls)
                {
                    string updateNullRecordsSql = $"UPDATE \"{tableName}\" SET \"{columnName}\" = {defVal} WHERE \"{columnName}\" IS NULL";
                    var    updateCommand        = connection.CreateCommand(updateNullRecordsSql);
                    updateCommand.ExecuteNonQuery();
                }

                string sql     = $"ALTER TABLE ONLY \"{tableName}\" ALTER COLUMN \"{columnName}\" SET DEFAULT {defVal}";
                var    command = connection.CreateCommand(sql);
                command.ExecuteNonQuery();
            }
        }
Exemple #57
0
    void AddField(List <string> list, Field field, SelectionSet selectionSet, string?parentPath, FieldType fieldType, IReadOnlyList <Navigation> parentNavigationProperties, IResolveFieldContext context, IComplexGraphType?graph = null)
    {
        if (graph == null && !fieldType.TryGetComplexGraph(out graph))
        {
            return;
        }

        var subFields = selectionSet.Selections.OfType <Field>().ToList();

        foreach (var inlineFragment in selectionSet.Selections.OfType <InlineFragment>())
        {
            if (inlineFragment.Type.GraphTypeFromType(context.Schema) is IComplexGraphType graphFragment)
            {
                AddField(list, field, inlineFragment.SelectionSet, parentPath, fieldType, parentNavigationProperties, context, graphFragment);
            }
        }

        foreach (var fragmentSpread in selectionSet.Selections.OfType <FragmentSpread>())
        {
            var fragmentDefinition = context.Fragments.FindDefinition(fragmentSpread.Name);
            if (fragmentDefinition == null)
            {
                continue;
            }

            AddField(list, field, fragmentDefinition.SelectionSet, parentPath, fieldType, parentNavigationProperties, context, graph);
        }

        if (IsConnectionNode(field) || field == context.FieldAst)
        {
            if (subFields.Count > 0)
            {
                ProcessSubFields(list, parentPath, subFields, graph !, parentNavigationProperties, context);
            }

            return;
        }

        if (!fieldType.TryGetEntityTypeForField(out var entityType))
        {
            return;
        }

        if (!TryGetIncludeMetadata(fieldType, out var includeNames))
        {
            return;
        }

        //todo: do a single check to avoid allocations
        var paths = GetPaths(parentPath, includeNames).ToList();

        foreach (var path in paths)
        {
            list.Add(path);
        }

        ProcessSubFields(list, paths.First(), subFields, graph !, navigations[entityType !], context);
 public static T Deserialize <T>(FieldDefinition def, FieldType type, byte[] buffer)
 {
     return(Deserialize <T>(def, type, buffer, 0, buffer.Length));
 }
Exemple #59
0
        public int UpdateAddress(Address addr, FieldType field, string value)
        {
            int response = 0;

            try
            {
                switch (field)
                {
                case FieldType.STARTDATE:
                    throw new Exception("Start date cannot be updated.");

                case FieldType.ENDDATE:
                    throw new Exception("End date cannot be updated.");

                case FieldType.ADDRESS1:
                    if (value.Length > 50)
                    {
                        throw new Exception("Invalid string length for Address1.");
                    }
                    else
                    {
                        addr.Address1 = value;
                    }
                    break;

                case FieldType.ADDRESS2:
                    if (value?.Length > 20)
                    {
                        throw new Exception("Invalid string length for Address2.");
                    }
                    else
                    {
                        addr.Address2 = value;
                    }
                    break;

                case FieldType.CITY:
                    if (value.Length > 20)
                    {
                        throw new Exception("Invalid string length for City.");
                    }
                    else
                    {
                        addr.City = value;
                    }
                    break;

                case FieldType.STATE:
                    if (value.Length == 2)
                    {
                        addr.State = value;
                    }
                    else
                    {
                        throw new Exception("Invalid string length for State.");
                    }
                    break;

                case FieldType.ZIP5:
                    if (value.Length != 5)
                    {
                        throw new Exception("Invalid string length for Zip5.");
                    }
                    else
                    {
                        addr.Zip5 = value;
                    }
                    break;

                case FieldType.ZIP4:
                    if (value != null && value.Length != 4)
                    {
                        throw new Exception("Invalid string length for Zip4.");
                    }
                    else
                    {
                        addr.Zip4 = value;
                    }
                    break;

                default:
                    throw new Exception("Invalid field type.");
                }

                response = Update(addr);

                if (response != 1)
                {
                    throw new Exception("Update operation affected other than one row.");
                }
            }
            catch (Exception ex)
            {
                InputOutput logger = InputOutput.GetInstance();

                ex.Data.Add("Class:", "DataRepo");
                ex.Data.Add("Method:", "UpdateAddress(Address addr, FieldType field, string value)");
                ex.Data.Add("StartDate:", addr.StartDate);
                ex.Data.Add("EndDate:", addr.EndDate);
                ex.Data.Add("Address:", addr.Address1);
                ex.Data.Add("value:", value);

                logger.WriteLogFile(ex);
            }

            return(response);
        }
Exemple #60
0
        public static Cell MakeFieldCell(FieldType type, string label, string value,
                                         TableSection fieldsSection, Page page)
        {
            Cell           cell;
            FormEntryCell  feCell = null;
            FormSwitchCell fsCell = null;

            switch (type)
            {
            case FieldType.Text:
            case FieldType.Hidden:
                var hidden = type == FieldType.Hidden;
                cell = feCell = new FormEntryCell(label, isPassword: hidden,
                                                  button1: hidden ? "eye.png" : "cog_alt.png", button2: hidden ? "cog_alt.png" : null);
                feCell.Entry.Text = value;
                feCell.Entry.DisableAutocapitalize = true;
                feCell.Entry.Autocorrect           = false;

                if (hidden)
                {
                    feCell.Entry.FontFamily = OnPlatform(iOS: "Menlo-Regular", Android: "monospace",
                                                         Windows: "Courier");
                    feCell.Button1.Command = new Command(() =>
                    {
                        feCell.Entry.InvokeToggleIsPassword();
                        feCell.Button1.Image = "eye" +
                                               (!feCell.Entry.IsPasswordFromToggled ? "_slash" : string.Empty) + ".png";
                    });
                }
                break;

            case FieldType.Boolean:
                cell = fsCell = new FormSwitchCell(label, "cog_alt.png");
                fsCell.Switch.IsToggled = value == "true";
                break;

            default:
                cell = null;
                break;
            }

            if (cell != null)
            {
                var optionsButton = feCell != null ? feCell.Button2 ?? feCell.Button1 : fsCell.Button1;
                optionsButton.Command = new Command(async() =>
                {
                    var optionsVal = await page.DisplayActionSheet(AppResources.Options, AppResources.Cancel,
                                                                   null, AppResources.Edit, AppResources.Remove);
                    if (optionsVal == AppResources.Remove)
                    {
                        if (fieldsSection.Contains(cell))
                        {
                            fieldsSection.Remove(cell);
                        }

                        if (feCell != null)
                        {
                            feCell.Dispose();
                        }
                        cell   = null;
                        feCell = null;
                        fsCell = null;
                    }
                    else if (optionsVal == AppResources.Edit)
                    {
                        var existingLabel = feCell?.Label.Text ?? fsCell?.Label.Text;
                        var daService     = Resolver.Resolve <IDeviceActionService>();
                        var editLabel     = await daService.DisplayPromptAync(AppResources.CustomFieldName,
                                                                              null, existingLabel);
                        if (editLabel != null)
                        {
                            if (feCell != null)
                            {
                                feCell.Label.Text = editLabel;
                            }
                            else if (fsCell != null)
                            {
                                fsCell.Label.Text = editLabel;
                            }
                        }
                    }
                });
            }

            return(cell);
        }