/// <summary>
        /// <see cref="Microsoft.Samples.NLayerApp.DistributedServices.MainModule.IMainModuleService"/>
        /// </summary>
        /// <param name="customer"><see cref="Microsoft.Samples.NLayerApp.DistributedServices.MainModule.IMainModuleService"/></param>
        public void ChangeCustomer(Customer customer)
        {
            try
            {
                //Resolve root dependency and perform operation
                ICustomerManagementService customerService = IoCFactory.Instance.CurrentContainer.Resolve<ICustomerManagementService>();
                customerService.ChangeCustomer(customer);
            }
            catch (ArgumentNullException ex)
            {
                //trace data for internal health system and return specific FaultException here!
                //Log and throw is a knowed anti-pattern but in this point ( entry point for clients this is admited!)

                //log exception for manage health system
                ITraceManager traceManager = IoCFactory.Instance.CurrentContainer.Resolve<ITraceManager>();
                traceManager.TraceError(ex.Message);

                //propagate exception to client
                ServiceError detailedError = new ServiceError()
                {
                    ErrorMessage = Resources.Messages.exception_InvalidArguments
                };

                throw new FaultException<ServiceError>(detailedError);
            }

        }
        /// <summary>
        /// <see cref="Microsoft.Samples.NLayerApp.Application.MainModule.CustomersManagement.ICustomerManagementService"/>
        /// </summary>
        /// <param name="customer"><see cref="Microsoft.Samples.NLayerApp.Application.MainModule.CustomersManagement.ICustomerManagementService"/></param>
        public void AddCustomer(Customer customer)
        {
            //Begin unit of work ( if Transaction is required init here a new TransactionScope element
            IUnitOfWork unitOfWork = _customerRepository.UnitOfWork as IUnitOfWork;


            _customerRepository.Add(customer);


            //Complete changes in this unit of work
            unitOfWork.Commit();
        }
        /// <summary>
        /// <see cref="Microsoft.Samples.NLayerApp.Application.MainModule.CustomersManagement.ICustomerManagementService"/>
        /// </summary>
        /// <param name="customer"><see cref="Microsoft.Samples.NLayerApp.Application.MainModule.CustomersManagement.ICustomerManagementService"/></param>
        public void ChangeCustomer(Customer customer)
        {
            if (customer == (Customer)null)
                throw new ArgumentNullException("customer");

            IUnitOfWork unitOfWork = _customerRepository.UnitOfWork as IUnitOfWork;

            _customerRepository.Modify(customer);

            unitOfWork.CommitAndRefreshChanges();

        }
        public VMCustomer(Customer current)
        {

            editCommand = new DelegateCommand<object>(EditExecute);
            backCommand = new DelegateCommand<object>(BackExecute);
            currentCustomerOrders = new ObservableCollection<Order>();

            if (!IsDesignTime)
            {
                Customer = current;
                GetCustomerOrders();
            }

        }
        public VMCustomerListView()
        {
            deleteCommand = new DelegateCommand<object>(DeleteExecute);
            editCommand = new DelegateCommand<object>(EditExecute);
            viewCommand = new DelegateCommand<object>(ViewExecute);
            addCommand = new DelegateCommand<object>(AddExecute);
            searchCommand = new DelegateCommand<object>(SearchExecute);

            customers = new ObservableCollection<Customer>();
            this.currentCustomer = new Customer();

            if (!IsDesignTime)
            {
                GetCustomers();
            }

        }
        public void Serialized_Hidden_Returns_A_Hidden_Field_With_The_Entity_Serialized()
        {
            //Arrang
            Customer customer = new Customer();

            
            string serializedCustomer = new SelfTrackingEntityBase64Converter<Customer>().ToBase64(customer);
            
            ViewDataDictionary viewData = new ViewDataDictionary();
            
            SViewContext viewContext = new SViewContext();
            viewContext.ViewData = viewData;
            
            SIViewDataContainer viewDataContainer = new SIViewDataContainer();
            viewDataContainer.ViewDataGet = () => viewData;
            

            HtmlHelper<Customer> helper = new HtmlHelper<Customer>(viewContext, viewDataContainer);
            
            //Act
            MvcHtmlString result = helper.SerializedHidden(customer);
            
            //Assert
            //Parse the result (it creates XML-Compliant HTML)
            XElement element = XElement.Parse(result.ToHtmlString());

            //Ensure it's an input tag.
            Assert.AreEqual("input", element.Name.LocalName);

            //Ensure it's a hidden field.
            Assert.AreEqual("hidden",element.Attribute("type").Value);

            //Ensure it has the correct name
            Assert.AreEqual("CustomerSTE",element.Attribute("name").Value);

            //Ensure it has the correct id
            Assert.AreEqual("CustomerSTE",element.Attribute("id").Value);

            //Ensure the serialized customer is serialized correctly.
            Assert.AreEqual(serializedCustomer, element.Attribute("value").Value);
        }
        public VMAddCustomer()
        {         

            //create default customer information

            this._currentCustomer = new Customer();
            this._currentCustomer.IsEnabled = true;

            this._currentCustomer.Address = new AddressInformation();
            this._currentCustomer.CustomerPicture = new CustomerPicture()
                                                    {
                                                       CustomerId = _currentCustomer.CustomerId,
                                                       Customer = _currentCustomer,
                                                       Photo = null
                                                    };

            this.CompanyName = "Company Name Here...";

            if (!NavigationController.IsInDesignMode)
                this.LoadCountries(); 
        }
 private bool CanDeleteExecute(Customer customer)
 {
     return (customer != null);
 }
 private bool CanEditExecute(Customer customer)
 {
     return (customer != null);
 }
        public VMCustomer(Customer customer)
        {
            if (customer != null)
            {
                //initialize main module service
                IMainModuleService mainModuleService = ProxyLocator.GetMainModuleService();

                this.Customer = mainModuleService.GetCustomerByCode(customer.CustomerCode);

                //load orders for this client
                using (BackgroundWorker worker = new BackgroundWorker())
                {
                    worker.DoWork += delegate(object sender, DoWorkEventArgs e)
                    {
                        try
                        {
                            e.Result = mainModuleService.GetOrdersByOrderInformation(new OrderInformation()
                                                                                    {
                                                                                        CustomerId = customer.CustomerId,
                                                                                        DateTimeFrom = DateTime.MinValue,
                                                                                        DateTimeTo  = DateTime.Now
                                                                                    });
                        }
                        catch
                        {
                            e.Cancel = true;
                        }
                    }; 
                    worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
                    {
                        if (!e.Cancelled && e.Error == null)
                        {
                            List<Order> orders = e.Result as List<Order>;

                            if (orders != null)
                            {
                                DateTimeFormatInfo dtformatInfo = new DateTimeFormatInfo();

                                this.CustomerOrders = orders;
                                this.CurrentCustomerOrdersPie = (from co in this.CustomerOrders 
                                                                 where co.OrderDate.Value.Year == this.Today.Year 
                                                                 group co by co.OrderDate.Value.Month 
                                                                 into g 
                                                                 select new { id = g.Key, Month = dtformatInfo.GetMonthName(g.Key), Count = g.Count() }
                                                                 ).OrderByDescending(o => o.id)
                                                                 .ToList<object>();
                            }
                        }
                    };

                    worker.WorkerSupportsCancellation = true;
                    worker.RunWorkerAsync();
                }
            }
        }
        public void CustomerPicture_Returns_Customer_Image_When_The_Customer_Has_Image()
        {
            /*
             *   Arrange 
             * 1º - Create a dummy list of customers
             * 2º - Initialize stub of SICustomerManagementService
             * 3º - Create controller to test
             */

            byte[] customerPhoto = new byte[] { 0x10 };
            Customer customer = new Customer()
            {
                CustomerCode = "A0001",
                CustomerPicture = new CustomerPicture()
                {
                    Photo = customerPhoto
                }
            };
           
            SICustomerManagementService customerService = new SICustomerManagementService();
            customerService.FindCustomerByCodeString = x => customer;

            //Create the controller
            CustomerController controller = new CustomerController(customerService);

            //Act
            FileContentResult result = controller.CustomerPicture("A0001") as FileContentResult;

            //Assert
            Assert.IsNotNull(result);
            Assert.AreEqual("img", result.ContentType);
            Assert.AreEqual(customerPhoto.Length, result.FileContents.Length);
            for (int i = 0; i < customerPhoto.Length; i++)
            {
                Assert.AreEqual(customerPhoto[i], result.FileContents[i]);
            }

        }
 public ActionResult Edit(Customer customer)
 {
     if (ModelState.IsValid)
     {
         _CustomerService.ChangeCustomer(customer);
         return RedirectToAction("Details", new RouteValueDictionary() { { "customerCode", customer.CustomerCode } });
     }
     else
     {
         return View();
     }
 }
 public ActionResult Create(Customer customer)
 {
     //Check if there aren't validation errors on the customer.
     if (ModelState.IsValid)
     {
         //Add the customer to the data base.
         _CustomerService.AddCustomer(customer);
         //Show the fist page of the customers list.
         return RedirectToAction("Index", new { page = 0, pageSize = 10 });
     }
     else
     {
         //Return the Create view and display the validation errors.
         return View();
     }
 }
        public VMEditCustomer(Customer customer)
        {
            //initialize proxy
            IMainModuleService mainModuleService = ProxyLocator.GetMainModuleService();
            mainModuleService = ProxyLocator.GetMainModuleService();

            if (!NavigationController.IsInDesignMode)
                LoadCountries();

            this.Customer = customer;
        }
        public VMEditCustomer()
        {
            //initialize proxy
            IMainModuleService mainModuleService = ProxyLocator.GetMainModuleService();
            mainModuleService = ProxyLocator.GetMainModuleService();

            //Create default customer
            this._currentCustomer = new Customer()
            {
                Address = new AddressInformation(),
                CustomerPicture = new CustomerPicture()
            };
        }
        public VMEditCustomer()
        {
            this._currentCustomer = new Customer()
            {
                Address = new AddressInformation(),
                CustomerPicture = new CustomerPicture()
            };

        }
        /// <summary>
        /// <see cref="Microsoft.Samples.NLayerApp.Application.MainModule.CustomersManagement.ICustomerManagementService"/>
        /// </summary>
        /// <param name="customer"><see cref="Microsoft.Samples.NLayerApp.Application.MainModule.CustomersManagement.ICustomerManagementService"/></param>
        public void RemoveCustomer(Customer customer)
        {
            if (customer == (Customer)null)
                throw new ArgumentNullException("customer");

            //Begin unit of work ( if Transaction is required init here a new TransactionScope element
            IUnitOfWork unitOfWork = _customerRepository.UnitOfWork as IUnitOfWork;


            //Set IsEnabled property to false, remove customer is only a logical operation 
            // cannot remove this item in  persistence store

            customer.IsEnabled = false;

            _customerRepository.Modify(customer);

            //Complete changes in this unit of work
            unitOfWork.CommitAndRefreshChanges();
        }
        public void Details_Returns_The_Requested_Customer_Details()
        {
            /*
             *   Arrange 
             * 1º - Create a dummy list of customers
             * 2º - Initialize stub of SICustomerManagementService
             * 3º - Create controller to test
             */

            Customer customer = new Customer() { CustomerCode = "A0001", CustomerPicture = null };
            
            SICustomerManagementService customerService = new SICustomerManagementService();
            customerService.FindCustomerByCodeString = x => customer;

            
            CustomerController controller = new CustomerController(customerService);

            //Act
            ViewResult result = controller.Details("A0001") as ViewResult;
            
            //Assert
            Assert.IsNotNull(result);

            Assert.AreEqual("", result.ViewName);

            Customer model = result.ViewData.Model as Customer;
            Assert.IsNotNull(model);

            Assert.AreEqual("A0001", model.CustomerCode);
        }
        public VMCustomer()
        {
            //create default data
            this._currentCustomer = new Customer()
            {
                CustomerPicture = new CustomerPicture() { }
            };

            
        }
        public void Create_Post_Adds_The_Customer_And_Redirects_To_The_Index_Page_With_A_Valid_Customer()
        {
            /*
            *   Arrange 
            * 1º - Create a dummy list of customers
            * 2º - Initialize stub of SICustomerManagementService
            * 3º - Create controller to test
            */

            Customer customer = new Customer() { CustomerCode = "A0001" };
            IList<Customer> customers = new List<Customer>();
            
            SICustomerManagementService customerService = new SICustomerManagementService();
            customerService.AddCustomerCustomer = x => customers.Add(customer);
            
            CustomerController controller = new CustomerController(customerService);

            //Act
            RedirectToRouteResult result =  controller.Create(customer) as RedirectToRouteResult;

            //Assert
            Assert.IsNotNull(result);

            Assert.AreEqual(0, result.RouteValues["page"]);

            Assert.AreEqual(10, result.RouteValues["pageSize"]);

            Assert.AreEqual(1, customers.Count);

            Assert.AreEqual("A0001", customers.First().CustomerCode);
        }
 private void EditExecute(Customer customer)
 {
     NavigationController.NavigateToView(new EditCustomerView(), new VMEditCustomer(customer));
 }
        public void Edit_Get_Returns_The_Correct_Customer_To_Edit()
        {
           /*
           *   Arrange 
           * 1º - Create a dummy list of customers
           * 2º - Initialize stub of SICustomerManagementService
           * 3º - Create controller to test
           */

            Customer customer = new Customer() { CustomerCode = "A0001" };
            IList<Customer> customers = new List<Customer>();
            
            SICustomerManagementService customerService = new SICustomerManagementService();
            customerService.FindCustomerByCodeString = x => customer;

            CustomerController controller = new CustomerController(customerService);

            //Act
            ViewResult result = controller.Edit("A0001") as ViewResult;

            //Assert
            Assert.IsNotNull(result);

            Customer model = result.ViewData.Model as Customer;
            Assert.IsNotNull(model);

            Assert.AreSame(customer, model);

            Assert.AreEqual("", result.ViewName);

        }
        private void DeleteExecute(Customer customer)
        {
            try
            {
                //remove customer
                IMainModuleService mainModuleService = ProxyLocator.GetMainModuleService();
                mainModuleService.RemoveCustomer(customer);

                //refresh customer list
                this.GetCustomers();
            }
            catch (FaultException<ServiceError> ex)
            {
                MessageBox.Show(ex.Detail.ErrorMessage);
            }
        }
        public void Edit_Post_Saves_A_Valid_Customer_And_Redirects_To_Details_Of_The_Customer()
        {
           /*
           *   Arrange 
           * 1º - Create a dummy list of customers
           * 2º - Initialize stub of SICustomerManagementService
           * 3º - Create controller to test
           */

            Customer customer = new Customer() { CustomerCode = "A0001" };
            IList<Customer> customers = new List<Customer>();
            
            bool changeCustomerWasCalled = false;
            
            SICustomerManagementService customerService = new SICustomerManagementService();
            customerService.ChangeCustomerCustomer = x => changeCustomerWasCalled = true;
            
            CustomerController controller = new CustomerController(customerService);

            //Act
            RedirectToRouteResult result = controller.Edit(customer) as RedirectToRouteResult;

            //Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(changeCustomerWasCalled);
            Assert.AreEqual("Details", result.RouteValues["action"]);

            //Asp.Net MVC convention to say "Same Controller"
            Assert.IsNull(result.RouteValues["controller"]);
            Assert.AreEqual("A0001", result.RouteValues["customerCode"]);
        }
     private void FixupCustomer(Customer previousValue)
     {
         if (IsDeserializing)
         {
             return;
         }
 
         if (previousValue != null && ReferenceEquals(previousValue.CustomerPicture, this))
         {
             previousValue.CustomerPicture = null;
         }
 
         if (Customer != null)
         {
             Customer.CustomerPicture = this;
             CustomerId = Customer.CustomerId;
         }
 
         if (ChangeTracker.ChangeTrackingEnabled)
         {
             if (ChangeTracker.OriginalValues.ContainsKey("Customer")
                 && (ChangeTracker.OriginalValues["Customer"] == Customer))
             {
                 ChangeTracker.OriginalValues.Remove("Customer");
             }
             else
             {
                 ChangeTracker.RecordOriginalValue("Customer", previousValue);
             }
             if (Customer != null && !Customer.ChangeTracker.ChangeTrackingEnabled)
             {
                 Customer.StartTracking();
             }
         }
     }
        public void Edit_Post_Returns_Edit_View_With_An_Invalid_Customer()
        {
           /*
           *   Arrange 
           * 1º - Create a dummy list of customers
           * 2º - Initialize stub of SICustomerManagementService
           * 3º - Create controller to test
           */

            Customer customer = new Customer() { CustomerCode = "A0001" };
            SICustomerManagementService customerService = new SICustomerManagementService();
            
            CustomerController controller = new CustomerController(customerService);
            
            ModelState state = new ModelState();
            state.Value = new ValueProviderResult("A0001", "A0001", CultureInfo.CurrentCulture);
            state.Errors.Add("Invalid Customer Code");
            controller.ModelState.Add("CustomerCode", state);

            //Act
            ViewResult result = controller.Edit(customer) as ViewResult;

            //Assert
            Assert.IsNotNull(result);
            Assert.AreEqual("A0001", result.ViewData.ModelState["CustomerCode"].Value.AttemptedValue);
            Assert.AreEqual("", result.ViewName);
        }
     private void FixupCustomer(Customer previousValue, bool skipKeys = false)
     {
         if (IsDeserializing)
         {
             return;
         }
 
         if (previousValue != null && previousValue.BankAccounts.Contains(this))
         {
             previousValue.BankAccounts.Remove(this);
         }
 
         if (Customer != null)
         {
             if (!Customer.BankAccounts.Contains(this))
             {
                 Customer.BankAccounts.Add(this);
             }
 
             CustomerId = Customer.CustomerId;
         }
         else if (!skipKeys)
         {
             CustomerId = null;
         }
 
         if (ChangeTracker.ChangeTrackingEnabled)
         {
             if (ChangeTracker.OriginalValues.ContainsKey("Customer")
                 && (ChangeTracker.OriginalValues["Customer"] == Customer))
             {
                 ChangeTracker.OriginalValues.Remove("Customer");
             }
             else
             {
                 ChangeTracker.RecordOriginalValue("Customer", previousValue);
             }
             if (Customer != null && !Customer.ChangeTracker.ChangeTrackingEnabled)
             {
                 Customer.StartTracking();
             }
         }
     }
        public void Delete_Action_Deletes_The_Customer_And_Redirects_To_Index()
        {
           /*
           *   Arrange 
           * 1º - Create a dummy list of customers
           * 2º - Initialize stub of SICustomerManagementService
           * 3º - Create controller to test
           */
            
            Customer customer = new Customer() { CustomerCode = "A0001" };
            IList<Customer> customers = new List<Customer>() { customer };
            
            SICustomerManagementService customerService = new SICustomerManagementService();
            customerService.FindCustomerByCodeString = x => customer;
            customerService.RemoveCustomerCustomer = x => customers.Remove(customer);
            
            
            CustomerController controller = new CustomerController(customerService);

            //Act
            RedirectToRouteResult result = controller.Delete("A0001") as RedirectToRouteResult;

            //Assert
            Assert.IsNotNull(result); 

            Assert.AreEqual(0, customers.Count);

            Assert.AreEqual("Index", result.RouteValues["action"]);

            Assert.IsNull(result.RouteValues["controller"]);

            Assert.AreEqual(0, result.RouteValues["page"]);

            Assert.AreEqual(10, result.RouteValues["pageSize"]);

        }
        public void AddCustomer_Invoke_Test()
        {
            //Arrange
            ICustomerManagementService customerService = IoCFactory.Instance.CurrentContainer.Resolve<ICustomerManagementService>();
            string newCustomerCode = "C0001";
            Customer customer = new Customer()
            {
                CustomerCode = newCustomerCode,
                ContactName = "Test",
                CountryId = 1,
                CompanyName = "Unit test",
                Address = new AddressInformation()
                {
                    Address = "address2",
                    City = "Madrid",
                    Fax = "+340010001",
                    Telephone = "+340010001"
                },
                IsEnabled = true,
                CustomerPicture = new CustomerPicture() { Photo = null }
            };

            //Act
            customerService.AddCustomer(customer);
            Customer inStorage = customerService.FindCustomerByCode(newCustomerCode);

            //Assert
            Assert.IsNotNull(inStorage);
        }
        public void CustomerPicture_Returns_A_Default_Image_When_The_Customer_Doesnt_Have_Image()
        {
            /*
             *   Arrange 
             * 1º - Create a dummy list of customers
             * 2º - Initialize stub of SICustomerManagementService
             * 3º - Create controller to test
             */

            //Create a customer
            Customer customer = new Customer(){ CustomerCode = "A0001", CustomerPicture = null};
            
            SICustomerManagementService customerService = new SICustomerManagementService();
            customerService.FindCustomerByCodeString = x => customer;

            CustomerController controller = new CustomerController(customerService);

            //Act
            FilePathResult result = controller.CustomerPicture("A0001") as FilePathResult;

            //Assert
            Assert.IsNotNull(result);
            Assert.AreEqual("img/png", result.ContentType);
            Assert.IsTrue(result.FileName.EndsWith("Unknown.png"));
        }