public static void VerifyFacetsEquivalent(LegacyMetadata.Facet legacyFacet, Facet facet)
        {
            Assert.Equal(legacyFacet.Name, facet.Name);
            Assert.Equal(legacyFacet.FacetType.FullName, facet.FacetType.FullName);

            // Specialcase Variable, Max and Identity facet values - they are internal singleton objects.
            if (legacyFacet.Value != null
                && (new[] { "Max", "Variable", "Identity" }.Contains(legacyFacet.Value.ToString())
                    || facet.Name == "ConcurrencyMode"))
            {
                // this is to make sure we did not stick EF6 Max/Variable/Identity on legacy facet as the value
                Assert.Equal(typeof(LegacyMetadata.EdmType).Assembly, legacyFacet.Value.GetType().Assembly);

                Assert.NotNull(facet.Value);
                Assert.Equal(legacyFacet.Value.ToString(), facet.Value.ToString());
            }
            else
            {
                Assert.Equal(legacyFacet.Value, facet.Value);
            }

            Assert.Equal(legacyFacet.IsUnbounded, facet.IsUnbounded);
            Assert.Equal(LegacyMetadata.BuiltInTypeKind.Facet, legacyFacet.BuiltInTypeKind);
            Assert.Equal(BuiltInTypeKind.Facet, facet.BuiltInTypeKind);
        }
        public bool TryConvertType(string oldStorageTypeName, out string result, out Facet[] facets)
        {
            PrimitiveType oldStorageType = null;

            if (this.oldStoreTypes.TryGetValue(oldStorageTypeName, out oldStorageType))
            {
                TypeUsage oldStorageTypeUsage = TypeUsage.CreateDefaultTypeUsage(oldStorageType);
                facets = oldStorageTypeUsage.Facets.ToArray();

                // TODO: Add injection point
                if (oldStorageType.NamespaceName == "SqlServer" &&
                    (oldStorageType.Name == "timestamp" || oldStorageType.Name == "rowversion"))
                {
                    result = "rowversion";
                    return true;
                }
                else
                {
                    TypeUsage edmType = this.oldProvider.Manifest.GetEdmType(oldStorageTypeUsage);
                    TypeUsage newStorageType = this.newProvider.Manifest.GetStoreType(edmType);

                    result = newStorageType.EdmType.Name;
                    return true;
                }
            }

            facets = new Facet[0];
            result = string.Empty;
            return false;
        }
Beispiel #3
0
 /// <summary>
 /// bad Hack because the form is going wrong and values are not working
 /// discard the null ones
 /// </summary>
 /// <param name="facet"></param>
 private void CleanFacet(Facet facet)
 {
     if (facet.Values != null)
     {
         facet.Values = facet.Values.Where(fc => ! string.IsNullOrEmpty(fc.Value)).ToList();
     }
 }
        /// <summary>
        /// Read a facet
        /// </summary>
        protected virtual Facet ReadFacet(TextReader reader)
        {
            Facet facet = new Facet();

            // Read the normal
            if ((facet.Normal = ReadVertex(reader, facetRegex)) == null)
                return null;

            // Skip the "outer loop"
            reader.ReadLine();

            // Read the vertices
            for (int i = 0; i < 3; i++)
            {
                var vertice = ReadVertex(reader, verticeRegex);
                if (vertice == null) return null;
                facet.Vertices.Add(vertice);
            }

            // Read the "endloop" and "endfacet"
            reader.ReadLine();
            reader.ReadLine();

            return facet;
        }
Beispiel #5
0
        public void TestEquatable()
        {
            var vn = new Vertex(12.34f, -98.7f, 54);
            var vertices = new Vertex[] { new Vertex(), vn, new Vertex(3, 2, 1) };
            var facet = new Facet(vn, vertices);

            IEquatable<Facet> ieqFacet = facet;

            Assert.False(ieqFacet.Equals((Facet)null));

            var facet2 = new Facet();
            Assert.False(ieqFacet.Equals(facet2));

            facet2 = new Facet(new Vertex(12.34f, -98.7f, 54), null);
            Assert.False(ieqFacet.Equals(facet2));

            facet2 = new Facet() { Normal = null };
            Assert.False(ieqFacet.Equals(facet2));

            facet2 = new Facet() { Vertices = null };
            Assert.False(ieqFacet.Equals(facet2));

            facet2 = new Facet(new Vertex(12.34f, -98.7f, 54), vertices);
            Assert.True(ieqFacet.Equals(facet2));

            Assert.True(ieqFacet.Equals(facet));
        }
Beispiel #6
0
 public ActionResult AddFacet()
 {
     var facet = new Facet
         {
             Values = new List<FacetValue>()
         };
     return View("EditFacet", facet);
 }
Beispiel #7
0
 public static object Query(Facet f, params object[] args)
 {
     foreach (Lie l in Singleton.Lies[f]) {
         if (l.Applies(args)) {
             return l.TellTale();
         }
     }
     return f.GetTruth()(args);
 }
Beispiel #8
0
 public Facet Insert(Facet facet)
 {
     if (facet.Values != null && facet.Values.Count > 0)
     {
         return InsertWithValues(facet);
     }
     var record = db.Facets.Insert(facet);
     return record;
 }
        /// <summary>
        /// Write a facet
        /// </summary>
        protected virtual void WriteFacet(Facet facet, BinaryWriter writer)
        {
            // Write the normal
            WriteVertex(facet.Normal, writer);

            // Write each vertice
            foreach (var vertice in facet.Vertices)
                WriteVertex(vertice, writer);

            // Write the attribute byte count.
            writer.Write(facet.AttributeByteCount);
        }
