Beispiel #1
0
        public void FailToReadFromInvalidBinaryStream()
        {
            var stream    = new MemoryStream();
            var writer    = new BinaryWriter(stream, System.Text.Encoding.UTF8, true);
            var hierarchy = SqlHierarchyId.Parse(new System.Data.SqlTypes.SqlString("/1/"));

            hierarchy.Write(writer);
            //Add extra bytes after
            for (int i = 0; i < 10; i++)
            {
                writer.Write(i);
            }
            writer.Close();
            stream.Position = 0;
            var reader     = new BinaryReader(stream);
            var hierarchy2 = new SqlHierarchyId();

            AssertEx.ThrowsException(() => hierarchy2.Read(reader), typeof(HierarchyIdException), "24000: SqlHierarchyId operation failed because HierarchyId object was constructed from an invalid binary string. ");
        }
Beispiel #2
0
        private static object ParseSqlServerType(Type type, string value)
        {
            if (type == typeof(SqlHierarchyId))
            {
                return(SqlHierarchyId.Parse(value));
            }

            if (type == typeof(SqlGeography))
            {
                return(SqlGeography.Parse(value));
            }

            if (type == typeof(SqlGeometry))
            {
                return(SqlGeometry.Parse(value));
            }

            throw new InvalidOperationException("Unexpected {0}".FormatWith(type.Name));
        }
        public override object ToDbValue(Type fieldType, object value)
        {
            if (value == null || value is DBNull)
            {
                return(SqlHierarchyId.Null);
            }

            if (value is SqlHierarchyId)
            {
                return(value);
            }

            if (value is string)
            {
                var str = value as string;
                return(SqlHierarchyId.Parse(str));
            }

            return(base.ToDbValue(fieldType, value));
        }
Beispiel #4
0
 public void TestHierarchyId(string context)
 {
     using (var conn = GetDataContext(context))
     {
         conn.GetTable <AllTypes2>()
         .Where(t => (bool)(t.hierarchyidDataType.GetLevel() > 0))
         .Select(t => new
         {
             v1 = SqlHierarchyId.GetRoot(),
             v2 = Sql.ToSql(t.hierarchyidDataType.GetDescendant(SqlHierarchyId.Parse("/1/3/4/"), SqlHierarchyId.Parse("/1/3/5/"))),
             v3 = t.hierarchyidDataType.IsDescendantOf(SqlHierarchyId.Parse("/1/")),
             v4 = t.hierarchyidDataType.GetLevel(),
             v5 = t.hierarchyidDataType.GetAncestor(0),
             v6 = t.hierarchyidDataType.GetReparentedValue(SqlHierarchyId.Parse("/1/"), SqlHierarchyId.Parse("/2/")),
             v7 = SqlHierarchyId.Parse("/1/2/3/4/5/"),
             v8 = t.hierarchyidDataType.ToString(),
         })
         .ToList();
     }
 }
Beispiel #5
0
 public void Promote(String pk)
 {
     // Transfere nó para nível imediatamente inferior (número do nível)
     try
     {
         byte[]         b = GetHid(pk);
         SqlHierarchyId h = Conversions.Bytes2HierarchyId(b);
         if (h.GetLevel() < 2)
         {
             throw new Exception("It is not allowed promotion from level 1 or 0.");
         }
         var  result  = db.Database.SqlQuery <long>("select " + PKName + " from " + TableName + " where hid = cast((Select cast(hid as hierarchyid) from " + TableName + " where " + PKName + " = " + pk + ").GetAncestor(2) as varbinary)").ToList();
         long novamae = result[0];
         MovSubTree(pk, novamae.ToString());
     }
     catch (Exception ex)
     {
         throw new Exception("Error on promote." + ex.Message);
     }
 }
Beispiel #6
0
        public string WhereClause(ArrayList collapsed)
        {
            System.Text.StringBuilder wc = new System.Text.StringBuilder("");
            foreach (string item in collapsed)
            {
                SqlHierarchyId itemHid = Conversions.Bytes2HierarchyId(GetHid(item));
                wc.Append("AND ((cast(hid as hierarchyid).IsDescendantOf('" + itemHid.ToString() + "')=0 or cast(hid as hierarchyid) = '" + itemHid.ToString() + "'))");
            }
            string result = wc.ToString();

            if (result == "")
            {
                result = "1=1";
            }
            else
            {
                result = result.Substring(3);
            }
            return(result);
        }
Beispiel #7
0
        public void Can_convert_to_and_from_HierarchyId_and_string_with_anon_typed_insert()
        {
            Db.DropAndCreateTable <HierarchyIdTable>();

            var dialect   = Db.GetDialectProvider();
            var tableName = dialect.GetQuotedTableName(ModelDefinition <HierarchyIdTable> .Definition);

            var stringValue = "/2/3/6/";
            var treeId      = SqlHierarchyId.Parse(stringValue);

            var sql = $"INSERT {tableName} (TreeId, StringTreeId, NullTreeId) VALUES (@TreeId, @StringTreeId, @NullTreeId);";

            Db.ExecuteSql(sql, new { TreeId = treeId, StringTreeId = stringValue, NullTreeId = SqlHierarchyId.Null });

            var result = Db.Select <FlippedHierarchyIdTable>().FirstOrDefault();

            Assert.AreEqual(stringValue, result.StringTreeId);
            Assert.AreEqual(treeId, result.TreeId);
            Assert.AreEqual(null, result.NullTreeId);
        }
