Example #1
0
        public async Task Store(TreeService treeService)
        {
            System.Diagnostics.Debug.WriteLine("Family {0}", this.family.Id);
            await treeService.Update(this.family).ConfigureAwait(false);

            await treeService.UpdateRelations(this.family.Id, this.spouses, this.children).ConfigureAwait(false);
        }
Example #2
0
        private async Task UpdateNodesAsync()
        {
            var oldNodesVisible = CollectionsVisible;

            try
            {
                UI = await TreeService.GetNodesAsync(CollectionAlias, ParentPath, _pageNr, PageSize);

                if (UI == null)
                {
                    return;
                }

                CollectionsVisible = UI.Nodes.ToDictionary(x => x.Id, x => x.DefaultOpenCollections);

                // restore the view state with the new nodes
                if (oldNodesVisible != null)
                {
                    foreach (var node in oldNodesVisible.Where(x => x.Value))
                    {
                        if (CollectionsVisible.ContainsKey(node.Key))
                        {
                            CollectionsVisible[node.Key] = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Error = ex.Message;
            }

            StateHasChanged();
        }
Example #3
0
        /// <summary>
        /// Finds the last folder.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="path">The path.</param>
        /// <param name="delim">The delim.</param>
        /// <param name="pattern">The pattern.</param>
        /// <returns></returns>
        private static Folder FindFolderByPattern(Folder folder, string path, char delim,
                                                  string pattern)
        {
            Folder      retVal = null;
            TreeService tree   = folder.GetTreeService();

            //recursion end point
            if (pattern.Equals(path, StringComparison.InvariantCultureIgnoreCase))
            {
                return(folder);
            }

            foreach (TreeNode node in tree.GetChildNodes())
            {
                String folderPath = path + delim + ((Folder)node.InnerObject).Name;
                if (retVal != null)
                {
                    break;
                }

                if (pattern.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase))
                {
                    retVal = FindFolderByPattern((Folder)node.InnerObject, folderPath,
                                                 delim, pattern);
                }
            }

            return(retVal);
        }
Example #4
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new ApplicationUser()
            {
                FirstName = model.FirstName, SecondName = model.SecondName, LastName = model.LastName, UserName = model.Email, Email = model.Email, DateOfBith = model.DateOfBith, Photo = model.Photo,
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            UnitOfWork  uow     = new UnitOfWork(new ApplicationDbContext());
            TreeService service = new TreeService(uow);

            service.CreateTree(user.Id);
            uow.Commit();
            return(Ok());
        }
        private void RenderCalendar(ref XmlTree tree)
        {
            if (null != this._db)
            {
                var calendars = this._db.Query <ECalendar>("SELECT * FROM ec_calendars");

                foreach (var c in calendars)
                {
                    XmlTreeNode node = XmlTreeNode.Create(this);

                    node.NodeID   = c.Id.ToString();
                    node.NodeType = "CalendarEntry";
                    node.Text     = c.Calendarname;
                    node.Icon     = "calendar.png";
                    node.Action   = "javascript:openCalendar(" + c.Id.ToString() + ")";

                    var treeService = new TreeService(c.Id, TreeAlias, ShowContextMenu, IsDialog, DialogMode, app, "CalendarEntry-" + c.Id.ToString());
                    node.Source = treeService.GetServiceUrl();

                    node.Menu.Clear();
                    //node.Menu.Add(ActionNew.Instance);
                    node.Menu.Add(ActionDelete.Instance);

                    tree.Add(node);
                }
            }
        }
Example #6
0
        public ActionResult TreeLabel(long id)
        {
            var tree = TreeService.Get(id);
            var data = TreeTagPainter.Paint(tree, HttpContext.Request.Url.Host);

            return(File(data, "image/jpeg"));
        }
        protected override async Task OnParametersSetAsync()
        {
            try
            {
                UI = await TreeService.GetCollectionAsync(CollectionAlias, ParentPath);

                NodesVisible = NodesVisible || (UI?.DefaultOpenEntities ?? false);

                if (Mediator.GetLatestEventArgs <NavigationEventArgs>() is NavigationEventArgs @event)
                {
                    await LocationChangedAsync(this, @event);
                }
            }
            catch (UnauthorizedAccessException)
            {
                UI = TreeCollectionUI.None;
            }
            catch (Exception ex)
            {
                UI    = null;
                Error = ex.Message;
            }

            StateHasChanged();
        }
Example #8
0
        public ActionResult Edit(long id)
        {
            var model = TreeService.Get(id);

            ConvertViewModel(model);
            return(View(model));
        }
Example #9
0
        public ActionResult View(long id)
        {
            var tree = TreeService.Get(id);

            tree = ConvertViewModel(tree);
            return(View(tree));
        }
Example #10
0
        public ActionResult Index(Models.TreeQueryModel q)
        {
            var user = GetUser();

            if (user != null)
            {
                if (q.Jump.HasValue)
                {
                    q.Current = q.Jump.Value;
                    q.Jump    = null;
                }
                var models = TreeService.Query(user.ID).ToList();
                var result = DoQuery(q, models);
                ViewBag.q = q;
                int pageSize  = 50;
                int count     = result.Count() % pageSize == 0 ? result.Count() / pageSize : result.Count() / pageSize + 1;
                int pageStart = q.Current - pageSize < 1 ? 1 : q.Current - pageSize;
                int pageEnd   = q.Current + 2 > count ? count : q.Current + 2;

                List <int> pages = new List <int>();
                for (int i = pageStart; i <= pageEnd; i++)
                {
                    pages.Add(i);
                }
                ViewBag.page = pages;

                result = result.Skip(q.Current * pageSize - pageSize).Take(pageSize).ToList();
                return(View(result));
            }
            else
            {
                return(RedirectToAction("Login", "User"));
            }
        }
Example #11
0
        /// <summary>
        /// Deletes the folder.
        /// </summary>
        /// <param name="folder">The folder.</param>
        public static void DeleteFolder(CalendarFolder folder)
        {
            if (folder == null)
            {
                throw new ArgumentNullException("folder");
            }

            using (TransactionScope tran = DataContext.Current.BeginTransaction())
            {
                TreeService treeService = folder.GetTreeService();

                //Erase all child folders
                foreach (TreeNode node in TreeManager.GetAllChildNodes(treeService.CurrentNode))
                {
                    CalendarFolder childFolder = (CalendarFolder)node.InnerObject;
                    EraseFolder(childFolder);
                    treeService.RemoveChild(node.ObjectId);
                    childFolder.Delete();
                }

                //Erase current folder
                EraseFolder(folder);
                folder.Delete();

                tran.Commit();
            }
        }
Example #12
0
        public HttpResponseMessage Index(
            [System.Web.Mvc.ModelBinder(typeof(Grit.Utility.Web.Json.JsonNetModelBinder))] Envelope envelope)
        {
            var client = ClientService.GetClient(envelope.Id);

            if (client == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Client not found"));
            }

            var decrypted = EnvelopeService.PublicDecrypt(envelope, client.PublicKey);
            var req       = JsonConvert.DeserializeObject <SettingsRequest>(decrypted);

            if (req.Client != envelope.Id)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid client"));
            }

            var tree = TreeService.GetTree(Constants.TREE_NODE);
            SettingsResponse settings = NodeService.GetClientSettings(client, tree)
                                        .Filter(req.Pattern);

            string json = JsonConvert.SerializeObject(settings);

            Envelope resp = EnvelopeService.Encrypt(client.Name, json, client.PublicKey);

            return(Request.CreateResponse(HttpStatusCode.OK, resp));
        }
 public ResourceItem(object target, object key, TreeItem parent, TreeService treeService, bool hasError)
     : base(target, parent, treeService)
 {
     this.key       = key;
     this.hasError  = hasError;
     this.SortOrder = int.MaxValue;
 }
Example #14
0
        public ActionResult Group([ModelBinder(typeof(JsonNetModelBinder))] IList <JsTreeNode> nodes)
        {
            var root = new JsTreeParser().Parse(Constants.TREE_NODE, nodes);

            TreeService.SaveTree(root);
            return(new JsonNetResult(nodes));
        }
        public void TreeService_Add_Throws_On_Null_Tree()
        {
            //Arrange
            _service = new TreeService(_mockUnitOfWork.Object);

            //Act,Assert
            Assert.Throws<ArgumentNullException>(() => _service.Add(null));
        }
Example #16
0
 private void OnNodesUpdate()
 {
     _eventHandle?.Dispose();
     _eventHandle = TreeService.SubscribeToUpdates(CollectionAlias, async() =>
     {
         await OnNodesUpdateAsync();
         OnNodesUpdate();
     });
 }
        public void WhichOneEmpty_ReturnsCorrectResults()
        {
            TreeService service = new TreeService();
            var         sGates  = "L,R,R,L,L,L,L,R,L,R,R,L,L,R,L";

            var actual = service.WhichOneEmpty(4, sGates.Split(','));

            Assert.AreEqual(actual, 12);
        }
Example #18
0
 private void OnNodesUpdate()
 {
     _nodeEventHandle?.Dispose();
     _nodeEventHandle = TreeService.SubscribeToRepositoryUpdates(CollectionAlias, async() =>
     {
         await InvokeAsync(() => OnNodesUpdateAsync());
         OnNodesUpdate();
     });
 }
Example #19
0
        public SnoopUI()
        {
            this.TreeService = TreeService.From(this.CurrentTreeType);

            this.filterCall = new DelayedCall(this.ProcessFilter, DispatcherPriority.Background);

            this.InitializeComponent();

            // wrap the following PresentationTraceSources.Refresh() call in a try/catch
            // sometimes a NullReferenceException occurs
            // due to empty <filter> elements in the app.config file of the app you are snooping
            // see the following for more info:
            // http://snoopwpf.codeplex.com/discussions/236503
            // http://snoopwpf.codeplex.com/workitem/6647
            try
            {
                PresentationTraceSources.Refresh();
                PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
            }
            catch (NullReferenceException)
            {
                // swallow this exception since you can snoop just fine anyways.
            }

            this.CommandBindings.Add(new CommandBinding(IntrospectCommand, this.HandleIntrospection));
            this.CommandBindings.Add(new CommandBinding(RefreshCommand, this.HandleRefresh));
            this.CommandBindings.Add(new CommandBinding(HelpCommand, this.HandleHelp));

            this.CommandBindings.Add(new CommandBinding(InspectCommand, this.HandleInspect));

            this.CommandBindings.Add(new CommandBinding(SelectFocusCommand, this.HandleSelectFocus));
            this.CommandBindings.Add(new CommandBinding(SelectFocusScopeCommand, this.HandleSelectFocusScope));

            //NOTE: this is up here in the outer UI layer so ESC will clear any typed filter regardless of where the focus is
            // (i.e. focus on a selected item in the tree, not in the property list where the search box is hosted)
            this.CommandBindings.Add(new CommandBinding(ClearSearchFilterCommand, this.ClearSearchFilterHandler));

            this.CommandBindings.Add(new CommandBinding(CopyPropertyChangesCommand, this.CopyPropertyChangesHandler));

            InputManager.Current.PreProcessInput += this.HandlePreProcessInput;
            this.Tree.SelectedItemChanged        += this.HandleTreeSelectedItemChanged;

            // we can't catch the mouse wheel at the ZoomerControl level,
            // so we catch it here, and relay it to the ZoomerControl.
            this.MouseWheel += this.SnoopUI_MouseWheel;

            this.filterTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(0.3)
            };
            this.filterTimer.Tick += (s, e) =>
            {
                this.EnqueueAfterSettingFilter();
                this.filterTimer.Stop();
            };
        }
        public void FormTree_ReturnsIncorrectGateStatusError()
        {
            TreeService service = new TreeService();
            var         sGates  = "L,R,R,L,L,L,L,R,L,R,R,L,";

            var tree = service.FormTree("4", sGates);

            Assert.IsTrue(tree.Error);
            Assert.AreEqual(tree.ErrorMessage, "Gate status value/s not set correctly.");
        }
        public void FormTree_ReturnsGatesNotMatchError()
        {
            TreeService service = new TreeService();
            var         sGates  = "L,R,R,L,L,L,L,R,L,R,R,L,L";

            var tree = service.FormTree("4", sGates);

            Assert.IsTrue(tree.Error);
            Assert.AreEqual(tree.ErrorMessage, "Gates do not match depth.");
        }
        public void FormTree_ReturnsNotANumberError()
        {
            TreeService service = new TreeService();
            var         sGates  = "L,R,R,L,L,L,L,R,L,R,R,L,L,R,L";

            var tree = service.FormTree("Four", sGates);

            Assert.IsTrue(tree.Error);
            Assert.AreEqual(tree.ErrorMessage, "The depth is not a number.");
        }