Beispiel #10
0
 public static Facet CreateFreeTextFacet()
 {
     var facets = new Facets(new DatabaseProvider());
     var facet = new Facet
                     {
                         Type = FacetType.FreeText,
                         Name = "FreeTextTest"
                     };
     var record = facets.Insert(facet);
     facet = record;
     return facet;
 }
Beispiel #11
0
 public void GetsTheResponse()
 {
     Server.Stub(new ApiExpectation { Response = "{numFound: 20, start: 2, gmt_offset: '-500', gap:'+1HOURS', data:{'2010-02-17 02:08:45.912-0800': 8999, '2010-02-17 03:08:45.912-0800': 9000, '2010-02-17 04:08:45.912-0800': 9001}}" });
      var r = new Facet("mogade").GetInput("anything");
      Assert.AreEqual(20, r.TotalRecords);
      Assert.AreEqual("+1HOURS", r.Gap);
      Assert.AreEqual(2, r.Start);
      Assert.AreEqual("-500", r.GmtOffset);
      Assert.AreEqual(3, r.Data.Count);
      Assert.AreEqual(8999, r.Data["2010-02-17 02:08:45.912-0800"]);
      Assert.AreEqual(9000, r.Data["2010-02-17 03:08:45.912-0800"]);
      Assert.AreEqual(9001, r.Data["2010-02-17 04:08:45.912-0800"]);
 }
        public ActionResult SaveFacet(Facet facet)
        {
            if (facet.Id > 0)
            {
                this.facetService.Update(facet);
            }
            else
            {
                this.facetService.Insert(facet);
            }

            return RedirectToAction("ListFacets");
        }
Beispiel #13
0
 public GridForm(Facet f)
 {
     facet = f;
     InitializeComponent();
     drawpanel = new Panel();
     drawpanel.BorderStyle = BorderStyle.FixedSingle;
     drawpanel.Location = new Point(0, 0);
     drawpanel.Size = new Size(3520, 3520);
     drawpanel.Paint += new PaintEventHandler(p_Paint);
     this.main_panel.Controls.Add(drawpanel);
     if (f != null)
     {
         this.Text = "Grid for facet" + facet.facetId;
         enumerator = facet.blockfiles.First;
     }
 }
        /// <summary>
        /// Write a facet
        /// </summary>
        protected virtual void WriteFacet(Facet facet, TextWriter writer)
        {
            // Write the normal
            writer.WriteLine("\tfacet normal {0}", VertexToString(facet.Normal));

            // Write each vertice
            writer.WriteLine("\t\touter loop");
            foreach (var vertice in facet.Vertices)
            {
                writer.WriteLine("\t\t\tvertex {0}", VertexToString(vertice));
            }

            // Write the end loop
            writer.WriteLine("\t\tendloop");
            writer.WriteLine("\tendfacet");
        }
        /// <summary>
        /// Read a facet
        /// </summary>
        protected virtual Facet ReadFacet(BinaryReader reader)
        {
            Facet result = new Facet();

            // Read the normal
            result.Normal = ReadVertex(reader);

            // Read the vertices
            for (int i = 0; i < 3; i++)
                result.Vertices.Add(ReadVertex(reader));

            // Read the attribute
            result.AttributeByteCount = reader.ReadUInt16();

            return result;
        }
Beispiel #16
0
        /// <summary>
        /// Calculate the signed volume for a triangle facet
        /// </summary>
        /// <remarks>
        /// Code based on https://github.com/mcanet/STL-Volume-Model-Calculator
        /// </remarks>
        public static float CalculateSignedVolume(Facet facet)
        {
            if (facet == null) return 0;

            var p1 = facet.Vertices[0];
            var p2 = facet.Vertices[1];
            var p3 = facet.Vertices[2];

            var v321 = (double)p3.X * (double)p2.Y * (double)p1.Z;
            var v231 = (double)p2.X * (double)p3.Y * (double)p1.Z;
            var v312 = (double)p3.X * (double)p1.Y * (double)p2.Z;
            var v132 = (double)p1.X * (double)p3.Y * (double)p2.Z;
            var v213 = (double)p2.X * (double)p1.Y * (double)p3.Z;
            var v123 = (double)p1.X * (double)p2.Y * (double)p3.Z;
            return (float)((1.0 / 6.0) * (-v321 + v231 + v312 - v132 - v213 + v123));
        }
Beispiel #17
0
 public static Facet CreateListFacet()
 {
     var facets = new Facets(new DatabaseProvider());
     var facet = new Facet
                     {
                         Type = FacetType.List,
                         Name = "ListTest",
                         Values = new List<FacetValue>
                                      {
                                          new FacetValue {Value = "One"},
                                          new FacetValue {Value = "Two"},
                                      }
                     };
     var record = facets.Insert(facet);
     facet = record;
     return facet;
 }