Beispiel #8
0
        public Document CreateFileDocument(
            string fullFileName,
            int documentLevel,
            SqlHierarchyId parentNode,
            string documentSummary,
            byte[] documentData)
        {
            var fileName      = Path.GetFileName(fullFileName);
            var title         = Path.GetFileNameWithoutExtension(fullFileName);
            var fileExtension = Path.GetExtension(fullFileName);

            var documentId = Guid.NewGuid();

            try
            {
                var documentNode = _repository.GetNewDocumentNode(parentNode);

                return(new Document
                {
                    Id = documentId,
                    ModifiedDate = DateTime.UtcNow,
                    DocumentNode = documentNode,
                    DocumentLevel = documentLevel,
                    Title = title,
                    Owner = 220,
                    FolderFlag = documentLevel > 0,
                    FileName = fileName,
                    FileExtension = fileExtension,
                    Revision = "0",
                    ChangeNumber = 0,
                    Status = 2,
                    DocumentSummary = documentSummary,
                    DocumentData = documentData
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw e;
            }
        }
Beispiel #9
0
        private static SqlHierarchyId GetNewPosition <T>(MoveTreeModel model, TreeEntity entity)
            where T : TreeEntity
        {
            var newParentRoute = model.NewParent == null?SqlHierarchyId.GetRoot() : model.NewParent.InDB(a => a.Route);

            if (newParentRoute.IsDescendantOf(entity.Route))
            {
                throw new Exception(TreeMessage.ImpossibleToMove0InsideOf1.NiceToString(entity, model.NewParent));
            }

            if (model.InsertPlace == InsertPlace.FirstNode)
            {
                return(newParentRoute.GetDescendant(SqlHierarchyId.Null, FirstChild <T>(newParentRoute)));
            }

            if (model.InsertPlace == InsertPlace.LastNode)
            {
                return(newParentRoute.GetDescendant(LastChild <T>(newParentRoute), SqlHierarchyId.Null));
            }

            var newSiblingRoute = model.Sibling !.InDB(a => a.Route);

            if (!newSiblingRoute.IsDescendantOf(newParentRoute) ||
                newSiblingRoute.GetLevel() != newParentRoute.GetLevel() + 1 ||
                newSiblingRoute == entity.Route)
            {
                throw new Exception(TreeMessage.ImpossibleToMove01Of2.NiceToString(entity, model.InsertPlace.NiceToString(), model.NewParent));
            }

            if (model.InsertPlace == InsertPlace.After)
            {
                return(newParentRoute.GetDescendant(newSiblingRoute, Next <T>(newSiblingRoute)));
            }

            if (model.InsertPlace == InsertPlace.Before)
            {
                return(newParentRoute.GetDescendant(Previous <T>(newSiblingRoute), newSiblingRoute));
            }

            throw new InvalidOperationException("Unexpected InsertPlace " + model.InsertPlace);
        }
Beispiel #10
0
 public static void FillFileRow(this File file, out Guid stream_id,
                                out byte[] file_stream,
                                out string name,
                                out SqlHierarchyId path_locator,
                                out SqlHierarchyId parent_path_locator,
                                out string file_type,
                                out long?cached_file_size,
                                out DateTimeOffset creation_time,
                                out DateTimeOffset last_write_time,
                                out DateTimeOffset?last_access_time,
                                out bool is_directory,
                                out bool is_offline,
                                out bool is_hidden,
                                out bool is_readonly,
                                out bool is_archive,
                                out bool is_system,
                                out bool is_temporary
                                )
 {
     if (file == null)
     {
         throw new Exception();
     }
     stream_id           = file.stream_id;
     file_stream         = file.file_stream;
     name                = file.name;
     path_locator        = file.path_locator;
     parent_path_locator = file.parent_path_locator;
     file_type           = file.file_type;
     cached_file_size    = file.cached_file_size;
     creation_time       = file.creation_time;
     last_write_time     = file.last_write_time;
     last_access_time    = file.last_access_time;
     is_directory        = file.is_directory;
     is_offline          = file.is_offline;
     is_hidden           = file.is_hidden;
     is_readonly         = file.is_readonly;
     is_archive          = file.is_archive;
     is_system           = file.is_system;
     is_temporary        = file.is_temporary;
 }
        public void CreateDirectoryAlreadyExistsTest()
        {
            // Arrange
            var table         = "MyTable";
            var tableRoot     = @"\MyTableDir";
            var dirStructure  = @"dir1\dir2\dir3";
            var dirManager    = new FileTableManager();
            var fileTableRepo = new Mock <FileTableRepo>();
            var stringId      = "/0/";
            var id            = SqlHierarchyId.Parse(stringId);

            fileTableRepo.Setup(m => m.FindPath(table, dirStructure, true, It.IsAny <SqlConnection>(), false)).Returns(id);
            fileTableRepo.Setup(m => m.GetTableRootPath(table, 0, null)).Returns(tableRoot);
            dirManager.FileTableRepo = fileTableRepo.Object;

            // Act
            var pathId = dirManager.CreateDirectory(table, dirStructure, null, true);

            // Assert
            Assert.AreEqual(stringId, pathId.ToString());
        }
Beispiel #12
0
        public void DeleteTree(String pk)
        // remove toda uma sub árvore
        {
            try
            {
                long           tree   = long.Parse(pk);
                T              t      = repo.Find(new object[] { tree });
                SqlHierarchyId hid    = Conversions.Bytes2HierarchyId(t.hid);
                Int16          maxNiv = 0;

                foreach (var r in repo.Get)
                {
                    SqlHierarchyId h = Conversions.Bytes2HierarchyId(r.hid);
                    if (h.IsDescendantOf(hid))
                    {
                        if (h.GetLevel() > maxNiv)
                        {
                            maxNiv = (Int16)h.GetLevel();
                        }
                    }
                }


                for (int i = maxNiv; i > 0; i--)
                {
                    foreach (T r in repo.Get)
                    {
                        SqlHierarchyId h = Conversions.Bytes2HierarchyId(r.hid);
                        if (h.IsDescendantOf(hid))
                        {
                            db.Entry(r).State = EntityState.Deleted;
                        }
                    }
                }

                db.SaveChanges();
            }
            catch (Exception ex)
            { throw new Exception("Erro em exclusão de sub-árvore: " + ex.Message); }
        }
        public static void FillFileRow(Object obj, out Guid stream_id,
                                       out byte[] file_stream,
                                       out string name,
                                       out SqlHierarchyId path_locator,
                                       out SqlHierarchyId parent_path_locator,
                                       out string file_type,
                                       out long?cached_file_size,
                                       out DateTimeOffset creation_time,
                                       out DateTimeOffset last_write_time,
                                       out DateTimeOffset?last_access_time,
                                       out bool is_directory,
                                       out bool is_offline,
                                       out bool is_hidden,
                                       out bool is_readonly,
                                       out bool is_archive,
                                       out bool is_system,
                                       out bool is_temporary
                                       )
        {
            File file = obj as File;

            file.FillFileRow(out stream_id,
                             out file_stream,
                             out name,
                             out path_locator,
                             out parent_path_locator,
                             out file_type,
                             out cached_file_size,
                             out creation_time,
                             out last_write_time,
                             out last_access_time,
                             out is_directory,
                             out is_offline,
                             out is_hidden,
                             out is_readonly,
                             out is_archive,
                             out is_system,
                             out is_temporary
                             );
        }
Beispiel #14
0
        public void TrocaPosicaoFilhos(String Filho1, String Filho2)
        {
            try
            {
                // Trocar posições
                T      t     = repo.Find(new object[] { long.Parse(Filho1) });
                byte[] hid1B = t.hid;
                T      u     = repo.Find(new object[] { long.Parse(Filho2) });
                byte[] hid2B = u.hid;
                t.hid             = hid2B;
                u.hid             = hid1B;
                db.Entry(t).State = EntityState.Modified;
                db.Entry(u).State = EntityState.Modified;
                SqlHierarchyId hid1 = Conversions.Bytes2HierarchyId(hid1B);
                SqlHierarchyId hid2 = Conversions.Bytes2HierarchyId(hid2B);

                // reorganiza descendentes
                foreach (T r in repo.Get)
                {
                    if (r.hid != hid1B && r.hid != hid2B)
                    {
                        if (Conversions.Bytes2HierarchyId(r.hid).IsDescendantOf(hid1))
                        {
                            r.hid             = Conversions.HierarchyId2Bytes(Conversions.Bytes2HierarchyId(r.hid).GetReparentedValue(hid1, hid2));
                            db.Entry(r).State = EntityState.Modified;
                        }
                        else
                        if (Conversions.Bytes2HierarchyId(r.hid).IsDescendantOf(hid2))
                        {
                            r.hid             = Conversions.HierarchyId2Bytes(Conversions.Bytes2HierarchyId(r.hid).GetReparentedValue(hid2, hid1));
                            db.Entry(r).State = EntityState.Modified;
                        }
                    }
                }
                db.SaveChanges();
            }
            catch (Exception ex)
            { throw new Exception("Erro ao trocar posição filhos: " + ex.Message); }
        }
Beispiel #15
0
        public int RenameFile(string table, SqlHierarchyId hierarchyid, string filename, SqlConnection conn)
        {
            SqlConnManager.IsConnected(conn);
            if (!FileTableExists(table, conn)) // This is used to prevent SQL injection
            {
                throw new Exception("Table does not exists or is not a FileTable.");
            }
            if (string.IsNullOrWhiteSpace(filename))
            {
                throw new ArgumentNullException("filename");
            }
            var insertQry = "UPDATE {0} SET Name = @fileName WHERE path_locator = @hierarchyId";
            var qry       = string.Format(insertQry, table);
            var cmd       = new SqlCommand(qry, conn);

            cmd.Parameters.Add(new SqlParameter("@fileName", filename));
            cmd.Parameters.Add(new SqlParameter("@hierarchyId", hierarchyid)
            {
                UdtTypeName = Constants.HierarchyId
            });
            return(cmd.ExecuteNonQuery());
        }
        public void Can_select_from_FileStream()
        {
            using (var db = OpenDbConnection())
            {
                db.DropAndCreateTable <FileStream>();

                db.Insert(new FileStream
                {
                    ID          = Guid.NewGuid(),
                    Name        = "file.txt",
                    Path        = SqlHierarchyId.Parse("/1/2/3/"),
                    ParentPath  = SqlHierarchyId.Parse("/1/2/"),
                    FileContent = "contents".ToUtf8Bytes(),
                    FileType    = MimeTypes.PlainText,
                });

                //db.Select<FileStream>().PrintDump();

                var q = db.From <FileStream>();
                db.Select(q);
            }
        }
        public void Can_insert_and_retrieve_HierarchyId()
        {
            using (var db = OpenDbConnection())
            {
                var stringValue = "/1/1/3/";  // 0x5ADE is hex

                var treeId = SqlHierarchyId.Parse(stringValue);

                db.Insert(new HierarchyTestTable()
                {
                    TreeId = treeId, NullTreeId = SqlHierarchyId.Null
                });

                var result = db.Select <HierarchyTestTable>();
                Assert.AreEqual(null, result[0].NullTreeId);
                Assert.AreEqual(treeId, result[0].TreeId);

                var parent = db.Column <SqlHierarchyId>("SELECT TreeId.GetAncestor(1) from HierarchyTestTable").First();
                var str    = parent.ToString();
                Assert.AreEqual("/1/1/", str);
            }
        }
Beispiel #18
0
        public async Task <ActionResult <Domain> > PostDomain(Domaintest domain)
        {
            Domain toInsert = new Domain();

            toInsert.DomainName   = domain.DomainName;
            toInsert.DomainTypeId = domain.DomainTypeId;
            toInsert.Parentt      = domain.Parentt;
            toInsert.HighLevel    = domain.HighLevel;
            //if (domain.Parentt == "N/A")
            //{
            //    SqlString level = new SqlString ( "/1/" );
            //    toInsert.Level = SqlHierarchyId.Parse("/1/");
            //}else
            //{
            //    //SqlString level = new SqlString("/1/2/");
            //    toInsert.Level = SqlHierarchyId.Parse("/1/3/");
            //}
            SqlHierarchyId id1 = SqlHierarchyId.Parse(domain.Path);

            using (var stream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(stream))
                {
                    id1.Write(writer);
                    toInsert.Level = stream.ToArray();
                }
            }
            _context.Domains.Add(toInsert);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
            }

            return(CreatedAtAction("GetDomain", new { id = toInsert.DomainId }, toInsert));
        }