Example #23
0
        /// <summary>
        /// Initializes the control and looks up the tree structures that are required to be rendered.
        /// Properties of the control (or SetTreeService) need to be set before pre render or calling
        /// GetJSONContextMenu or GetJSONNode
        /// </summary>
        protected void Initialize()
        {
            //use the query strings if the TreeParams isn't explicitly set
            if (m_TreeService == null)
            {
                m_TreeService = TreeRequestParams.FromQueryStrings().CreateTreeService();
            }
            m_TreeService.App = GetCurrentApp();

            // Validate permissions
            if (!BasePages.BasePage.ValidateUserContextID(BasePages.BasePage.umbracoUserContextID))
            {
                return;
            }
            UmbracoEnsuredPage page = new UmbracoEnsuredPage();

            if (!page.ValidateUserApp(GetCurrentApp()))
            {
                throw new ArgumentException("The current user doesn't have access to this application. Please contact the system administrator.");
            }

            //find all tree definitions that have the current application alias that are ACTIVE.
            //if an explicit tree has been requested, then only load that tree in.
            //m_ActiveTreeDefs = TreeDefinitionCollection.Instance.FindActiveTrees(GetCurrentApp());

            m_ActiveTreeDefs = Services.ApplicationTreeService.GetApplicationTrees(GetCurrentApp(), true).ToList();

            if (!string.IsNullOrEmpty(this.TreeType))
            {
                m_ActiveTreeDefs = m_ActiveTreeDefs
                                   .Where(x => x.Alias == this.TreeType)
                                   .ToList(); //this will only return 1
            }

            //find all tree defs that exists for the current application regardless of if they are active
            var appTreeDefs = Services.ApplicationTreeService.GetApplicationTrees(GetCurrentApp()).ToList();

            //Create the BaseTree's based on the tree definitions found
            foreach (var treeDef in appTreeDefs)
            {
                //create the tree and initialize it
                var bTree = LegacyTreeDataConverter.GetLegacyTreeForLegacyServices(treeDef);
                //BaseTree bTree = treeDef.CreateInstance();
                bTree.SetTreeParameters(m_TreeService);

                //store the created tree
                m_AllAppTrees.Add(bTree);
                if (treeDef.Initialize)
                {
                    m_ActiveTrees.Add(bTree);
                }
            }

            m_IsInit = true;
        }