Beispiel #18
0
        public void TestEquals()
        {
            var vn = new Vertex(12.34f, -98.7f, 54);
            var vertices = new Vertex[] { new Vertex(), vn, new Vertex(3, 2, 1) };
            var facet = new Facet(vn, vertices);

            Assert.False(facet.Equals((object)null));
            Assert.False(facet.Equals(12345));

            var facet2 = new Facet();
            Assert.False(facet.Equals((object)facet2));

            facet2 = new Facet(new Vertex(12.34f, -98.7f, 54), null);
            Assert.False(facet.Equals((object)facet2));

            facet2 = new Facet(new Vertex(12.34f, -98.7f, 54), vertices);
            Assert.True(facet.Equals((object)facet2));

            Assert.True(facet.Equals((object)facet));
        }
Beispiel #19
0
 /// <summary>
 /// Get land tile and static tiles from specified map.
 /// </summary>
 /// <param name="facet">Target map.</param>
 /// <param name="x">X coordinate.</param>
 /// <param name="y">Y coordinate.</param>
 /// <param name="mapInfo">MapInfo (out).</param>
 /// <returns>True on success.</returns>
 public static bool GetMapInfo(Facet facet, int x, int y, out MapInfo mapInfo)
 {
     switch (facet)
     {
         case Facet.Felucca:
             return Map.GetInfo(0, x, y, out mapInfo);
         case Facet.Trammel:
             return Map.GetInfo(1, x, y, out mapInfo);
         case Facet.Ilshenar:
             return Map.GetInfo(2, x, y, out mapInfo);
         case Facet.Malas:
             return Map.GetInfo(3, x, y, out mapInfo);
         case Facet.Tokuno:
             return Map.GetInfo(4, x, y, out mapInfo);
         case Facet.Ter_Mur:
             return Map.GetInfo(5, x, y, out mapInfo);
     }
     mapInfo = null;
     return false;
 }
Beispiel #20
0
        public void TestCreate()
        {
            var facet = new Facet();
            Assert.NotNull(facet.Normal);
            Assert.NotNull(facet.Vertices);
            Assert.Equal(0, facet.AttributeByteCount);
            Assert.Equal(0, facet.Vertices.Count);

            var vn = new Vertex(1, 2, 3);

            facet = new Facet(vn, null);
            Assert.Same(vn, facet.Normal);
            Assert.NotNull(facet.Vertices);
            Assert.Equal(0, facet.AttributeByteCount);
            Assert.Equal(0, facet.Vertices.Count);

            facet = new Facet(null, new Vertex[] { new Vertex(), new Vertex(3, 2, 1) }, 23);
            Assert.NotNull(facet.Normal);
            Assert.NotNull(facet.Vertices);
            Assert.Equal(23, facet.AttributeByteCount);
            Assert.Equal(2, facet.Vertices.Count);
        }
        private void SetupSearchResultMock()
        {
            var facetGroupMock = new Mock<ISearchFacetGroup>();
            facetGroupMock.Setup(x => x.Name).Returns("FacetGroupName");
            facetGroupMock.Setup(x => x.FieldName).Returns("FacetGroupFieldName");
            _facet = new Facet(facetGroupMock.Object, "FacetKey", "FacetName", 10);
            var facetList = new ISearchFacet[] { _facet };
            facetGroupMock.Setup(x => x.Facets).Returns(() => facetList);

            var searchDocumentMock = new Mock<ISearchDocument>();
            searchDocumentMock.Setup(x => x["displayname"])
                .Returns(() => new SearchField("displayname", "DisplayName"));
            searchDocumentMock.Setup(x => x["image_url"])
                .Returns(() => new SearchField("image_url", "/image.jpg"));  // Tests will ensures that hostname gets removed
            searchDocumentMock.Setup(x => x["content_link"])
                .Returns(() => new SearchField("content_link", "1"));
            searchDocumentMock.Setup(x => x[It.IsNotIn(new[] { "displayname", "image_url", "content_link" })])
                .Returns(() => new SearchField("name", ConvertToPrefixCodedLong(1m)));

            searchDocumentMock.Setup(x => x["brand"]).Returns(() => new SearchField("brand", "Brand"));
            searchDocumentMock.Setup(x => x["code"]).Returns(() => new SearchField("code", "Code"));

            _searchResultsMock = new Mock<ISearchResults>();
            _searchResultsMock.Setup(x => x.FacetGroups).Returns(() => new[] { facetGroupMock.Object });

            _searchResultsMock.Setup(x => x.Documents)
                .Returns(() => new SearchDocuments { searchDocumentMock.Object });
        }
Beispiel #22
0
 public void TestGetHashCode()
 {
     var vn = new Vertex(1.2f, -3.4f, 5);
     var facet = new Facet(vn, null);
     Assert.Equal(vn.GetHashCode(), facet.GetHashCode());
 }
Beispiel #23
0
 public void TestToString()
 {
     var vn = new Vertex(1.2f, -3.4f, 5);
     var facet = new Facet(vn, null);
     Assert.Equal("facet([1.2, -3.4, 5])", facet.ToString());
 }
Beispiel #24
0
		private void WriteFacetTags(Facet facet)
		{
			// Only emit a Facet element if there is content inside it
			if (!facet.IsTags)
				return;

			_w.WriteStartElement("Facet");
			_w.WriteAttributeString("Name", facet.Category);
			if (facet.FacetType == FacetType.Link)
			{
				foreach (Link value in facet.Tags)
				{
					_w.WriteStartElement(facet.FacetType.ToElementName());
					_w.WriteAttributeString("Name", value.Name);
					_w.WriteAttributeString("Href", value.Href);
					_w.WriteEndElement();  //  facet.DataType
				}
			}
			else
			{
				foreach (object value in facet.EnumerateNonEmptyTags())
				{
					_w.WriteStartElement(facet.FacetType.ToElementName());
					_w.WriteAttributeString("Value", new XAttribute("Value", value).Value); // This performs the proper value conversion for DateTime
					_w.WriteEndElement(); // facet.DataType
				}
			}
			_w.WriteEndElement(); // Facet
		}