Beispiel #19
0
    private void AddChildrens(Member member)
    {
        var children = member.GetDirectDescendants();

        for (int i = 0; i < AppSettings.Matrix.MaxChildrenInMatrix; i++)  //Matrix size = 2 (binary)
        {
            SqlHierarchyId result = SqlHierarchyId.Parse(member.MatrixId.ToString() + ((i % AppSettings.Matrix.MaxChildrenInMatrix) + 1) + "/");

            if (children.Any(x => (bool)(x.MatrixId == result)))
            {
                Member child = children.First(x => (bool)(x.MatrixId == result));

                AddNode(child);
                AddEdge(member, child);

                AddChildrens(child);
            }
            else
            {
                AddEmptyNode(member, i);
            }
        }
    }
Beispiel #20
0
        public Document CreateDirectoryDocument(
            string directoryName,
            int documentLevel,
            SqlHierarchyId parentNode)
        {
            var newDocumentNode = _repository.GetNewDocumentNode(parentNode);

            return(new Document
            {
                Id = Guid.NewGuid(),
                ModifiedDate = DateTime.UtcNow,
                DocumentNode = newDocumentNode,
                DocumentLevel = documentLevel,
                Title = directoryName,
                Owner = 220,
                FolderFlag = true,
                FileName = directoryName,
                FileExtension = string.Empty,
                Revision = "0",
                ChangeNumber = 0,
                Status = 2
            });
        }