Example #24
0
        public async Task TestTreeService()
        {
            ITreeService treeService = new TreeService(null);
            await treeService.InitializeAsync();

            var tree = treeService.GetTree();

            Assert.AreEqual("C-1", tree[0].id);
            Assert.AreEqual("第1章 极限与连续(523题)", tree[0].text);
            Assert.AreEqual("1-1", tree[0].children[0].id);
        }
Example #25
0
    public void GetNodes()
    {
        XmlTree        xTree      = new XmlTree();
        ITreeService   treeParams = new TreeService(1099, "content", false, false, TreeDialogModes.none, null);
        TreeDefinition tree       = TreeDefinitionCollection.Instance.FindTree("content");
        BaseTree       instance   = tree.CreateInstance();

        instance.SetTreeParameters((ITreeService)treeParams);
        instance.Render(ref xTree);
        Response.ContentType = "application/json";
        Response.Write(((object)xTree).ToString());
    }
        public void FormTree_ReturnsCorrectResults()
        {
            TreeService service = new TreeService();
            var         sGates  = "L,R,R,L,L,L,L,R,L,R,R,L,L,R,L";

            var tree = service.FormTree("4", sGates);

            Assert.AreEqual(tree.Depth, 4);
            Assert.AreEqual(tree.Gates.Length, 15);
            Assert.IsFalse(tree.Error);
            Assert.IsNull(tree.ErrorMessage);
        }