Beispiel #25
0
 private IEnumerable<XStreamingElement> MakeItemFacetTags(Facet facet)
 {
     if (facet.DataType == FacetType.Link)
     {
         foreach (FacetHyperlink value in facet.Tags)
         {
             yield return new XStreamingElement(Xmlns + FacetTypeText(facet.DataType),
                 new XAttribute("Name", value.Name), new XAttribute("Href", value.Url));
         }
     }
     else
     {
         foreach (var value in facet.EnumerateNonEmptyTags())
         {
             yield return new XStreamingElement(Xmlns + FacetTypeText(facet.DataType),
                 new XAttribute("Value", value));
         }
     }
 }
        /// <summary>
        /// Calculates the result count.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="baseDocIdSet">The base doc id set.</param>
        /// <param name="facetGroup">The facet group.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="criteria">The criteria.</param>
        /// <returns></returns>
        private int CalculateResultCount(IndexReader reader, DocIdSet baseDocIdSet, FacetGroup facetGroup, ISearchFilter filter, ISearchCriteria criteria)
        {
            var count = 0;

            var values = LuceneQueryHelper.GetFilterValues(filter);

            if (values == null)
            {
                return 0;
            }

            BooleanFilter ffilter = null;
            foreach (var f in criteria.CurrentFilters)
            {
                if (!f.Key.Equals(facetGroup.FieldName))
                {
                    if (ffilter == null) ffilter = new BooleanFilter();

                    var q = LuceneQueryHelper.CreateQuery(criteria, f, Occur.SHOULD);
                    ffilter.Add(new FilterClause(q, Occur.MUST));
                }
            }

            foreach (var value in values)
            {
                var queryFilter = new BooleanFilter();
                    
                var valueFilter = LuceneQueryHelper.CreateQueryForValue(Results.SearchCriteria, filter, value);

                if (valueFilter == null) continue;

                queryFilter.Add(new FilterClause(valueFilter, Occur.MUST));
                if(ffilter!=null)
                    queryFilter.Add(new FilterClause(ffilter, Occur.MUST));

                var filterArray = queryFilter.GetDocIdSet(reader);
                var newCount = (int)CalculateFacetCount(baseDocIdSet, filterArray);
                if (newCount == 0) continue;

                var newFacet = new Facet(facetGroup, value.Id, GetDescription(value, Results.SearchCriteria.Locale), newCount);
                facetGroup.Facets.Add(newFacet);
                count += newCount;
            }

            return count;
        }
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }

            Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);

            PrimitiveType primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw new ArgumentException(String.Format(Resources.TypeNotSupported, edmType));
            }

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bool"]));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["utinyint"]));

            case PrimitiveTypeKind.SByte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["guid"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["double"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Decimal:
            {
                byte  precision = DEFAULT_DECIMAL_PRECISION;
                byte  scale     = DEFAULT_DECIMAL_SCALE;
                Facet facet;

                if (edmType.Facets.TryGetValue("Precision", false, out facet))
                {
                    if (!facet.IsUnbounded && facet.Value != null)
                    {
                        precision = (byte)facet.Value;
                    }
                }

                if (edmType.Facets.TryGetValue("Scale", false, out facet))
                {
                    if (!facet.IsUnbounded && facet.Value != null)
                    {
                        scale = (byte)facet.Value;
                    }
                }

                return(TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale));
            }

            case PrimitiveTypeKind.Binary:
            {
                bool  isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value;
                Facet f             = facets["MaxLength"];
                bool  isMaxLength   = f.IsUnbounded || null == f.Value || (int)f.Value > MEDIUMBLOB_MAXLEN;
                int   maxLength     = !isMaxLength ? (int)f.Value : LONGBLOB_MAXLEN;

                string typeName = String.Empty;

                // now this applies for both isFixedLength and !isFixedLength
                if (maxLength < CHAR_MAXLEN)
                {
                    typeName = "tinyblob";
                }
                else if (maxLength < MEDIUMBLOB_MAXLEN)
                {
                    typeName = "blob";
                }
                else if (maxLength < LONGTEXT_MAXLEN)
                {
                    typeName = "mediumblob";
                }
                else
                {
                    typeName = "longblob";
                }

                return(TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isFixedLength, maxLength));
            }

            case PrimitiveTypeKind.String:
            {
                string typeName      = String.Empty;
                bool   isUnicode     = null != facets["Unicode"].Value && (bool)facets["Unicode"].Value;
                bool   isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value;
                int    maxLenghtValue;

                Facet maxLengthFacet = facets["MaxLength"];
                if (isFixedLength)
                {
                    typeName = isUnicode ? "nchar" : "char";
                    if (maxLengthFacet.Value != null && Int32.TryParse(maxLengthFacet.Value.ToString(), out maxLenghtValue) && maxLenghtValue <= CHAR_MAXLEN)
                    {
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength, (int)maxLengthFacet.Value));
                    }
                    else if (maxLengthFacet.Value != null && maxLengthFacet.Value.ToString() == "Max")
                    {
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength, CHAR_MAXLEN));
                    }
                    else
                    {
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength));
                    }
                }
                else
                {
                    typeName = isUnicode ? "nvarchar" : "varchar";
                    if (maxLengthFacet.Value != null && Int32.TryParse(maxLengthFacet.Value.ToString(), out maxLenghtValue))
                    {
                        if (maxLenghtValue > VARCHAR_MAXLEN && maxLenghtValue <= MEDIUMTEXT_MAXLEN)
                        {
                            typeName = "mediumtext";
                        }
                        else if ((int)maxLengthFacet.Value > MEDIUMTEXT_MAXLEN)
                        {
                            typeName = "longtext";
                        }
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength, (int)maxLengthFacet.Value));
                    }
                    else
                    {
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["longtext"], isUnicode, isFixedLength, LONGBLOB_MAXLEN));
                    }
                }
            }

            case PrimitiveTypeKind.DateTimeOffset:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["timestamp"]));

            case PrimitiveTypeKind.DateTime:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["datetime"]));

            case PrimitiveTypeKind.Time:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["time"]));