Beispiel #21
0
        public async Task <ActionResult <List <Domaintest> > > GetDomains()
        {
            object domain = (from x in _context.Domains
                             select new
            {
                Id = x.DomainId,
                Name = x.DomainName,
                Type = x.DomainTypeId,
                Parent = x.Parentt,
                Path = x.Level.ToString(),
                HighLevel = x.HighLevel
            }).ToList();

            //var type = domain.GetType();
            //var strNode = (string) type.GetProperty("Path").GetValue(domain, null);

            List <Domaintest> resultList = new List <Domaintest>();
            dynamic           myDyn      = domain;

            foreach (var dyn in myDyn)
            {
                int            myId      = dyn.Id;
                string         strName   = dyn.Name;
                int            iType     = dyn.Type;
                string         strParent = dyn.Parent;
                string         strNode   = dyn.Path;
                int            hLevel    = dyn.HighLevel;
                SqlHierarchyId node      = SqlHierarchyId.Parse(dyn.Path);

                Domaintest result = new Domaintest(myId, strName, iType, strParent, strNode, hLevel);
                resultList.Add(result);
            }



            return(resultList);
        }
Beispiel #22
0
        public static object WorkbookToDatabase(object workbookValue, Type expectedType)
        {
            if (workbookValue == null)
            {
                return(DBNull.Value);
            }

            if (workbookValue is string && string.IsNullOrEmpty(workbookValue.ToString()))
            {
                return(DBNull.Value);
            }

            if (expectedType != null)
            {
                switch (expectedType.FullName)
                {
                case "Microsoft.SqlServer.Types.SqlGeography":
                    return(SqlGeography.Parse(new SqlString(workbookValue.ToString())));

                case "Microsoft.SqlServer.Types.SqlGeometry":
                    return(SqlGeometry.Parse(new SqlString(workbookValue.ToString())));

                case "Microsoft.SqlServer.Types.SqlHierachyId":
                    return(SqlHierarchyId.Parse(new SqlString(workbookValue.ToString())));

                case "System.DateTime":
                    if (workbookValue is double)
                    {
                        return(DateTime.FromOADate((double)workbookValue));
                    }

                    break;
                }
            }

            return(workbookValue);
        }
