Пример #1
0
        internal static void ProductProc(IDataReader dr, FieldDictionary Fields, object Param)
        {
            ProductCollection coll = Param as ProductCollection;
            Product           item = Mapper.ReadProduct(dr, Fields);

            coll.Add(item);
        }
Пример #2
0
        /// <summary>
        ///     生成分页的SQL
        /// </summary>
        /// <param name="page">页号</param>
        /// <param name="pageSize">每页几行(强制大于0,小于500行)</param>
        /// <param name="order">排序字段</param>
        /// <param name="desc">是否倒序</param>
        /// <param name="condition">数据条件</param>
        /// <returns></returns>
        private string CreatePageSql(int page, int pageSize, string order, bool desc, string condition)
        {
            var orderField = string.IsNullOrWhiteSpace(order) || !FieldDictionary.ContainsKey(order)
                ? KeyField
                : FieldDictionary[order];

            var sql = new StringBuilder();

            sql.Append($@"SELECT {ContextLoadFields}
FROM {ContextReadTable}{ConditionSqlCode(condition)}
ORDER BY `{orderField}` {(desc ? "DESC" : "ASC")}");

            if (pageSize >= 0)
            {
                if (page <= 0)
                {
                    page = 1;
                }
                if (pageSize == 0)
                {
                    pageSize = 20;
                }
                else if (pageSize > 500)
                {
                    pageSize = 500;
                }
                sql.Append($" LIMIT {(page - 1) * pageSize},{pageSize}");
            }
            sql.Append(";");
            return(sql.ToString());
        }
Пример #3
0
 public override void ApplyValues(FieldDictionary fields)
 {
     this.ID           = fields.GetValue <int>("TestFlowID", -1);
     this.Name         = fields.GetValue <string>("TestFlowName");
     this.DateCreated  = fields.GetValue <string>("DateCreated", DateTime.MinValue);
     this.DateModified = fields.GetValue <string>("DateModified", DateTime.MinValue);
 }
Пример #4
0
        internal static void OrderProc(IDataReader dr, FieldDictionary Fields, object Param)
        {
            OrderCollection coll = Param as OrderCollection;
            Order           item = Mapper.ReadOrder(dr, Fields);

            coll.Add(item);
        }
Пример #5
0
 public override void ApplyValues(FieldDictionary fields)
 {
     this.ID                  = fields.GetValue <int>("TestID", -1);
     this.TestType            = fields.GetThing <TestType>("TestTypeID");
     this.Status              = fields.GetThing <TestStatus>("Status", TestStatus.Pending);
     this.Metadata.Definition = fields.GetValue <string>("Metadata");
     this.DateCreated         = fields.GetValue <DateTime>("DateCreated", DateTime.MinValue);
     this.DateUpdated         = fields.GetValue <DateTime>("DateUpdated", DateTime.MinValue);
 }
Пример #6
0
        /// <summary>
        /// Get the column metatada from the DataReader and store it in a Dictionary
        /// This Dictionary could be cached for better performances
        /// </summary>
        /// <param name="dr">IDataReader from which obtaining metadata</param>
        /// <returns>The dictionary</returns>
        public static FieldDictionary GetFields(IDataReader dr)
        {
            int             FieldCount = dr.FieldCount;
            FieldDictionary dic        = new FieldDictionary(FieldCount);

            for (int i = 0; i < FieldCount; i++)
            {
                dic.Add(dr.GetName(i), i);
            }
            return(dic);
        }
Пример #7
0
        private string GetField(Field salesForceField)
        {
            var valueFound = FieldDictionary.TryGetValue(salesForceField.type, out var value);

            if (valueFound)
            {
                return(value);
            }
            Log.Logger.Error($"Field Type: {salesForceField.type} Field Name : {salesForceField.name} Field Length: {salesForceField.length}");
            return("NOT FOUND");
        }
Пример #8
0
        /// <summary>
        ///     生成分页的SQL
        /// </summary>
        /// <param name="page">页号</param>
        /// <param name="pageSize">每页几行(强制大于0,小于500行)</param>
        /// <param name="order">排序字段</param>
        /// <param name="desc">是否倒序</param>
        /// <param name="condition">数据条件</param>
        /// <returns></returns>
        private string CreatePageSql(int page, int pageSize, string order, bool desc, string condition)
        {
            var orderField = string.IsNullOrWhiteSpace(order) || !FieldDictionary.ContainsKey(order)
                ? KeyField
                : FieldDictionary[order];

            var sql = new StringBuilder();

            CreateLoadSql(sql, ContextLoadFields, condition, orderField, desc, pageSize, page);
            return(sql.ToString());
        }
Пример #9
0
        internal static OrderDetail ReadOrderDetail(IDataReader dr, FieldDictionary Fields)
        {
            OrderDetail item = new OrderDetail();

            item.OrderID   = Values.GetInt32(dr, Fields, "OrderID");
            item.ProductID = Values.GetInt32(dr, Fields, "ProductID");
            item.UnitPrice = Values.GetDecimal(dr, Fields, "UnitPrice");
            item.Quantity  = Values.GetInt32(dr, Fields, "Quantity");
            item.Discount  = Values.GetDecimal(dr, Fields, "Discount");
            return(item);
        }
Пример #10
0
        internal string GetFieldType(Field salesForceField, string objectName = "Not specified")
        {
            var valueFound = FieldDictionary.TryGetValue(salesForceField.type, out var value);

            if (valueFound)
            {
                return(value);
            }
            Log.Logger.Fatal($"ObjectName: {objectName} Field Type: {salesForceField.type} Field Name : {salesForceField.name} Field Length: {salesForceField.length}");
            return("string");
        }
Пример #11
0
        // Main parent method which calls the other methods
        public void initSnapView(SnapView sv)
        {
            // First load the xml from disk, and validate against the xsd
            loadAndValidateXml();

            // Then given the schema read in from the xsd, pull out the meta-data
            FieldDictionary dict = fillFieldDictionary(fsSchema, sv);

            // Set the meta-data for the SnapView
            sv.setDict(dict);

            // Finally, pull out the table from the xml file
            fillSnapViewTable(sv);
        } //method
Пример #12
0
        internal static Product ReadProduct(IDataReader dr, FieldDictionary Fields)
        {
            Product item = new Product();

            item.ProductID       = Values.GetInt32(dr, Fields, "ProductID");
            item.ProductName     = Values.GetString(dr, Fields, "ProductName");
            item.SupplierID      = Values.GetInt32(dr, Fields, "SupplierID");
            item.CategoryID      = Values.GetInt32(dr, Fields, "CategoryID");
            item.QuantityPerUnit = Values.GetString(dr, Fields, "QuantityPerUnit");
            item.UnitPrice       = Values.GetDecimal(dr, Fields, "UnitPrice");
            item.UnitsInStock    = Values.GetInt32(dr, Fields, "UnitsInStock");
            item.UnitsOnOrder    = Values.GetInt32(dr, Fields, "UnitsOnOrder");
            item.Discontinued    = Values.GetBoolean(dr, Fields, "Discontinued");
            return(item);
        }
Пример #13
0
        /// <summary>
        ///     生成分页的SQL
        /// </summary>
        /// <param name="page">页号</param>
        /// <param name="pageSize">每页几行(强制大于0,小于500行)</param>
        /// <param name="order">排序字段</param>
        /// <param name="desc">是否倒序</param>
        /// <param name="condition">数据条件</param>
        /// <returns></returns>
        private string CreatePageSql(int page, int pageSize, string order, bool desc, string condition)
        {
            if (pageSize <= 0 || page < 0)
            {
                return(CreateLoadSql(condition, $@" [{order}] {(desc ? "DESC" : "ASC")}"));
            }
            var orderField = string.IsNullOrWhiteSpace(order) || !FieldDictionary.ContainsKey(order)
                ? KeyField
                : FieldDictionary[order];

            return($@"SELECT * FROM (
    SELECT {ContextLoadFields},
           ROW_NUMBER() OVER (ORDER BY [{orderField}] {(desc ? "DESC" : "ASC")}) AS __rs
      FROM {ContextReadTable}{ConditionSqlCode(condition)}
) t WHERE __rs > {(page - 1) * pageSize} AND __rs <= {page * pageSize};");
        }
Пример #14
0
        internal static Customer ReadCustomer(IDataReader dr, FieldDictionary Fields)
        {
            Customer item = new Customer();

            item.CustomerID   = Values.GetString(dr, Fields, "CustomerID");
            item.CompanyName  = Values.GetString(dr, Fields, "CompanyName");
            item.ContactName  = Values.GetString(dr, Fields, "ContactName");
            item.ContactTitle = Values.GetString(dr, Fields, "ContactTitle");
            item.Address      = Values.GetString(dr, Fields, "Address");
            item.City         = Values.GetString(dr, Fields, "City");
            item.Region       = Values.GetString(dr, Fields, "Region");
            item.PostalCode   = Values.GetString(dr, Fields, "PostalCode");
            item.Country      = Values.GetString(dr, Fields, "Country");
            item.Phone        = Values.GetString(dr, Fields, "Phone");
            item.Fax          = Values.GetString(dr, Fields, "Fax");
            return(item);
        }
Пример #15
0
        protected virtual bool IsFieldMatch(string sourceFieldValue, FieldDictionary targetFields, string fieldId)
        {
            // note that returning "true" means the values DO NOT MATCH EACH OTHER.

            if (sourceFieldValue == null)
            {
                return(false);
            }

            // it's a "match" if the target item does not contain the source field
            string targetFieldValue;

            if (!targetFields.TryGetValue(fieldId, out targetFieldValue))
            {
                return(true);
            }

            return(!sourceFieldValue.Equals(targetFieldValue));
        }
Пример #16
0
        internal static Order ReadOrder(IDataReader dr, FieldDictionary Fields)
        {
            Order item = new Order();

            item.OrderID        = Values.GetInt32(dr, Fields, "OrderID");
            item.CustomerID     = Values.GetString(dr, Fields, "CustomerID");
            item.EmployeeID     = Values.GetInt32(dr, Fields, "EmployeeID");
            item.OrderDate      = Values.GetDateTime(dr, Fields, "OrderDate");
            item.RequiredDate   = Values.GetDateTime(dr, Fields, "RequiredDate");
            item.ShippedDate    = Values.GetDateTime(dr, Fields, "ShippedDate");
            item.ShipVia        = Values.GetInt32(dr, Fields, "ShipVia");
            item.Freight        = Values.GetDecimal(dr, Fields, "Freight");
            item.ShipName       = Values.GetString(dr, Fields, "ShipName");
            item.ShipAddress    = Values.GetString(dr, Fields, "ShipAddress");
            item.ShipCity       = Values.GetString(dr, Fields, "ShipCity");
            item.ShipRegion     = Values.GetString(dr, Fields, "ShipRegion");
            item.ShipPostalCode = Values.GetString(dr, Fields, "ShipPostalCode");
            item.ShipCountry    = Values.GetString(dr, Fields, "ShipCountry");
            return(item);
        }
Пример #17
0
        protected virtual bool AnyFieldMatch(FieldDictionary sourceFields, FieldDictionary targetFields, ISourceItem existingItem, ISerializedItem serializedItem, DeferredLogWriter <ISerializedAsMasterEvaluatorLogger> deferredUpdateLog, ItemVersion version = null)
        {
            if (sourceFields == null)
            {
                return(false);
            }

            return(sourceFields.Any(x =>
            {
                if (!_fieldPredicate.Includes(x.Key).IsIncluded)
                {
                    return false;
                }

                if (!existingItem.IsFieldComparable(x.Key))
                {
                    return false;
                }

                bool isMatch = IsFieldMatch(x.Value, targetFields, x.Key);
                if (isMatch)
                {
                    deferredUpdateLog.AddEntry(logger =>
                    {
                        string sourceFieldValue;
                        targetFields.TryGetValue(x.Key, out sourceFieldValue);

                        if (version == null)
                        {
                            logger.IsSharedFieldMatch(serializedItem, x.Key, x.Value, sourceFieldValue);
                        }
                        else
                        {
                            logger.IsVersionedFieldMatch(serializedItem, version, x.Key, x.Value, sourceFieldValue);
                        }
                    });
                }
                return isMatch;
            }));
        }
Пример #18
0
        private static string executeP4Cmd(string cmd, string [] args)
        {
            string results = "";

            try
            {
                P4Connection p4 = new P4Connection();
                p4.Connect();

                P4RecordSet recSet = p4.Run(cmd, args);

                foreach (object obj in recSet.Messages)
                {
                    results += String.Format("{0}\r\n", (string)obj);
                }

                foreach (P4Record rec in recSet)
                {
                    FieldDictionary fd = rec.Fields;
                    if (cmd.Equals("opened"))
                    {
                        results += fd["clientFile"];
                    }
                    else
                    {
                        foreach (string key in fd.Keys)
                        {
                            results += String.Format("{0}\t\t{1}\r\n", key, fd[key]);
                        }
                    }
                    results += "\r\n";
                }
                p4.Disconnect();
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return(results);
        }
Пример #19
0
        // esegue una query e per ogni riga chiama il delegate specificato con il parametro specificato
        /// <summary>
        /// Run a query and for each row of the resultset
        /// it calls the ProcessRow delegate
        /// </summary>
        /// <param name="cmd">Command with a valid connection assigned</param>
        /// <param name="pr">Delegate to be called for each row</param>
        /// <param name="Param">A parameter to be passed to the delegate.
        /// Typically a collection in ehich to add the created entity</param>
        /// <returns>The number of rows</returns>
        public static int RunQuery(IDbCommand cmd, ProcessRow pr, object Param)
        {
            int         Count            = 0;
            IDataReader dr               = null;
            bool        IsConnectionOpen = (cmd.Connection.State == ConnectionState.Open);

            if (!IsConnectionOpen)
            {
                cmd.Connection.Open();
            }
            try
            {
                dr = cmd.ExecuteReader();
                FieldDictionary dic = GetFields(dr);
                while (dr.Read())
                {
                    pr(dr, dic, Param);
                    Count++;
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                }
                if (!IsConnectionOpen)
                {
                    cmd.Connection.Close();
                }
            }
            return(Count);
        }
Пример #20
0
 protected virtual void Dispose(bool disposing)
 {
   if (null != m_FieldDictionary)
   {
     m_FieldDictionary.InternalDispose();
     m_FieldDictionary = null;
   }
   if (m_bAutoDelete)
   {
     UnsafeNativeMethods.Rdk_RenderContent_DeleteThis(NonConstPointer());
   }
   foreach (var item in m_bitmap_to_icon_dictionary)
     UnsafeNativeMethods.DestroyIcon(item.Value);
   m_bitmap_to_icon_dictionary.Clear();
   foreach (var item in m_bitmap_from_icon_dictionary)
     item.Value.Dispose();
   m_bitmap_from_icon_dictionary.Clear();
   // for now we, don't need to perform any disposal
   //if (IntPtr.Zero != m_pRenderContent)
   //{
   //  UnsafeNativeMethods.Rdk_RenderContent_DeleteThis(m_pRenderContent);
   //  m_pRenderContent = IntPtr.Zero;
   //}
 }
Пример #21
0
 public ItemVersion(string language, int versionNumber)
 {
     Language      = language;
     VersionNumber = versionNumber;
     Fields        = new FieldDictionary();
 }
Пример #22
0
 protected override void LoadPresetBlockchainFields()
 {
     FieldDictionary.AddPresetFilterLogFields();
 }
Пример #23
0
 /// <summary>
 ///     生成载入字段值的SQL语句
 /// </summary>
 /// <param name="field">字段</param>
 /// <param name="condition">条件</param>
 /// <returns>载入字段值的SQL语句</returns>
 private string CreateLoadValueSql(string field, string condition)
 {
     Debug.Assert(FieldDictionary.ContainsKey(field));
     return($@"SELECT [{FieldMap[field]}] FROM {ContextReadTable}{ConditionSqlCode(condition)};");
 }
Пример #24
0
        public FieldDictionary fillFieldDictionary(XmlSchema schema, SnapView sv)
        {
            // Create a new FieldDictionary to fill:
            FieldDictionary return_dict = new FieldDictionary(10); // this is growable.

            // Iterate over the schema and process appinfo
            // NOTE: this code is totally unproteced from unhandled exceptions (To fix: 30/7/13)
            // The structure of this code totally depends on the form of the xsd file.
            // WARNING: If you change the xsd file - this code will become invalid (code weakness)
            foreach (XmlSchemaObject xso in schema.Items)
            {
                XmlSchemaComplexType xsa = xso as XmlSchemaComplexType;

                if (xsa != null)
                {
                    string comment =
                        //    ((XmlSchemaDocumentation)xsa.Items[0]).Markup[0].InnerText;
                        xsa.Name; // THIS is where we got to. Look at MSDN article "Traversing XML Schemas"
                    Console.WriteLine(comment);

                    // Only consider gameRowType block
                    if (xsa.Name == config.xsdFieldBlockName)
                    {
                        Console.WriteLine("Inside gameRowType if");


                        // Get the sequence particle of the complex type.
                        XmlSchemaSequence sequence = xsa.ContentTypeParticle as XmlSchemaSequence;


                        // Initial value of address for the fields (0)
                        int current_field_address = 0;

                        // Iterate over each XmlSchemaElement in the Items collection.
                        foreach (XmlSchemaElement childElement in sequence.Items)
                        {
                            Console.WriteLine("Element: {0}", childElement.Name);

                            string field_name = childElement.Name;

                            // Iterate over appinfo
                            XmlSchemaAnnotation annotation = childElement.Annotation;

                            // Iterate over Items to find appinfo
                            foreach (XmlSchemaObject xso2 in annotation.Items)
                            {
                                XmlSchemaAppInfo ai = xso2 as XmlSchemaAppInfo;
                                Console.WriteLine("     Markup[0] displayStr : " + (ai.Markup[0]).Attributes[config.xsdFieldName_displayStr].InnerText);
                                Console.WriteLine("     Markup[0] descStr : " + (ai.Markup[0]).Attributes[config.xsdFieldName_descStr].InnerText);

                                string field_displayStr = (ai.Markup[0]).Attributes[config.xsdFieldName_displayStr].InnerText;
                                string field_descStr    = (ai.Markup[0]).Attributes[config.xsdFieldName_descStr].InnerText;


                                // NOTE: we may want to construct the field outside this foreach
                                // Now we can construct the Field object and add it to the FieldDictionary
                                Field f = new Field(field_name, field_displayStr, field_descStr, current_field_address, sv);

                                // Increment field address
                                current_field_address++;

                                // Add field to the dictionary
                                // NOTE: one of the few accesses to a SnapView data member.
                                return_dict.Add(f);
                            }//foreach
                        }


                        // NEED some kind of protection for not finding anything (i.e., fails to find any entries at all)
                    } //if
                }     //if
            }         //foreach (loop over xsd top level elements)



            return(return_dict);
        }
Пример #25
0
 protected override void LoadPresetBlockchainFields()
 {
     FieldDictionary.AddPresetTransactionFields();
 }
Пример #26
0
 internal protected FieldDictionary(IntermediateFullMemberDictionary master, TInstanceIntermediateType parent, FieldDictionary root)
     : base(master, parent, root)
 {
 }
        private FieldBase GetField(ContractPropertyInfo property)
        {
            FieldBase field;

            if (property.IsDictionary)
            {
                if (property.TypeName == "TranslatedStringDictionary")
                {
                    field = new FieldTranslatedString
                    {
                        Required       = false,
                        Fixed          = false,
                        Index          = true,
                        SimpleSearch   = true,
                        MultiLine      = false,
                        Boost          = 1,
                        IndexAnalyzers = new List <AnalyzerBase>
                        {
                            new LanguageAnalyzer()
                        },
                        SimpleSearchAnalyzers = new List <AnalyzerBase>
                        {
                            new LanguageAnalyzer()
                        }
                    };
                }
                else if (property.IsArray)
                {
                    field = new FieldDictionaryArray();
                }
                else
                {
                    field = new FieldDictionary();
                }
            }
            else if (property.IsEnum)
            {
                throw new NotSupportedException("Enum types are not supported in Class to Schema conversion");
            }
            else if (property.IsSimpleType)
            {
                if (!Enum.TryParse(property.TypeName, out TypeCode typeCode))
                {
                    throw new Exception($"Parsing to TypeCode enumerated object failed for string value: {property.TypeName}.");
                }

                if (property.IsArray)
                {
                    switch (typeCode)
                    {
                    case TypeCode.String:
                        field = new FieldStringArray
                        {
                            Index = true
                        };
                        break;

                    case TypeCode.DateTime:
                        field = new FieldDateTimeArray
                        {
                            Index = true
                        };
                        break;

                    case TypeCode.Int16:
                    case TypeCode.Int32:
                    case TypeCode.Int64:
                        field = new FieldLongArray
                        {
                            Index = true
                        };
                        break;

                    default:
                        throw new Exception($"TypeCode {typeCode} is not supported.");
                    }
                }
                else
                {
                    var stringInfos = property.PictureparkAttributes.OfType <PictureparkStringAttribute>().SingleOrDefault();

                    switch (typeCode)
                    {
                    case TypeCode.String:
                        field = new FieldString
                        {
                            Index          = true,
                            SimpleSearch   = true,
                            Boost          = 1,
                            IndexAnalyzers = new List <AnalyzerBase>
                            {
                                new SimpleAnalyzer()
                            },
                            SimpleSearchAnalyzers = new List <AnalyzerBase>
                            {
                                new SimpleAnalyzer()
                            },
                            MultiLine = stringInfos?.MultiLine ?? false
                        };
                        break;

                    case TypeCode.DateTime:
                        field = CreateDateTypeField(property);

                        break;

                    case TypeCode.Boolean:
                        field = new FieldBoolean
                        {
                            Index = true
                        };
                        break;

                    case TypeCode.Int16:
                    case TypeCode.Int32:
                    case TypeCode.Int64:
                        field = new FieldLong
                        {
                            Index = true
                        };
                        break;

                    case TypeCode.Decimal:
                    case TypeCode.Double:
                    case TypeCode.Single:
                        field = new FieldDecimal
                        {
                            Index = true
                        };
                        break;

                    default:
                        throw new Exception($"TypeCode {typeCode} is not supported.");
                    }
                }
            }
            else
            {
                var schemaIndexingAttribute         = property.PictureparkAttributes.OfType <PictureparkSchemaIndexingAttribute>().SingleOrDefault();
                var listItemCreateTemplateAttribute = property.PictureparkAttributes.OfType <PictureparkListItemCreateTemplateAttribute>().SingleOrDefault();
                var tagboxAttributes          = property.PictureparkAttributes.OfType <PictureparkTagboxAttribute>().SingleOrDefault();
                var contentRelationAttributes = property.PictureparkAttributes.OfType <PictureparkContentRelationAttribute>().ToList();

                var relationTypes = new List <RelationType>();
                if (contentRelationAttributes.Any())
                {
                    relationTypes = contentRelationAttributes.Select(i => new RelationType
                    {
                        Id            = i.Name,
                        Filter        = i.Filter,
                        TargetDocType = i.TargetDocType,
                        Names         = new TranslatedStringDictionary {
                            { _defaultLanguage, i.Name }
                        }
                    }).ToList();
                }

                if (property.IsArray)
                {
                    if (contentRelationAttributes.Any())
                    {
                        field = new FieldMultiRelation
                        {
                            Index              = true,
                            RelationTypes      = relationTypes,
                            SchemaId           = property.TypeName,
                            SchemaIndexingInfo = schemaIndexingAttribute?.SchemaIndexingInfo
                        };
                    }
                    else if (property.IsReference)
                    {
                        field = new FieldMultiTagbox
                        {
                            Index                  = true,
                            SimpleSearch           = true,
                            SchemaId               = property.TypeName,
                            Filter                 = tagboxAttributes?.Filter,
                            SchemaIndexingInfo     = schemaIndexingAttribute?.SchemaIndexingInfo,
                            ListItemCreateTemplate = listItemCreateTemplateAttribute?.ListItemCreateTemplate
                        };
                    }
                    else
                    {
                        field = new FieldMultiFieldset
                        {
                            Index              = true,
                            SimpleSearch       = true,
                            SchemaId           = property.TypeName,
                            SchemaIndexingInfo = schemaIndexingAttribute?.SchemaIndexingInfo
                        };
                    }
                }
                else
                {
                    if (contentRelationAttributes.Any())
                    {
                        field = new FieldSingleRelation
                        {
                            Index              = true,
                            SimpleSearch       = true,
                            RelationTypes      = relationTypes,
                            SchemaId           = property.TypeName,
                            SchemaIndexingInfo = schemaIndexingAttribute?.SchemaIndexingInfo
                        };
                    }
                    else if (property.TypeName == "GeoPoint")
                    {
                        field = new FieldGeoPoint
                        {
                            Index = true
                        };
                    }
                    else if (property.IsReference)
                    {
                        field = new FieldSingleTagbox
                        {
                            Index                  = true,
                            SimpleSearch           = true,
                            SchemaId               = property.TypeName,
                            Filter                 = tagboxAttributes?.Filter,
                            SchemaIndexingInfo     = schemaIndexingAttribute?.SchemaIndexingInfo,
                            ListItemCreateTemplate = listItemCreateTemplateAttribute?.ListItemCreateTemplate
                        };
                    }
                    else
                    {
                        field = new FieldSingleFieldset
                        {
                            Index              = true,
                            SimpleSearch       = true,
                            SchemaId           = property.TypeName,
                            SchemaIndexingInfo = schemaIndexingAttribute?.SchemaIndexingInfo
                        };
                    }
                }
            }

            if (field == null)
            {
                throw new Exception($"Could not find type for {property.Name}");
            }

            foreach (var attribute in property.PictureparkAttributes)
            {
                if (attribute is PictureparkSearchAttribute searchAttribute)
                {
                    field.Index        = searchAttribute.Index;
                    field.SimpleSearch = searchAttribute.SimpleSearch;

                    if (field.GetType().GetRuntimeProperty("Boost") != null)
                    {
                        field.GetType().GetRuntimeProperty("Boost").SetValue(field, searchAttribute.Boost);
                    }
                }

                if (attribute is PictureparkRequiredAttribute)
                {
                    field.Required = true;
                }

                if (attribute is PictureparkMaximumLengthAttribute maxLengthAttribute)
                {
                    field.GetType().GetRuntimeProperty("MaximumLength").SetValue(field, maxLengthAttribute.Length);
                }

                if (attribute is PictureparkPatternAttribute patternAttribute)
                {
                    field.GetType().GetRuntimeProperty("Pattern").SetValue(field, patternAttribute.Pattern);
                }

                if (attribute is PictureparkNameTranslationAttribute nameTranslationAttribute)
                {
                    if (field.Names == null)
                    {
                        field.Names = new TranslatedStringDictionary();
                    }

                    var language = string.IsNullOrEmpty(nameTranslationAttribute.LanguageAbbreviation)
                        ? _defaultLanguage
                        : nameTranslationAttribute.LanguageAbbreviation;

                    field.Names[language] = nameTranslationAttribute.Translation;
                }

                if (attribute is PictureparkSortAttribute)
                {
                    if (field is FieldSingleRelation || field is FieldMultiRelation)
                    {
                        throw new InvalidOperationException($"Relation property {property.Name} must not be marked as sortable.");
                    }

                    if (field is FieldGeoPoint)
                    {
                        throw new InvalidOperationException($"GeoPoint property {property.Name} must not be marked as sortable.");
                    }

                    field.Sortable = true;
                }
            }

            var fieldName = property.Name;

            field.Id = fieldName.ToLowerCamelCase();

            if (field.Names == null)
            {
                field.Names = new TranslatedStringDictionary
                {
                    [_defaultLanguage] = fieldName
                };
            }

            if (property.PictureparkAttributes.OfType <PictureparkAnalyzerAttribute>().Any(a => !a.Index && !a.SimpleSearch))
            {
                throw new InvalidOperationException(
                          $"Property {property.Name} has invalid analyzer configuration: Specify one or both of {nameof(PictureparkAnalyzerAttribute.Index)}, {nameof(PictureparkAnalyzerAttribute.SimpleSearch)}.");
            }

            var fieldIndexAnalyzers = property.PictureparkAttributes
                                      .OfType <PictureparkAnalyzerAttribute>()
                                      .Where(a => a.Index)
                                      .Select(a => a.CreateAnalyzer())
                                      .ToList();

            if (fieldIndexAnalyzers.Any())
            {
                field.GetType().GetRuntimeProperty("IndexAnalyzers").SetValue(field, fieldIndexAnalyzers);
            }

            var fieldSimpleSearchAnalyzers = property.PictureparkAttributes
                                             .OfType <PictureparkAnalyzerAttribute>()
                                             .Where(a => a.SimpleSearch)
                                             .Select(a => a.CreateAnalyzer())
                                             .ToList();

            if (fieldSimpleSearchAnalyzers.Any())
            {
                field.GetType().GetRuntimeProperty("SimpleSearchAnalyzers").SetValue(field, fieldSimpleSearchAnalyzers);
            }

            return(field);
        }
        private FieldBase GetField(ContractPropertyInfo property)
        {
            FieldBase field = null;

            if (property.IsDictionary)
            {
                if (property.TypeName == "TranslatedStringDictionary")
                {
                    field = new FieldTranslatedString
                    {
                        Required     = false,
                        Fixed        = false,
                        Index        = true,
                        SimpleSearch = true,
                        MultiLine    = false,
                        Boost        = 1,
                        Analyzers    = new List <AnalyzerBase>
                        {
                            new LanguageAnalyzer
                            {
                                SimpleSearch = true
                            }
                        }
                    };
                }
                else if (property.IsArray)
                {
                    field = new FieldDictionaryArray();
                }
                else
                {
                    field = new FieldDictionary();
                }
            }
            else if (property.IsEnum)
            {
                Type enumType = Type.GetType($"{property.FullName}, {property.AssemblyFullName}");

                // TODO: Handle enums
            }
            else if (property.IsSimpleType)
            {
                if (!Enum.TryParse(property.TypeName, out TypeCode typeCode))
                {
                    throw new Exception($"Parsing to TypeCode enumarated object failed for string value: {property.TypeName}.");
                }

                if (property.IsArray)
                {
                    switch (typeCode)
                    {
                    case TypeCode.String:
                        field = new FieldStringArray
                        {
                            Index = true
                        };
                        break;

                    case TypeCode.DateTime:
                        field = new FieldDateTimeArray
                        {
                            Index = true
                        };
                        break;

                    case TypeCode.Int16:
                    case TypeCode.Int32:
                    case TypeCode.Int64:
                        field = new FieldLongArray
                        {
                            Index = true
                        };
                        break;

                    default:
                        throw new Exception($"TypeCode {typeCode} is not supported.");
                    }
                }
                else
                {
                    var stringInfos = property.PictureparkAttributes.OfType <PictureparkStringAttribute>().SingleOrDefault();

                    switch (typeCode)
                    {
                    case TypeCode.String:
                        field = new FieldString
                        {
                            Index        = true,
                            SimpleSearch = true,
                            Boost        = 1,
                            Analyzers    = new List <AnalyzerBase>
                            {
                                new SimpleAnalyzer
                                {
                                    SimpleSearch = true
                                }
                            },
                            MultiLine = stringInfos?.MultiLine ?? false
                        };
                        break;

                    case TypeCode.DateTime:
                        field = new FieldDateTime
                        {
                            Index = true
                        };
                        break;

                    case TypeCode.Boolean:
                        field = new FieldBoolean
                        {
                            Index = true
                        };
                        break;

                    case TypeCode.Int16:
                    case TypeCode.Int32:
                    case TypeCode.Int64:
                        field = new FieldLong
                        {
                            Index = true
                        };
                        break;

                    case TypeCode.Decimal:
                    case TypeCode.Double:
                    case TypeCode.Single:
                        field = new FieldDecimal
                        {
                            Index = true
                        };
                        break;

                    default:
                        throw new Exception($"TypeCode {typeCode} is not supported.");
                    }
                }
            }
            else
            {
                var schemaIndexingAttribute         = property.PictureparkAttributes.OfType <PictureparkSchemaIndexingAttribute>().SingleOrDefault();
                var listItemCreateTemplateAttribute = property.PictureparkAttributes.OfType <PictureparkListItemCreateTemplateAttribute>().SingleOrDefault();
                var maximumRecursionAttribute       = property.PictureparkAttributes.OfType <PictureparkMaximumRecursionAttribute>().SingleOrDefault();
                var tagboxAttributes          = property.PictureparkAttributes.OfType <PictureparkTagboxAttribute>().SingleOrDefault();
                var contentRelationAttributes = property.PictureparkAttributes.OfType <PictureparkContentRelationAttribute>().ToList();

                var relationTypes = new List <RelationType>();
                if (contentRelationAttributes.Any())
                {
                    relationTypes = contentRelationAttributes.Select(i => new RelationType
                    {
                        Id            = i.Name,
                        Filter        = i.Filter,
                        TargetDocType = i.TargetDocType,
                        Names         = new TranslatedStringDictionary {
                            { "x-default", i.Name }
                        }
                    }).ToList();
                }

                if (property.IsArray)
                {
                    if (contentRelationAttributes.Any())
                    {
                        field = new FieldMultiRelation
                        {
                            Index              = true,
                            RelationTypes      = relationTypes,
                            SchemaId           = property.TypeName,
                            SchemaIndexingInfo = schemaIndexingAttribute?.SchemaIndexingInfo
                        };
                    }
                    else if (property.IsReference)
                    {
                        field = new FieldMultiTagbox
                        {
                            Index                  = true,
                            SimpleSearch           = true,
                            SchemaId               = property.TypeName,
                            Filter                 = tagboxAttributes?.Filter,
                            SchemaIndexingInfo     = schemaIndexingAttribute?.SchemaIndexingInfo,
                            ListItemCreateTemplate = listItemCreateTemplateAttribute?.ListItemCreateTemplate
                        };
                    }
                    else
                    {
                        field = new FieldMultiFieldset
                        {
                            Index              = true,
                            SimpleSearch       = true,
                            SchemaId           = property.TypeName,
                            SchemaIndexingInfo = schemaIndexingAttribute?.SchemaIndexingInfo
                        };
                    }
                }
                else
                {
                    if (contentRelationAttributes.Any())
                    {
                        field = new FieldSingleRelation
                        {
                            Index              = true,
                            SimpleSearch       = true,
                            RelationTypes      = relationTypes,
                            SchemaId           = property.TypeName,
                            SchemaIndexingInfo = schemaIndexingAttribute?.SchemaIndexingInfo
                        };
                    }
                    else if (property.TypeName == "GeoPoint")
                    {
                        field = new FieldGeoPoint
                        {
                            Index = true
                        };
                    }
                    else if (property.IsReference)
                    {
                        field = new FieldSingleTagbox
                        {
                            Index                  = true,
                            SimpleSearch           = true,
                            SchemaId               = property.TypeName,
                            Filter                 = tagboxAttributes?.Filter,
                            SchemaIndexingInfo     = schemaIndexingAttribute?.SchemaIndexingInfo,
                            ListItemCreateTemplate = listItemCreateTemplateAttribute?.ListItemCreateTemplate
                        };
                    }
                    else
                    {
                        field = new FieldSingleFieldset
                        {
                            Index              = true,
                            SimpleSearch       = true,
                            SchemaId           = property.TypeName,
                            SchemaIndexingInfo = schemaIndexingAttribute?.SchemaIndexingInfo
                        };
                    }
                }
            }

            if (field == null)
            {
                throw new Exception($"Could not find type for {property.Name}");
            }

            foreach (var attribute in property.PictureparkAttributes)
            {
                if (attribute is PictureparkSearchAttribute searchAttribute)
                {
                    field.Index        = searchAttribute.Index;
                    field.SimpleSearch = searchAttribute.SimpleSearch;

                    if (field.GetType().GetRuntimeProperty("Boost") != null)
                    {
                        field.GetType().GetRuntimeProperty("Boost").SetValue(field, searchAttribute.Boost);
                    }
                }

                if (attribute is PictureparkRequiredAttribute)
                {
                    field.Required = true;
                }

                if (attribute is PictureparkMaximumLengthAttribute maxLengthAttribute)
                {
                    field.GetType().GetRuntimeProperty("MaximumLength").SetValue(field, maxLengthAttribute.Length);
                }

                if (attribute is PictureparkPatternAttribute patternAttribute)
                {
                    field.GetType().GetRuntimeProperty("Pattern").SetValue(field, patternAttribute.Pattern);
                }

                if (attribute is PictureparkNameTranslationAttribute nameTranslationAttribute)
                {
                    if (field.Names == null)
                    {
                        field.Names = new TranslatedStringDictionary();
                    }

                    field.Names[nameTranslationAttribute.LanguageAbbreviation] = nameTranslationAttribute.Translation;
                }
            }

            var fieldName = property.Name;

            field.Id = fieldName.ToLowerCamelCase();

            if (field.Names == null)
            {
                field.Names = new TranslatedStringDictionary
                {
                    ["x-default"] = fieldName
                };
            }

            var fieldAnalyzers = property.PictureparkAttributes
                                 .OfType <PictureparkAnalyzerAttribute>()
                                 .Select(a => a.CreateAnalyzer())
                                 .ToList();

            if (fieldAnalyzers.Any())
            {
                field.GetType().GetRuntimeProperty("Analyzers").SetValue(field, fieldAnalyzers);
            }

            return(field);
        }
Пример #29
0
        /// <summary>
        /// Decode the Fields in record (returned from fstat for a file).
        /// </summary>
        /// <param name="record">A record returned from fstat for a file</param>
        /// <param name="p4FileName">The P4 fileName for which this record applies</param>
        /// <returns>The FileState for the file</returns>
        private static FileState GetFileStateFromRecordSet(P4Record record, out string p4FileName)
        {
            FieldDictionary fields = record.Fields;

            p4FileName = fields["clientFile"];
            p4FileName = p4FileName.Replace('/', '\\');

            if (fields.ContainsKey("headAction") && fields["headAction"] == "delete")
            {
                return(FileState.DeletedAtHeadRevision);
            }

            if (fields.ContainsKey("ourLock"))
            {
                return(FileState.Locked); // implies also opened for edit
            }

            if (fields.ContainsKey("action"))
            {
                string val = fields["action"];
                if (val == "edit")
                {
                    if (fields.ContainsKey("unresolved"))
                    {
                        return(FileState.NeedsResolved);
                    }

                    if (fields.ContainsKey("haveRev") && fields.ContainsKey("headRev") && fields["haveRev"] != fields["headRev"])
                    {
                        return(FileState.OpenForEditDiffers);
                    }

                    return(FileState.OpenForEdit);
                }

                if (val == "add")
                {
                    if (fields.ContainsKey("movedFile"))
                    {
                        return(FileState.OpenForRenameTarget);
                    }

                    return(FileState.OpenForAdd);
                }

                if (val == "delete")
                {
                    if (fields.ContainsKey("movedFile"))
                    {
                        return(FileState.OpenForRenameSource);
                    }

                    return(FileState.OpenForDelete);
                }

                if (val == "move/delete")
                {
                    return(FileState.OpenForRenameSource);
                }

                if (val == "move/add")
                {
                    return(FileState.OpenForRenameTarget);
                }

                if (val == "integrate")
                {
                    return(FileState.OpenForIntegrate);
                }

                if (val == "branch")
                {
                    return(FileState.OpenForBranch);
                }
            }
            else
            {
                // No action field
                if (fields.ContainsKey("haveRev"))
                {
                    if (fields.ContainsKey("headRev") && fields["haveRev"] == fields["headRev"])
                    {
                        return(FileState.CheckedInHeadRevision);
                    }
                    else
                    {
                        return(FileState.CheckedInPreviousRevision);
                    }
                }
            }

            if (fields.ContainsKey("otherOpen"))
            {
                ArrayFieldDictionary arrayFields = record.ArrayFields;
                if (arrayFields.ContainsKey("otherLock"))
                {
                    return(FileState.LockedByOtherUser);
                }

                if (arrayFields.ContainsKey("otherAction"))
                {
                    string[] array = arrayFields["otherAction"];
                    if (array.Any(val => val == "edit"))
                    {
                        return(FileState.OpenForEditOtherUser);
                    }

                    if (array.Any(val => val == "delete"))
                    {
                        return(FileState.OpenForDeleteOtherUser);
                    }
                }
            }

            return(FileState.NotSet);
        }
Пример #30
0
 /// <summary>
 ///     用在条件中的字段条件
 /// </summary>
 /// <param name="field">字段</param>
 /// <param name="expression">条件表达式</param>
 /// <returns>字段条件</returns>
 public string FieldConditionSQL(string field, string expression = "=")
 {
     Debug.Assert(FieldDictionary.ContainsKey(field));
     return($@"[{FieldMap[field]}] {expression} @{field}");
 }
Пример #31
0
		public ItemVersion(string language, int versionNumber)
		{
			Language = language;
			VersionNumber = versionNumber;
			Fields = new FieldDictionary();
		}