#if NET_45_OR_GREATER
            case PrimitiveTypeKind.Geometry:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["geometry"]));
#endif
            default:
                throw new NotSupportedException(String.Format(Resources.NoStoreTypeForEdmType, edmType, primitiveType.PrimitiveTypeKind));
            }
        }
Beispiel #28
0
            private void ApplyAggregation(Facet facet, FacetValue value, ArraySegment <int> docsInQuery, IndexReader indexReader, int docBase)
            {
                var sortOptionsForFacet = GetSortOptionsForFacet(facet.AggregationField);

                switch (sortOptionsForFacet)
                {
                case SortOptions.String:
                case SortOptions.StringVal:
                case SortOptions.Byte:
                case SortOptions.Short:
                case SortOptions.Custom:
                case SortOptions.None:
                    throw new InvalidOperationException(string.Format("Cannot perform numeric aggregation on index field '{0}'. You must set the Sort mode of the field to Int, Float, Long or Double.", TryTrimRangeSuffix(facet.AggregationField)));

                case SortOptions.Int:
                    int[] ints = FieldCache_Fields.DEFAULT.GetInts(indexReader, facet.AggregationField);
                    for (int index = 0; index < docsInQuery.Count; index++)
                    {
                        var doc        = docsInQuery.Array[index];
                        var currentVal = ints[doc - docBase];
                        if (facet.Aggregation.HasFlag(FacetAggregation.Max))
                        {
                            value.Max = Math.Max(value.Max ?? Double.MinValue, currentVal);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Min))
                        {
                            value.Min = Math.Min(value.Min ?? Double.MaxValue, currentVal);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Sum))
                        {
                            value.Sum = currentVal + (value.Sum ?? 0d);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Average))
                        {
                            value.Average = currentVal + (value.Average ?? 0d);
                        }
                    }
                    break;

                case SortOptions.Float:
                    var floats = FieldCache_Fields.DEFAULT.GetFloats(indexReader, facet.AggregationField);
                    for (int index = 0; index < docsInQuery.Count; index++)
                    {
                        var doc        = docsInQuery.Array[index];
                        var currentVal = floats[doc - docBase];
                        if (facet.Aggregation.HasFlag(FacetAggregation.Max))
                        {
                            value.Max = Math.Max(value.Max ?? Double.MinValue, currentVal);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Min))
                        {
                            value.Min = Math.Min(value.Min ?? Double.MaxValue, currentVal);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Sum))
                        {
                            value.Sum = currentVal + (value.Sum ?? 0d);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Average))
                        {
                            value.Average = currentVal + (value.Average ?? 0d);
                        }
                    }
                    break;

                case SortOptions.Long:
                    var longs = FieldCache_Fields.DEFAULT.GetLongs(indexReader, facet.AggregationField);
                    for (int index = 0; index < docsInQuery.Count; index++)
                    {
                        var doc = docsInQuery.Array[index];

                        var currentVal = longs[doc - docBase];
                        if (facet.Aggregation.HasFlag(FacetAggregation.Max))
                        {
                            value.Max = Math.Max(value.Max ?? Double.MinValue, currentVal);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Min))
                        {
                            value.Min = Math.Min(value.Min ?? Double.MaxValue, currentVal);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Sum))
                        {
                            value.Sum = currentVal + (value.Sum ?? 0d);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Average))
                        {
                            value.Average = currentVal + (value.Average ?? 0d);
                        }
                    }
                    break;

                case SortOptions.Double:
                    var doubles = FieldCache_Fields.DEFAULT.GetDoubles(indexReader, facet.AggregationField);
                    for (int index = 0; index < docsInQuery.Count; index++)
                    {
                        var doc = docsInQuery.Array[index];

                        var currentVal = doubles[doc - docBase];
                        if (facet.Aggregation.HasFlag(FacetAggregation.Max))
                        {
                            value.Max = Math.Max(value.Max ?? Double.MinValue, currentVal);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Min))
                        {
                            value.Min = Math.Min(value.Min ?? Double.MaxValue, currentVal);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Sum))
                        {
                            value.Sum = currentVal + (value.Sum ?? 0d);
                        }

                        if (facet.Aggregation.HasFlag(FacetAggregation.Average))
                        {
                            value.Average = currentVal + (value.Average ?? 0d);
                        }
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException("Cannot understand " + sortOptionsForFacet);
                }
            }