Beispiel #23
0
        private static Category setCategory(StoreContext _context, Category category)
        {
            var parentNode = new byte[2147483591];
            var lastChild  = new Category();

            parentNode = _context.Categorys.FirstOrDefault(x => x.Name == category.CategoryUp).Node;

            try
            {
                lastChild = _context.Categorys.Where(x => x.CategoryUp == category.CategoryUp)
                            .OrderByDescending(x => x.Node)
                            .FirstOrDefault();

                SqlHierarchyId lastSqlNode = HierarchyExtensions.ToSqlHierarchyId(lastChild.Node);

                category.Node = HierarchyExtensions.ToByteArray(HierarchyExtensions.ToSqlHierarchyId(parentNode).GetDescendant(lastSqlNode, new SqlHierarchyId()));
            }
            catch (Exception ex)
            {
                category.Node = HierarchyExtensions.ToByteArray(HierarchyExtensions.ToSqlHierarchyId(parentNode).GetDescendant(new SqlHierarchyId(), new SqlHierarchyId()));
            }

            return(category);
        }
        public void DirectoryExistsFoundTest()
        {
            // Arrange
            var table         = "MyTable";
            var tableRoot     = @"\MyTableDir";
            var dirStructure  = @"dir1\dir2\dir3";
            var id            = SqlHierarchyId.Parse("/0/1/2/3/");
            var dirManager    = new FileTableManager();
            var fileTableRepo = new Mock <FileTableRepo>();

            fileTableRepo.Setup(m => m.FindPath(It.IsAny <string>(), It.IsAny <string>(), true, null, false)).Returns(id);
            dirManager.FileTableRepo = fileTableRepo.Object;

            var fileTableManagerMock = new Mock <IFileTableRepo>();

            fileTableManagerMock.Setup(m => m.FileTableExists(table, null)).Returns(true);
            fileTableManagerMock.Setup(m => m.GetTableRootPath(table, 0, null)).Returns(tableRoot);

            // Act
            var pathId = dirManager.DirectoryExists(table, dirStructure, null);

            // Assert
            Assert.AreEqual(id, pathId);
        }