Example #27
0
        public ActionResult Index()
        {
            var nodes = NodeService.GetNodes();
            var root  = TreeService.GetTree(Constants.TREE_NODE);

            ViewBag.Tree = new Grit.Tree.JsTree.JsTreeBuilder <Node>(
                x => x.Name,
                x => x.NodeId)
                           .Build(root, nodes)
                           .children;
            return(View());
        }
        void TreeProxy_InsertTreeCompleted(object sender, TreeService.InsertTreeCompletedEventArgs e)
        {
            int result = e.Result;

            if (result>0)
            {
                MessageBox.Show("Message saved successfully!");
            }
            else
            {
                MessageBox.Show("Message was not save!");
            }
        }
Example #29
0
        /// <summary>
        /// Converts the tree parameters to a tree service object
        ///
        /// </summary>
        ///
        /// <returns/>
        public TreeService CreateTreeService()
        {
            TreeService treeService = new TreeService();

            treeService.ShowContextMenu = this.ShowContextMenu;
            treeService.IsDialog        = this.IsDialog;
            treeService.DialogMode      = this.DialogMode;
            treeService.App             = this.Application;
            treeService.TreeType        = this.TreeType;
            treeService.NodeKey         = this.NodeKey;
            treeService.StartNodeID     = this.StartNodeID;
            treeService.FunctionToCall  = this.FunctionToCall;
            return(treeService);
        }