Beispiel #29
0
 private Facet InsertWithValues(Facet facet)
 {
     using (var transaction = db.BeginTransaction())
     {
         try
         {
             Facet inserted = transaction.Facets.Insert(facet);
             foreach (var facetValue in facet.Values)
             {
                 facetValue.FacetId = inserted.Id;
             }
             inserted.Values = transaction.FacetValues.Insert(facet.Values).ToList<FacetValue>();
             transaction.Commit();
             return inserted;
         }
         catch
         {
             transaction.Rollback();
             throw;
         }
     }
 }
Beispiel #30
0
        protected virtual IDictionary <string, FacetGroup> GetFacets(CatalogSearchQuery searchQuery, int totalHits)
        {
            var result     = new Dictionary <string, FacetGroup>();
            var storeId    = searchQuery.StoreId ?? _services.StoreContext.CurrentStore.Id;
            var languageId = searchQuery.LanguageId ?? _services.WorkContext.WorkingLanguage.Id;

            foreach (var key in searchQuery.FacetDescriptors.Keys)
            {
                var descriptor = searchQuery.FacetDescriptors[key];
                var facets     = new List <Facet>();
                var kind       = FacetGroup.GetKindByKey("Catalog", key);

                switch (kind)
                {
                case FacetGroupKind.Category:
                case FacetGroupKind.Brand:
                case FacetGroupKind.DeliveryTime:
                case FacetGroupKind.Rating:
                case FacetGroupKind.Price:
                    if (totalHits == 0 && !descriptor.Values.Any(x => x.IsSelected))
                    {
                        continue;
                    }
                    break;
                }

                if (kind == FacetGroupKind.Category)
                {
                    var categoryTree = _categoryService.GetCategoryTree(0, false, storeId);
                    var categories   = categoryTree.Flatten(false);

                    if (descriptor.MaxChoicesCount > 0)
                    {
                        categories = categories.Take(descriptor.MaxChoicesCount);
                    }

                    var nameQuery = _localizedPropertyRepository.TableUntracked
                                    .Where(x => x.LocaleKeyGroup == "Category" && x.LocaleKey == "Name" && x.LanguageId == languageId);
                    var names = nameQuery.ToList().ToDictionarySafe(x => x.EntityId, x => x.LocaleValue);

                    foreach (var category in categories)
                    {
                        string label = null;
                        names.TryGetValue(category.Id, out label);

                        facets.Add(new Facet(new FacetValue(category.Id, IndexTypeCode.Int32)
                        {
                            IsSelected   = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(category.Id)),
                            Label        = label.HasValue() ? label : category.Name,
                            DisplayOrder = category.DisplayOrder
                        }));
                    }
                }
                else if (kind == FacetGroupKind.Brand)
                {
                    var manufacturers = _manufacturerService.GetAllManufacturers(null, storeId);
                    if (descriptor.MaxChoicesCount > 0)
                    {
                        manufacturers = manufacturers.Take(descriptor.MaxChoicesCount).ToList();
                    }

                    var nameQuery = _localizedPropertyRepository.TableUntracked
                                    .Where(x => x.LocaleKeyGroup == "Manufacturer" && x.LocaleKey == "Name" && x.LanguageId == languageId);
                    var names = nameQuery.ToList().ToDictionarySafe(x => x.EntityId, x => x.LocaleValue);

                    foreach (var manu in manufacturers)
                    {
                        string label = null;
                        names.TryGetValue(manu.Id, out label);

                        facets.Add(new Facet(new FacetValue(manu.Id, IndexTypeCode.Int32)
                        {
                            IsSelected   = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(manu.Id)),
                            Label        = label.HasValue() ? label : manu.Name,
                            DisplayOrder = manu.DisplayOrder
                        }));
                    }
                }
                else if (kind == FacetGroupKind.DeliveryTime)
                {
                    var deliveryTimes = _deliveryTimeService.GetAllDeliveryTimes();
                    var nameQuery     = _localizedPropertyRepository.TableUntracked
                                        .Where(x => x.LocaleKeyGroup == "DeliveryTime" && x.LocaleKey == "Name" && x.LanguageId == languageId);
                    var names = nameQuery.ToList().ToDictionarySafe(x => x.EntityId, x => x.LocaleValue);

                    foreach (var deliveryTime in deliveryTimes)
                    {
                        if (descriptor.MaxChoicesCount > 0 && facets.Count >= descriptor.MaxChoicesCount)
                        {
                            break;
                        }

                        string label = null;
                        names.TryGetValue(deliveryTime.Id, out label);

                        facets.Add(new Facet(new FacetValue(deliveryTime.Id, IndexTypeCode.Int32)
                        {
                            IsSelected   = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(deliveryTime.Id)),
                            Label        = label.HasValue() ? label : deliveryTime.Name,
                            DisplayOrder = deliveryTime.DisplayOrder
                        }));
                    }
                }
                else if (kind == FacetGroupKind.Price)
                {
                    var count = 0;
                    var hasActivePredefinedFacet = false;
                    var minPrice = _productRepository.Table.Where(x => !x.Deleted && x.Published && !x.IsSystemProduct).Min(x => (double)x.Price);
                    var maxPrice = _productRepository.Table.Where(x => !x.Deleted && x.Published && !x.IsSystemProduct).Max(x => (double)x.Price);
                    minPrice = FacetUtility.MakePriceEven(minPrice);
                    maxPrice = FacetUtility.MakePriceEven(maxPrice);

                    for (var i = 0; i < _priceThresholds.Length; ++i)
                    {
                        if (descriptor.MaxChoicesCount > 0 && facets.Count >= descriptor.MaxChoicesCount)
                        {
                            break;
                        }

                        var price = _priceThresholds[i];
                        if (price < minPrice)
                        {
                            continue;
                        }

                        if (price >= maxPrice)
                        {
                            i = int.MaxValue - 1;
                        }

                        var selected = descriptor.Values.Any(x => x.IsSelected && x.Value == null && x.UpperValue != null && (double)x.UpperValue == price);
                        if (selected)
                        {
                            hasActivePredefinedFacet = true;
                        }

                        facets.Add(new Facet(new FacetValue(null, price, IndexTypeCode.Double, false, true)
                        {
                            DisplayOrder = ++count,
                            IsSelected   = selected
                        }));
                    }

                    // Add facet for custom price range.
                    var priceDescriptorValue = descriptor.Values.FirstOrDefault();

                    var customPriceFacetValue = new FacetValue(
                        priceDescriptorValue != null && !hasActivePredefinedFacet ? priceDescriptorValue.Value : null,
                        priceDescriptorValue != null && !hasActivePredefinedFacet ? priceDescriptorValue.UpperValue : null,
                        IndexTypeCode.Double,
                        true,
                        true);

                    customPriceFacetValue.IsSelected = customPriceFacetValue.Value != null || customPriceFacetValue.UpperValue != null;

                    if (!(totalHits == 0 && !customPriceFacetValue.IsSelected))
                    {
                        facets.Insert(0, new Facet("custom", customPriceFacetValue));
                    }
                }
                else if (kind == FacetGroupKind.Rating)
                {
                    foreach (var rating in FacetUtility.GetRatings())
                    {
                        var newFacet = new Facet(rating);
                        newFacet.Value.IsSelected = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(rating.Value));
                        facets.Add(newFacet);
                    }
                }
                else if (kind == FacetGroupKind.Availability || kind == FacetGroupKind.NewArrivals)
                {
                    var value = descriptor.Values.FirstOrDefault();
                    if (value != null)
                    {
                        if (kind == FacetGroupKind.NewArrivals && totalHits == 0 && !value.IsSelected)
                        {
                            continue;
                        }

                        var newValue = value.Clone();
                        newValue.Value      = true;
                        newValue.TypeCode   = IndexTypeCode.Boolean;
                        newValue.IsRange    = false;
                        newValue.IsSelected = value.IsSelected;

                        facets.Add(new Facet(newValue));
                    }
                }

                if (facets.Any(x => x.Published))
                {
                    //facets.Each(x => $"{key} {x.Value.ToString()}".Dump());

                    result.Add(key, new FacetGroup(
                                   "Catalog",
                                   key,
                                   descriptor.Label,
                                   descriptor.IsMultiSelect,
                                   false,
                                   descriptor.DisplayOrder,
                                   facets.OrderBy(descriptor)));
                }
            }

            return(result);
        }