Beispiel #25
0
        public async Task <ActionResult <Pagination <ItemToReturnDto> > > GetItems(
            [FromQuery] ItemSpecParams itemParams)
        {
            //Get the category choose
            if (itemParams.CategoryId == null)
            {
                itemParams.CategoryId = 0 /*Root*/;
            }
            if (itemParams.BrandId == null)
            {
                //Initialize the BrandId List
                itemParams.BrandId = new List <int?>();
            }
            itemParams.SubCategory = new List <int?>();
            itemParams.SubCategory.Add(itemParams.CategoryId);
            var cat = await _context.Categorys.Where(x => x.Id == itemParams.CategoryId).FirstOrDefaultAsync();

            SqlHierarchyId catNode = HierarchyExtensions.ToSqlHierarchyId(cat.Node);

            //Get all subCategories
            var allCategories = await _context.Categorys.ToListAsync();

            var subCategorys = new List <Category>();

            // Select all subcategories
            foreach (var cats in allCategories)
            {
                SqlHierarchyId node = HierarchyExtensions.ToSqlHierarchyId(cats.Node);
                if (node.IsDescendantOf(catNode) && node != catNode)
                {
                    subCategorys.Add(cats);
                    itemParams.SubCategory.Add(cats.Id);
                }
            }

            var spec = new ItemsWithTypesAndBrandsSpecification(itemParams);

            var countSpec = new ItemWithFiltersForCountSpecificication(itemParams);

            var totalItems = await _itemsRepo.CountAsync(countSpec);

            var items = await _itemsRepo.ListAsync(spec);

            IList <ItemToReturnDto> itemsToReturns = new List <ItemToReturnDto>();

            foreach (var elts in items)
            {
                int id = elts.Id;

                List <string>           colorName = new List <string>();
                List <string>           sizeName = new List <string>();
                List <ReviewDto>        reviewList = new List <ReviewDto>();
                List <ImageToReturnDto> imageList = new List <ImageToReturnDto>();
                int ratingsCount = 0; int ratingsValue = 0;

                var colors = await _context.Colors.Where(x => x.ItemId == id).ToListAsync();

                if (colors.Count > 0)
                {
                    elts.Color = colors;
                    foreach (var elt in elts.Color)
                    {
                        colorName.Add(elt.Name);
                    }
                }
                var sizes = await _context.Sizes.Where(x => x.ItemId == id).ToListAsync();

                if (sizes.Count > 0)
                {
                    elts.Size = sizes;
                    foreach (var elt in elts.Size)
                    {
                        sizeName.Add(elt.Name);
                    }
                }
                var images = await _context.Images.Where(x => x.ItemId == id).ToListAsync();

                if (images.Count > 0)
                {
                    elts.Images = images;
                    foreach (var elt in elts.Images)
                    {
                        ImageToReturnDto img = new ImageToReturnDto();
                        img.small  = (ApiUrl + elt.UrlSmall);
                        img.medium = (ApiUrl + elt.UrlMedium);
                        img.big    = (ApiUrl + elt.UrlBig);
                        imageList.Add(img);
                    }
                }
                var reviews = await _context.Reviews.Where(x => x.ItemId == id).ToListAsync();

                if (reviews.Count > 0)
                {
                    elts.Review = reviews;
                    foreach (var elt in elts.Review)
                    {
                        ReviewDto rev = new ReviewDto();
                        rev.ReviewerName  = elt.ReviewerName;
                        rev.ReviewerPhoto = (ApiUrl + elt.ReviewerPhoto);
                        rev.ReviewMessage = elt.ReviewMessage;
                        rev.rate          = elt.rate;
                        if (elt.rate == 1)
                        {
                            rev.sentiment = "sentiment_very_dissatisfied";
                        }
                        else if (elt.rate == 2)
                        {
                            rev.sentiment = "sentiment_dissatisfied";
                        }
                        else if (elt.rate == 3 || elt.rate == 4)
                        {
                            rev.sentiment = "sentiment_satisfied";
                        }
                        else if (elt.rate == 5)
                        {
                            rev.sentiment = "sentiment_very_satisfied";
                        }
                        rev.ReviewDate = elt.ReviewDate;
                        reviewList.Add(rev);
                        ratingsCount++;
                        ratingsValue += elt.rate;
                    }
                }

                var itemsToReturn = new ItemToReturnDto
                {
                    Id                    = id,
                    Name                  = elts.Name,
                    Description           = elts.Description,
                    OldPrice              = elts.OldPrice,
                    NewPrice              = elts.NewPrice,
                    Discount              = elts.Discount,
                    RatingsCount          = ratingsCount,
                    RatingsValue          = ratingsValue,
                    availibilityCount     = elts.availibilityCount,
                    cartCount             = elts.cartCount,
                    TechnicalDescription  = elts.TechnicalDescription,
                    AdditionalInformation = elts.AdditionalInformation,
                    Weight                = elts.Weight,
                    Color                 = colorName,
                    Size                  = sizeName,
                    Images                = imageList,
                    Reviews               = reviewList,
                    CategoryId            = elts.Category.Id,
                    BrandName             = elts.ProductBrand.Name,
                    CategoryName          = elts.Category.Name,
                    PictureUrl            = ApiUrl + elts.PictureUrl
                };
                itemsToReturns.Add(itemsToReturn);
            }


            //var data = _mapper
            //    .Map<IReadOnlyList<Item>, IReadOnlyList<ItemToReturnDto>>(items);

            return(Ok(new Pagination1 <ItemToReturnDto>(itemParams.PageIndex, itemParams.PageSize, totalItems, itemsToReturns)));;
        }
 static bool IsDescendantOf(SqlHierarchyId child, SqlHierarchyId parent)
 {
     return child.IsDescendantOf(parent).Value;
 }