Example #30
0
        static void Main(string[] args)
        {
            var constants = new Constants();

            if (CommandLine.Parser.Default.ParseArguments(args, constants))
            {
                var data        = ReadData("training.csv");
                var treeService = new TreeService(constants);
                var t           = new Node();
                if (constants.DecisionAlgorithm == "information-gain")
                {
                    Console.WriteLine("Building tree using information gain...");
                }
                else if (constants.DecisionAlgorithm == "gini-index")
                {
                    Console.WriteLine("Building tree using gini index...");
                }
                else
                {
                    Console.WriteLine("Building tree with gini and information gain");
                }

                t = treeService.BuildTree(data, constants.DecisionAlgorithm);

                Console.WriteLine("Traversing Tree...");
                var i = treeService.DetermineAccuracy(data, t);
                Console.WriteLine("Our tree was " + i + "% accurate!");


                //run on testing data
                data = ReadData("testing.csv");
                int      length = data.Count;
                string[] lines  = new string[length + 1];
                lines[0] = "id,class";
                for (int k = 0; k < length; k++)
                {
                    var c = treeService.TraverseTree(data[k], t);
                    lines[k + 1] = data[k].id + "," + c;
                }
                System.IO.File.WriteAllLines(@"Data\results.csv", lines);
            }
            else
            {
                Console.WriteLine("Arguments failed to parse. Program exiting.");
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Example #31
0
        /// <summary>
        /// Render the top Root Nodes.
        /// - Calendar -> The Root of all Calendars
        /// - Locations -> The Root of all Locations
        /// </summary>
        /// <param name="tree">The current tree</param>
        private void PopulateRootNodes(ref XmlTree tree)
        {
            XmlTreeNode xNode = XmlTreeNode.Create(this);

            xNode.NodeID = "1";
            xNode.Text   = "Calendar";
            //xNode.Action = "javascript:openCustom('" + "1" + "');";
            xNode.Icon     = "calendar.png";
            xNode.OpenIcon = "folder_o.gif";
            xNode.NodeType = "EventCalendarBase";

            var treeService = new TreeService(-1, TreeAlias, ShowContextMenu, IsDialog, DialogMode, app, "CalendarBase");

            xNode.Source = treeService.GetServiceUrl();

            xNode.Menu.Clear();
            xNode.Menu.Add(ActionNew.Instance);
            xNode.Menu.Add(ActionRefresh.Instance);

            tree.Add(xNode);

            xNode        = XmlTreeNode.Create(this);
            xNode.NodeID = "2";
            xNode.Text   = "Locations";
            //xNode.Action = "javascript:openCustom('" + "1" + "');";
            xNode.Icon     = "map.png";
            xNode.OpenIcon = "folder_o.gif";
            xNode.NodeType = "EventLocationBase";

            treeService  = new TreeService(-1, TreeAlias, ShowContextMenu, IsDialog, DialogMode, app, "LocationBase");
            xNode.Source = treeService.GetServiceUrl();

            xNode.Menu.Clear();
            xNode.Menu.Add(ActionNew.Instance);
            xNode.Menu.Add(ActionRefresh.Instance);

            tree.Add(xNode);

            //xNode = XmlTreeNode.Create(this);
            //xNode.NodeID = "3";
            //xNode.Text = "Settings";
            //xNode.Action = "javascript:openSettings();";
            //xNode.Icon = "cog.png";
            //xNode.NodeType = "GeneralSettings";
            //xNode.Menu.Clear();

            //tree.Add(xNode);
        }
Example #32
0
        public ActionResult Map()
        {
            var clients  = ClientService.GetClients();
            var leftTree = new Grit.Tree.Node(1);

            ViewBag.LeftTree = new Grit.Tree.JsTree.JsTreeBuilder <Settings.Model.Client>(x => x.Name, x => x.ClientId, x => x.Nodes)
                               .Build(leftTree, clients)
                               .children;

            var nodes     = NodeService.GetNodes();
            var rightTree = TreeService.GetTree(Constants.TREE_NODE);

            ViewBag.RightTree = new Grit.Tree.JsTree.JsTreeBuilder <Node>(x => x.Name, x => x.NodeId)
                                .Build(rightTree, nodes)
                                .children;

            return(View());
        }
        public void TreeService_Add_Calls_Repsoitory_Add_Method_With_The_Same_Tree_Object_It_Recieved()
        {
            // Create test data
            var newTree = new Tree
                                {
                                    Name = "Foo"
                                };

            //SetUp Mock
            var mockRepository = new Mock<IRepository<Tree>>();
            _mockUnitOfWork.Setup(d => d.GetRepository<Tree>()).Returns(mockRepository.Object);

            //Arrange
            _service = new TreeService(_mockUnitOfWork.Object);

            //Act
            _service.Add(newTree);

            //Assert
            mockRepository.Verify(r => r.Add(newTree));
        }
Example #34
0
 public TreeViewModel(TreeService.Tree tree)
 {
     this.tree = tree;
 }
Example #35
0
 // GET api/values
 public string Get()
 {
     TreeService service = new TreeService();
     return HttpStatusCode.NotImplemented.ToString();
 }
        public void TreeService_Get_Throws_On_Negative_Id()
        {
            //Arrange
            _service = new TreeService(_mockUnitOfWork.Object);

            //Assert
            Assert.Throws<IndexOutOfRangeException>(() => _service.Get(-1));
        }
        public void TreeService_Get_Calls_Repository_GetAll()
        {
            //Arrange
            var mockRepository = new Mock<IRepository<Tree>>();
            mockRepository.Setup(r => r.GetAll()).Returns(GetTrees(TestConstants.PAGE_TotalCount));
            _mockUnitOfWork.Setup(d => d.GetRepository<Tree>()).Returns(mockRepository.Object);

            _service = new TreeService(_mockUnitOfWork.Object);
            const int id = TestConstants.ID_Exists;

            //Act
            _service.Get(id);

            //Assert
            mockRepository.Verify(r => r.GetAll());
        }
        public void TreeService_Get_Returns_Null_On_InValid_Id()
        {
            //Arrange
            var mockRepository = new Mock<IRepository<Tree>>();
            mockRepository.Setup(r => r.GetAll()).Returns(GetTrees(TestConstants.PAGE_TotalCount));
            _mockUnitOfWork.Setup(d => d.GetRepository<Tree>()).Returns(mockRepository.Object);

            _service = new TreeService(_mockUnitOfWork.Object);
            const int id = TestConstants.ID_NotFound;

            //Act
            var tree = _service.Get(id);

            //Assert
            Assert.IsNull(tree);
        }
        public void TreeService_Get_ByPage_Overload_Calls_Repository_GetAll()
        {
            //Arrange
            var mockRepository = new Mock<IRepository<Tree>>();
            _mockUnitOfWork.Setup(d => d.GetRepository<Tree>()).Returns(mockRepository.Object);

            _service = new TreeService(_mockUnitOfWork.Object);

            //Act
            _service.Get(t => true, 0, 5);

            //Assert
            mockRepository.Verify(r => r.GetAll());
        }
 void treeProxy_GetTreesCompleted(object sender, TreeService.GetTreesCompletedEventArgs e)
 {
     this.treeList = e.Result;
     dataGrid1.ItemsSource = treeList;
 }
        public void TreeService_Add_Calls_UnitOfWork_Commit_Method()
        {
            // Create test data
            var newTree = new Tree
            {
                Name = "Foo"
            };

            //Create Mock
            var mockRepository = new Mock<IRepository<Tree>>();
            _mockUnitOfWork.Setup(d => d.GetRepository<Tree>()).Returns(mockRepository.Object);

            //Arrange
            _service = new TreeService(_mockUnitOfWork.Object);

            //Act
            _service.Add(newTree);

            //Assert
            _mockUnitOfWork.Verify(db => db.Commit());
        }
        public void TreeService_Get_ByPage_Overload_Returns_PagedList_Of_Trees()
        {
            //Arrange
            var mockRepository = new Mock<IRepository<Tree>>();
            mockRepository.Setup(r => r.GetAll()).Returns(GetTrees(TestConstants.PAGE_TotalCount));
            _mockUnitOfWork.Setup(d => d.GetRepository<Tree>()).Returns(mockRepository.Object);

            _service = new TreeService(_mockUnitOfWork.Object);

            //Act
            var trees = _service.Get(t => true, 0, TestConstants.PAGE_RecordCount);

            //Assert
            Assert.IsInstanceOf<IPagedList<Tree>>(trees);
            Assert.AreEqual(TestConstants.PAGE_TotalCount, trees.TotalCount);
            Assert.AreEqual(TestConstants.PAGE_RecordCount, trees.PageSize);
        }