Beispiel #31
0
        /// <summary>
        /// Returns a collection of all the <see cref="Attribute"/>s we infer from the metadata associated
        /// with the metadata member corresponding to the given property descriptor
        /// </summary>
        /// <param name="pd">A <see cref="PropertyDescriptor"/> to examine</param>
        /// <returns>A collection of attributes inferred from the metadata in the given descriptor.</returns>
        protected override IEnumerable <Attribute> GetMemberAttributes(PropertyDescriptor pd)
        {
            List <Attribute> attributes = new List <Attribute>();

            // Exclude any EntityState, EntityReference, etc. members
            if (ShouldExcludeEntityMember(pd))
            {
                // for these members, we don't want to do any further
                // attribute inference
                attributes.Add(new ExcludeAttribute());
                return(attributes.ToArray());
            }

            EditableAttribute editableAttribute  = null;
            bool inferRoundtripOriginalAttribute = false;

            bool hasKeyAttribute = (pd.Attributes[typeof(KeyAttribute)] != null);
            bool isEntity        = this.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType;

            if (isEntity)
            {
                EntityType entityType = (EntityType)this.EdmType;
                EdmMember  keyMember  = entityType.KeyMembers.SingleOrDefault(k => k.Name == pd.Name);
                if (keyMember != null && !hasKeyAttribute)
                {
                    attributes.Add(new KeyAttribute());
                    hasKeyAttribute = true;
                }
            }

            EdmProperty member = this.EdmType.Members.SingleOrDefault(p => p.Name == pd.Name) as EdmProperty;

            if (member != null)
            {
                if (hasKeyAttribute)
                {
                    // key members must always be roundtripped
                    inferRoundtripOriginalAttribute = true;

                    // key members that aren't also FK members are non-editable (but allow an initial value)
                    if (!this._keyIsEditable)
                    {
                        editableAttribute = new EditableAttribute(false)
                        {
                            AllowInitialValue = true
                        };
                    }
                }

                // Check if the member is DB generated and add the DatabaseGeneratedAttribute to it if not already present.
                bool databaseGenerated = false;
                if (pd.Attributes[typeof(DatabaseGeneratedAttribute)] == null)
                {
                    MetadataProperty md = ObjectContextUtilities.GetStoreGeneratedPattern(member);
                    if (md != null)
                    {
                        if ((string)md.Value == "Computed")
                        {
                            attributes.Add(new DatabaseGeneratedAttribute(DatabaseGeneratedOption.Computed));
                            databaseGenerated = true;
                        }
                        else if ((string)md.Value == "Identity")
                        {
                            attributes.Add(new DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity));
                            databaseGenerated = true;
                        }
                    }
                }
                else
                {
                    databaseGenerated = ((DatabaseGeneratedAttribute)pd.Attributes[typeof(DatabaseGeneratedAttribute)]).DatabaseGeneratedOption != DatabaseGeneratedOption.None;
                }

                // Add implicit ConcurrencyCheck attribute to metadata if ConcurrencyMode is anything other than ConcurrencyMode.None
                Facet facet = member.TypeUsage.Facets.SingleOrDefault(p => p.Name == "ConcurrencyMode");
                if (facet != null && facet.Value != null && (ConcurrencyMode)facet.Value != ConcurrencyMode.None &&
                    pd.Attributes[typeof(ConcurrencyCheckAttribute)] == null)
                {
                    attributes.Add(new ConcurrencyCheckAttribute());
                    inferRoundtripOriginalAttribute = true;
                }

                // Add Required attribute to metadata if the member cannot be null and it is either a reference type or a Nullable<T>
                // unless it is a database generated field
                if (!member.Nullable && (!pd.PropertyType.IsValueType || IsNullableType(pd.PropertyType)) &&
                    !databaseGenerated &&
                    pd.Attributes[typeof(RequiredAttribute)] == null)
                {
                    attributes.Add(new RequiredAttribute());
                }

                bool isStringType = pd.PropertyType == typeof(string) || pd.PropertyType == typeof(char[]);
                if (isStringType &&
                    pd.Attributes[typeof(StringLengthAttribute)] == null)
                {
                    facet = member.TypeUsage.Facets.SingleOrDefault(p => p.Name == "MaxLength");
                    if (facet != null && facet.Value != null && facet.Value.GetType() == typeof(int))
                    {
                        // need to test for Type int, since the value can also be of type
                        // System.Data.Metadata.Edm.EdmConstants.Unbounded
                        int maxLength = (int)facet.Value;
                        attributes.Add(new StringLengthAttribute(maxLength));
                    }
                }

                bool hasTimestampAttribute = (pd.Attributes[typeof(TimestampAttribute)] != null);

                if (this._timestampMember == member && !hasTimestampAttribute)
                {
                    attributes.Add(new TimestampAttribute());
                    hasTimestampAttribute = true;
                }

                // All members marked with TimestampAttribute (inferred or explicit) need to
                // have [Editable(false)] and [RoundtripOriginal] applied
                if (hasTimestampAttribute)
                {
                    inferRoundtripOriginalAttribute = true;

                    if (editableAttribute == null)
                    {
                        editableAttribute = new EditableAttribute(false);
                    }
                }

                // Add RTO to this member if required. If this type has a timestamp
                // member that member should be the ONLY member we apply RTO to.
                // Dont apply RTO if it is an association member.
                bool isForeignKeyMember = this._foreignKeyMembers != null && this._foreignKeyMembers.Contains(member);
                if ((this._timestampMember == null || this._timestampMember == member) &&
                    (inferRoundtripOriginalAttribute || isForeignKeyMember) &&
                    pd.Attributes[typeof(AssociationAttribute)] == null)
                {
                    if (pd.Attributes[typeof(RoundtripOriginalAttribute)] == null)
                    {
                        attributes.Add(new RoundtripOriginalAttribute());
                    }
                }
            }

            // Add the Editable attribute if required
            if (editableAttribute != null && pd.Attributes[typeof(EditableAttribute)] == null)
            {
                attributes.Add(editableAttribute);
            }

            if (isEntity)
            {
                this.AddAssociationAttributes(pd, attributes);
            }

            return(attributes.ToArray());
        }