Beispiel #27
0
        public static void Load()
        {
            var ama = new AmericanMusicAwardEntity {
                Category = "Indie Rock", Year = 1991, Result = AwardResult.Nominated
            }
            .Execute(AwardOperation.Save);

            BandEntity smashingPumpkins = new BandEntity
            {
                Name    = "Smashing Pumpkins",
                Members = "Billy Corgan, James Iha, D'arcy Wretzky, Jimmy Chamberlin"
                          .Split(',').Select(s => new ArtistEntity {
                    Name = s.Trim(), Sex = s.Contains("Wretzky") ? Sex.Female : Sex.Male, Status = s.Contains("Wretzky") ? Status.Married : (Status?)null
                }).ToMList(),
                LastAward = ama,
            }.Execute(BandOperation.Save);

            CountryEntity usa = new CountryEntity {
                Name = "USA"
            };
            CountryEntity japan = new CountryEntity {
                Name = Japan
            };

            smashingPumpkins.Members.ForEach(m => m.Friends = smashingPumpkins.Members.Where(a => a.Sex != m.Sex).Select(a => a.ToLiteFat()).ToMList());

            smashingPumpkins.Execute(BandOperation.Save);

            new NoteWithDateEntity {
                CreationTime = DateTime.Now.AddHours(+8), Text = "American alternative rock band", Target = smashingPumpkins
            }
            .Execute(NoteWithDateOperation.Save);

            LabelEntity virgin = new LabelEntity {
                Name = "Virgin", Country = usa, Node = SqlHierarchyId.GetRoot().FirstChild()
            }
            .Execute(LabelOperation.Save);

            new AlbumEntity
            {
                Name   = "Siamese Dream",
                Year   = 1993,
                Author = smashingPumpkins,
                Songs  = { new SongEmbedded {
                               Name = "Disarm"
                           } },
                Label = virgin
            }.Execute(AlbumOperation.Save);

            AlbumEntity mellon = new AlbumEntity
            {
                Name   = "Mellon Collie and the Infinite Sadness",
                Year   = 1995,
                Author = smashingPumpkins,
                Songs  =
                {
                    new SongEmbedded {
                        Name = "Zero", Duration = TimeSpan.FromSeconds(123)
                    },
                    new SongEmbedded {
                        Name = "1976"
                    },
                    new SongEmbedded {
                        Name = "Tonight, Tonight", Duration = TimeSpan.FromSeconds(376)
                    }
                },
                BonusTrack = new SongEmbedded {
                    Name = "Jellybelly"
                },
                Label = virgin
            }.Execute(AlbumOperation.Save);

            new NoteWithDateEntity {
                CreationTime = DateTime.Now.AddDays(-100).AddHours(-8), Text = "The blue one with the angel", Target = mellon
            }
            .Execute(NoteWithDateOperation.Save);

            LabelEntity wea = new LabelEntity {
                Name = "WEA International", Country = usa, Owner = virgin.ToLite(), Node = virgin.Node.FirstChild()
            }
            .Execute(LabelOperation.Save);

            new AlbumEntity
            {
                Name   = "Zeitgeist",
                Year   = 2007,
                Author = smashingPumpkins,
                Songs  = { new SongEmbedded {
                               Name = "Tarantula"
                           } },
                BonusTrack = new SongEmbedded {
                    Name = "1976"
                },
                Label = wea,
            }.Execute(AlbumOperation.Save);

            new AlbumEntity
            {
                Name   = "American Gothic",
                Year   = 2008,
                Author = smashingPumpkins,
                Songs  = { new SongEmbedded {
                               Name = "The Rose March", Duration = TimeSpan.FromSeconds(276)
                           } },
                Label = wea,
            }.Execute(AlbumOperation.Save);

            var pa = new PersonalAwardEntity {
                Category = "Best Artist", Year = 1983, Result = AwardResult.Won
            }.Execute(AwardOperation.Save);

            ArtistEntity michael  = new ArtistEntity
            {
                Name      = "Michael Jackson",
                Dead      = true,
                LastAward = pa,
                Status    = Status.Single,
                Friends   = { smashingPumpkins.Members.SingleEx(a => a.Name.Contains("Billy Corgan")).ToLite() }
            }.Execute(ArtistOperation.Save);;

            new NoteWithDateEntity {
                CreationTime = new DateTime(2009, 6, 25, 0, 0, 0), Text = "Death on June, 25th", Target = michael
            }
            .Execute(NoteWithDateOperation.Save);

            new NoteWithDateEntity {
                CreationTime = new DateTime(2000, 1, 1, 0, 0, 0), Text = null, Target = michael
            }
            .SetMixin((CorruptMixin c) => c.Corrupt, true)
            .Do(n => n.Mixin <ColaboratorsMixin>().Colaborators.Add(michael))
            .Execute(NoteWithDateOperation.Save);

            LabelEntity universal = new LabelEntity {
                Name = "UMG Recordings", Country = usa, Node = virgin.Node.NextSibling()
            }
            .Execute(LabelOperation.Save);

            new AlbumEntity
            {
                Name   = "Ben",
                Year   = 1972,
                Author = michael,
                Songs  = { new SongEmbedded {
                               Name = "Ben"
                           } },
                BonusTrack = new SongEmbedded {
                    Name = "Michael"
                },
                Label = universal,
            }.Execute(AlbumOperation.Save);

            LabelEntity sony      = new LabelEntity {
                Name = "Sony", Country = japan, Node = universal.Node.NextSibling()
            }
            .Execute(LabelOperation.Save);

            new AlbumEntity
            {
                Name   = "Thriller",
                Year   = 1982,
                Author = michael,
                Songs  = "Wanna Be Startin' Somethin', Thriller, Beat It"
                         .Split(',').Select(s => new SongEmbedded {
                    Name = s.Trim()
                }).ToMList(),
                BonusTrack = new SongEmbedded {
                    Name = "Billie Jean"
                },
                Label = sony
            }.Execute(AlbumOperation.Save);

            LabelEntity mjj = new LabelEntity {
                Name = "MJJ", Country = usa, Owner = sony.ToLite(), Node = sony.Node.FirstChild()
            }
            .Execute(LabelOperation.Save);

            new AlbumEntity
            {
                Name   = "Bad",
                Year   = 1989,
                Author = michael,
                Songs  = "Bad, Man in the Mirror, Dirty Diana, Smooth Criminal"
                         .Split(',').Select(s => new SongEmbedded {
                    Name = s.Trim()
                }).ToMList(),
                Label = mjj
            }.Execute(AlbumOperation.Save);

            new AlbumEntity
            {
                Name   = "Dangerous",
                Year   = 1991,
                Author = michael,
                Songs  = "Black or White, Who Is It, Give it to Me"
                         .Split(',').Select(s => new SongEmbedded {
                    Name = s.Trim()
                }).ToMList(),
                Label = mjj
            }.Execute(AlbumOperation.Save);

            new AlbumEntity
            {
                Name   = "HIStory",
                Year   = 1995,
                Author = michael,
                Songs  = "Billie Jean, Stranger In Moscow"
                         .Split(',').Select(s => new SongEmbedded {
                    Name = s.Trim()
                }).ToMList(),
                BonusTrack = new SongEmbedded {
                    Name = "Heal The World"
                },
                Label = mjj
            }.Execute(AlbumOperation.Save);

            new AlbumEntity
            {
                Name   = "Blood on the Dance Floor",
                Year   = 1995,
                Author = michael,
                Songs  = "Blood on the Dance Floor, Morphine"
                         .Split(',').Select(s => new SongEmbedded {
                    Name = s.Trim()
                }).ToMList(),
                Label = mjj
            }.Execute(AlbumOperation.Save);;

            var ga = (GrammyAwardEntity) new GrammyAwardEntity {
                Category = "Foreing Band", Year = 2001, Result = AwardResult.Won
            }
            .Execute(AwardOperation.Save);

            BandEntity sigurRos = new BandEntity
            {
                Name    = "Sigur Ros",
                Members = "Jón Þór Birgisson, Georg Hólm, Orri Páll Dýrason"
                          .Split(',').Select(s => new ArtistEntity {
                    Name = s.Trim()
                }.Execute(ArtistOperation.Save)).ToMList(),
                LastAward = ga,
            }.Execute(BandOperation.Save);

            LabelEntity fatCat = new LabelEntity {
                Name = "FatCat Records", Country = usa, Owner = universal.ToLite(), Node = universal.Node.FirstChild()
            }
            .Execute(LabelOperation.Save);

            new AlbumEntity
            {
                Name   = "Ágaetis byrjun",
                Year   = 1999,
                Author = sigurRos,
                Songs  = "Scefn-g-englar"
                         .Split(',').Select(s => new SongEmbedded {
                    Name = s.Trim()
                }).ToMList(),
                BonusTrack = new SongEmbedded {
                    Name = "Intro"
                },
                Label = fatCat,
            }.Execute(AlbumOperation.Save);

            LabelEntity emi = new LabelEntity {
                Name = "EMI", Country = usa, Node = sony.Node.NextSibling()
            }.Execute(LabelOperation.Save);

            new AlbumEntity
            {
                Name   = "Takk...",
                Year   = 2005,
                Author = sigurRos,
                Songs  = "Hoppípolla, Glósóli, Saeglópur"
                         .Split(',').Select(s => new SongEmbedded {
                    Name = s.Trim()
                }).ToMList(),
                BonusTrack = new SongEmbedded {
                    Name = "Svo hljótt"
                },
                Label = emi
            }.Execute(AlbumOperation.Save);

            new AwardNominationEntity {
                Author = sigurRos.ToLite(), Award = ga.ToLite()
            }.Save();
            new AwardNominationEntity {
                Author = michael.ToLite(), Award = ga.ToLite()
            }.Save();
            new AwardNominationEntity {
                Author = smashingPumpkins.ToLite(), Award = ga.ToLite()
            }.Save();

            new AwardNominationEntity {
                Author = sigurRos.ToLite(), Award = ama.ToLite()
            }.Save();
            new AwardNominationEntity {
                Author = michael.ToLite(), Award = ama.ToLite()
            }.Save();
            new AwardNominationEntity {
                Author = smashingPumpkins.ToLite(), Award = ama.ToLite()
            }.Save();

            new AwardNominationEntity {
                Author = michael.ToLite(), Award = pa.ToLite()
            }.Save();
            new AwardNominationEntity {
                Author = michael.ToLite(), Award = null
            }.Save();

            new ConfigEntity
            {
                EmbeddedConfig = new EmbeddedConfigEmbedded
                {
                    Awards = { ga.ToLite() }
                }
            }.Execute(ConfigOperation.Save);
        }
Beispiel #28
0
 public static SqlHierarchyId NextSibling(this SqlHierarchyId sibling)
 {
     return(sibling.GetAncestor(1).GetDescendant(sibling, SqlHierarchyId.Null));
 }
Beispiel #29
0
 public static SqlHierarchyId FirstChild(this SqlHierarchyId parent)
 {
     return(parent.GetDescendant(SqlHierarchyId.Null, SqlHierarchyId.Null));
 }
 public static SqlHierarchyId ToSqlHierarchyId(this string value)
 {
     return(string.IsNullOrEmpty(value)
     ? SqlHierarchyId.Null
     : SqlHierarchyId.Parse(value));
 }
Beispiel #31
0
 public void ThrowsOnNegativeAncestor()
 {
     var root   = SqlHierarchyId.GetRoot();
     var parent = root.GetAncestor(-1);
 }