Beispiel #32
0
 public Bloodlands(int index, SegmentCache cache, Facet facet) : base(index, cache, facet)
 {
 }
Beispiel #33
0
 private void UpdateWithValues(Facet facet)
 {
     using (var transaction = db.BeginTransaction())
     {
         try
         {
             transaction.Facets.UpdateById(facet);
             foreach (var facetValue in facet.Values)
             {
                 if (facetValue.Id == 0)
                 {
                     facetValue.FacetId = facet.Id;
                     transaction.FacetValues.Insert(facetValue);
                 }
                 else if (string.IsNullOrWhiteSpace(facetValue.Value))
                 {
                     transaction.FacetValues.DeleteById(facetValue.Id);
                 }
                 else
                 {
                     transaction.FacetValues.UpdateById(facetValue);
                 }
             }
             transaction.Commit();
         }
         catch (Exception)
         {
             transaction.Rollback();
             throw;
         }
     }
 }
Beispiel #34
0
 public void Update(Facet facet)
 {
     if (facet.Values != null && facet.Values.Count > 0)
     {
         UpdateWithValues(facet);
     }
     else
     {
         databaseProvider.GetDatabase().Facets.UpdateById(facet);
     }
 }
Beispiel #35
0
 public void Update(Facet facet)
 {
     if (facet.Values != null && facet.Values.Count > 0)
     {
         UpdateWithValues(facet);
     }
     else
     {
         db.Facets.UpdateById(facet);
     }
 }
Beispiel #36
0
 private bool IsCategoryFacet(Facet facet)
 {
     return(facet.FieldName != null && facet.FieldName.StartsWith("CategoryLevel"));
 }