private Case[] GenerateCases(int count)
		{
			List<Case> retVal = new List<Case>();

			Random r = new Random();

			for (int i = 0; i < count; i++)
			{
				Case createdCase = new Case();
				createdCase.Title = string.Format("Title {0}", i);
				createdCase.Description = string.Format("Description {0}", i);

				if (i % 2 == 0)
				{
					createdCase.Status = "1";
					createdCase.Channel = "1";
					createdCase.Priority = 0;
				}
				else
				{
					createdCase.Status = "2";
                    createdCase.Channel = "1";
					createdCase.Priority = 1;
				}

				if (i % 3 == 0)
				{
					createdCase.Status = "3";
                    createdCase.Channel = "1";
					createdCase.Priority = 2;
				}

				//HistoryItemDto[] histories = new HistoryItemDto[]{
				//	new HistoryItemDto(){ModifyDate=DateTime.Now},
				//	new HistoryItemDto(){ModifyDate=new DateTime(2011,12,12)}


				//LabelDto[] labels = new LabelDto[] { };

				//int customerId = r.Next(0, 101);
				//createdCase.CustomerId = customerId;
				int agentId = r.Next(0, 101);
				createdCase.AgentId = agentId.ToString();
				createdCase.AgentName = _customersAgentsList[agentId];

				//createdCase.Histories = histories;
				//createdCase.Items = GetLabels().Skip(9).ToArray();

				retVal.Add(createdCase);
			}

			return retVal.ToArray();
		}
        public CustomersDetailViewModel(ICustomerEntityFactory entityFactory, ICustomerRepository repository,
                    NavigationManager navManager, IRepositoryFactory<ICustomerRepository> repositoryFactory,
                    IAuthenticationContext authContext, ICustomersCommonViewModel parentViewModel,
                    Case innerCase, Contact innerContact,
                    CaseActionState caseAction, ContactActionState contactAction,
                    IViewModelsFactory<CaseDetailViewModel> caseDetailVmFactory, IViewModelsFactory<CustomerDetailViewModel> customerDetailVmFactory,
                    IViewModelsFactory<ICreateCustomerDialogViewModel> wizardCustomerVmFactory,
                    IViewModelsFactory<IKnowledgeBaseDialogViewModel> knowledgeBaseGroupVmFactory)
        {
            _entityFactory = entityFactory;
            Repository = repository;
            _authContext = authContext;
            _navManager = navManager;
            _repositoryFactory = repositoryFactory;
            _caseDetailVmFactory = caseDetailVmFactory;
            _customerDetailVmFactory = customerDetailVmFactory;
            _wizardCustomerVmFactory = wizardCustomerVmFactory;
            _knowledgeBaseGroupVmFactory = knowledgeBaseGroupVmFactory;
            _parentViewModel = parentViewModel;

            OriginalItem = innerCase;
            OriginalContact = innerContact;

            InnerItem = innerCase;
            CurrentCustomer = innerContact;

            CaseActionState = caseAction;
            ContactActionState = contactAction;

            InitializeCommands();

            _isItemsInitialized = false;

            ViewTitle = new ViewTitleBase
                {
                    SubTitle = string.Format("Case #{0}".Localize(), InnerItem.Number),
                    Title = "Customer Service"
                };


            _authorId = _authContext.CurrentUserId;
            _authorName = _authContext.CurrentUserName;
        }
        private void RaiseOpenItemInteractionRequest()
        {
            var parameters = new List<KeyValuePair<string, object>>();

            var customer = new Contact();
            var caseItem = new Case();
            if (_resultType == SearchResultType.Case)
            {
                caseItem.CaseId = _id;
                if (string.IsNullOrWhiteSpace(CaseContactId))
                {
                    parameters.Add(new KeyValuePair<string, object>("contactAction", ContactActionState.New));
                }
                else
                {
                    customer.MemberId = CaseContactId;
                    parameters.Add(new KeyValuePair<string, object>("contactAction", ContactActionState.Open));
                }

                parameters.Add(new KeyValuePair<string, object>("caseAction", CaseActionState.Open));
                parameters.Add(new KeyValuePair<string, object>("isContactOnlyShow", false));
            }
            else
            {
                customer.MemberId = _id;
                parameters.Add(new KeyValuePair<string, object>("contactAction", ContactActionState.Open));
                parameters.Add(new KeyValuePair<string, object>("caseAction", CaseActionState.None));
                parameters.Add(new KeyValuePair<string, object>("isContactOnlyShow", true));
            }
            parameters.Add(new KeyValuePair<string, object>("parentViewModel", _parentViewModel));
            parameters.Add(new KeyValuePair<string, object>("innerCase", caseItem));
            parameters.Add(new KeyValuePair<string, object>("innerContact", customer));

            var itemVM = _customersDetailVmFactory.GetViewModelInstance(parameters.ToArray());

            var openTracking = (IOpenTracking)itemVM;
            openTracking.OpenItemCommand.Execute();
        }
		public void CreateCaseTest()
		{
			var client = GetRepository();

			Case caseToAdd = new Case();

			client.Add(caseToAdd);
			client.UnitOfWork.Commit();

			client = GetRepository();

			var caseFromDb = client.Cases.Where(cs => cs.CaseId == caseToAdd.CaseId).SingleOrDefault();

			Assert.IsNotNull(caseFromDb);
		}
		public void CreateNewOutboundCallCaseWithExistingContactTest()
		{
			//get from db Case with status==Open
			var client = GetRepository();

			Contact qqqContact = client.Members.Where(m => (m as Contact).FullName == "qqq").OfType<Contact>()
				.Expand(c => c.Addresses).Expand(c => c.Cases).Expand(c => c.Emails)
				.Expand(c => c.Labels).Expand(c => c.Notes).Expand(c => c.Phones)
				.SingleOrDefault();

			client.Attach(qqqContact);

			Assert.IsNotNull(qqqContact);

			//create new case
			Case newCase = new Case();

			newCase.Description = "testDescroption";
			newCase.Number = "adasdqw";
			newCase.Priority = 1;
			newCase.Status = CaseStatus.Open.ToString();
			newCase.Title = "cooltitle";


			//clear existing contact's labels
			qqqContact.Labels.Clear();


			//get all labels
			var labels = client.Labels.ToList();
			var label1 = labels[0];
			client.Attach(label1);


			qqqContact.Labels.Add(label1);
			newCase.Labels.Add(label1);

			newCase.ContactId = qqqContact.MemberId;

			client.Add(newCase);
			client.Update(qqqContact);

			client.UnitOfWork.Commit();


			client = GetRepository();

			Contact qqqFromDbContact = client.Members.Where(m => (m as Contact).FullName == "qqq").OfType<Contact>()
				.Expand(c => c.Addresses).Expand(c => c.Cases).Expand(c => c.Emails)
				.Expand(c => c.Labels).Expand(c => c.Notes).Expand(c => c.Phones)
				.SingleOrDefault();

			Assert.IsNotNull(qqqFromDbContact);
			Assert.IsNotNull(qqqFromDbContact.Cases);
			Assert.IsTrue(qqqFromDbContact.Labels.Count == 1);


			Case caseFromDb = client.Cases.Where(c => c.CaseId == newCase.CaseId)
				.Expand(c => c.CommunicationItems).Expand(c => c.Labels).Expand(c => c.Notes)
				.SingleOrDefault();

			Assert.IsNotNull(caseFromDb);
			Assert.IsTrue(caseFromDb.Labels.Count == 1);

		}
		public void CreateNewContactWithNewCaseTest()
		{
			//ICustomerRepository client = new EFCustomersRepository(new CustomerEntityFactory());
			var client = GetRepository();


			Contact contactToDb = new Contact();
			contactToDb.BirthDate = new DateTime(1970, 8, 15);
			contactToDb.FullName = "dataServiceFullnameTest";

			Case caseToDb = new Case();
			caseToDb.Description = "dataServiceDescriptionTest";
			caseToDb.Number = "qweqweas";
			caseToDb.Priority = 1;
			caseToDb.Status = CaseStatus.Open.ToString();
			caseToDb.Title = "dataServiceTitleTest";



			contactToDb.Addresses.Add(CreateAddress("Верхнеозерная", "25/8", "Калининград", "RUS", "Russianfederation", string.Empty, "238210", "Primary"));
			contactToDb.Addresses.Add(CreateAddress("пл. Победы", "1", "Калининград", "RUS", "Russianfederation", string.Empty, "666259", "Shipping"));

            contactToDb.Emails.Add(new Email { Address = "*****@*****.**", Type = "Primary" });
            contactToDb.Emails.Add(new Email { Address = "*****@*****.**", Type = "Secondary" });

			contactToDb.Phones.Add(new Phone { Number = "12346578912", Type = "Primary" });


			//add labels

			var labels = client.Labels.ToList();

			foreach (var lb in labels)
			{
				client.Attach(lb);
			}

			var label1 = labels[0];
			var label2 = labels[1];

			contactToDb.Labels.Add(label1);

			caseToDb.Labels.Add(label1);
			caseToDb.Labels.Add(label2);


			//save new contact in db
			caseToDb.ContactId = contactToDb.MemberId;
			client.Add(caseToDb);
			client.Add(contactToDb);



			client.UnitOfWork.Commit();

			string contactId = contactToDb.MemberId;

			client = new DSCustomerClient(service.ServiceUri, new CustomerEntityFactory(), null);

			Contact contactFromDb = client.Members.Where(m => (m as Contact).MemberId == contactId).OfType<Contact>()
				.Expand(c => c.Addresses).Expand(c => c.Cases).Expand(c => c.Emails)
				.Expand(c => c.Labels).Expand(c => c.Notes).Expand(c => c.Phones).SingleOrDefault();


			//contact is saved correctly
			Assert.IsNotNull(contactFromDb);
			//cases count>0
			Assert.IsTrue(contactFromDb.Cases.Count > 0);
			//addresses count>0
			Assert.IsTrue(contactFromDb.Addresses.Count > 0);
			//phones count > 0
			Assert.IsTrue(contactFromDb.Phones.Count > 0);
			//emails count > 0
			Assert.IsTrue(contactFromDb.Emails.Count > 0);

			Assert.IsTrue(contactToDb.Labels.Count == 1);

		}
		private Case CreateCase(string number, int priority, string agentId, string agentName, string title, string description, string status, string type)
		{
			Case c = new Case();


			c.Number = number;
			c.Priority = priority;
			c.AgentId = agentId;
			c.AgentName = agentName;
			c.Title = title;
			c.Description = description;
			c.Status = status;
            c.Channel = type;

			return c;

		}
        public void Can_change_case_status()
        {
            //get from db Case with status==Open
            var client = GetRepository();

	        var caseToDb = new Case {Title = "Case_change_Status_test", Status = CaseStatus.Open.ToString()};

			client.Add(caseToDb);
	        client.UnitOfWork.Commit();
	        client = GetRepository();

	        var caseWithOpenedStatusFromDb = client.Cases.Where(c => c.CaseId == caseToDb.CaseId).SingleOrDefault();

			Assert.NotNull(caseWithOpenedStatusFromDb);
			Assert.True(caseWithOpenedStatusFromDb.Status==CaseStatus.Open.ToString());

	        caseWithOpenedStatusFromDb.Status = CaseStatus.Pending.ToString();
			//после этого вызова объект Case удалится из коллекции client.Cases, хотя я этого не делаю
			//Adomas: No Magic here, just Parent validator was removing item even if FK property was not modified
	        client.UnitOfWork.Commit();


	        client = GetRepository();

	        var caseWithPendingStatusFromDb =
		        client.Cases.Where(c => c.CaseId == caseWithOpenedStatusFromDb.CaseId).SingleOrDefault();

			Assert.NotNull(caseWithPendingStatusFromDb);
	        Assert.True(caseWithPendingStatusFromDb.Status == CaseStatus.Pending.ToString());
        }
	    public void Can_create_labels_to_case_and_contact()
		{

			var client = GetRepository();

			var contactToDb = new Contact();
			contactToDb.FullName = "test";

			var caseToDb = new Case();

			contactToDb.Cases.Add(caseToDb);

			var labelForContact = new Label(){Name = "testName", Description = "testDescription"};

			var labelForCase = new Label() { Name = "testName", Description = "testDescription"};

			caseToDb.Labels.Add(labelForCase);
			
			contactToDb.Labels.Add(labelForContact);

			client.Add(contactToDb);
			client.UnitOfWork.Commit();


			client = GetRepository();

			var contactFromDB =
				client.Members.OfType<Contact>()
					.Where(c => c.MemberId == contactToDb.MemberId)
					.Expand(c => c.Cases)
					.Expand(c => c.Labels).SingleOrDefault();

			Assert.NotNull(contactFromDB);
			Assert.NotNull(contactFromDB.Cases);
			Assert.True(contactFromDB.Labels.Count==1);



			var caseFromDb =
				client.Cases.Where(c => c.CaseId == caseToDb.CaseId).Expand(c => c.Labels).SingleOrDefault();

			Assert.NotNull(caseFromDb);
			Assert.True(caseFromDb.Labels.Count == 1);

		}
 private void CreateNewCaseForCurrentContact()
 {
     if (CaseActionState == CaseActionState.None)
     {
         InnerItem = new Case { Status = CaseStatus.Open.ToString(), Number = UniqueNumberGenerator.GetUniqueNumber() };
         InitializeCaseViewModel();
         CaseActionState = CaseActionState.New;
     }
     else
     {
         if (_parentViewModel != null)
         {
             _parentViewModel.CreateNewEmailCaseCommand.Execute(CurrentCustomer);
         }
     }
 }
        private void RiseOpenCaseInteractionRequest(Case item)
        {

        }
        public async void InitializeForOpen()
        {
            if (!_isItemsInitialized)
            {
                ShowLoadingAnimation = true;

                Repository = _repositoryFactory.GetRepositoryInstance();

                await Task.Run(() =>
                    {
                        //loading or creating contact
                        switch (ContactActionState)
                        {
                            case ContactActionState.New:
                                CurrentCustomer = new Contact();
                                break;

                            case ContactActionState.Open:
                                _originalContact =
                                    Repository.Members.Where(m => m.MemberId == _innerContact.MemberId)
                                               .OfType<Contact>()
                                               .Expand(c => c.Addresses)
                                               .Expand(c => c.Emails)
                                               .Expand(c => c.Labels)
                                    /*.Expand(c => c.Notes)*/.Expand(c => c.Phones).SingleOrDefault();

                                var contactNotes = Repository.Notes.Where(n => n.MemberId == CurrentCustomer.MemberId).ToList();
                                OnUIThread(() =>
                                {
                                    CurrentCustomer = _originalContact;
                                    ContactNotes = contactNotes;
                                });


                                if (CaseActionState == CaseActionState.None)
                                {
                                    IsCaseOptionSelected = false;
                                    IsCustomerOptionSelected = true;
                                }
                                break;
                        }

                        //loading or creating case
                        switch (CaseActionState)
                        {
                            case CaseActionState.None:
                                IsCaseOptionSelected = false;
                                IsCustomerOptionSelected = true;
                                break;

                            case CaseActionState.New:
                                InnerItem = new Case();
                                InnerItem.Status = CaseStatus.Open.ToString();
                                InnerItem.Number = UniqueNumberGenerator.GetUniqueNumber();

                                IsCaseOptionSelected = true;
                                IsCustomerOptionSelected = false;

                                break;

                            case CaseActionState.Open:

                                _originalItem =
                                    Repository.Cases.Where(c => c.CaseId == _originalItem.CaseId)
                                    /*.Expand(c => c.Notes)*/
                                                .Expand(c => c.Labels)
                                               .Expand(c => c.CaseCc).SingleOrDefault();



                                InnerItem = _originalItem.DeepClone(_entityFactory as IKnownSerializationTypes);

                                CaseCommunicationItems = Repository.CommunicationItems.Where(ci => ci.CaseId == InnerItem.CaseId).ToList();
                                CaseNotes = Repository.Notes.Where(n => n.CaseId == InnerItem.CaseId).ToList();

                                _oldCasePropertyValues =
                                    Repository.CasePropertyValues.Where(x => x.CaseId == InnerItem.CaseId)
                                               .ToList();

                                IsCaseOptionSelected = true;
                                IsCustomerOptionSelected = false;
                                break;
                        }
                    });

                await Task.Run(() =>
                    {
                        InitializeViewModels();
                        InitCommunicationControl();
                    });

                OnPropertyChanged("CaseCommunications");
                OnPropertyChanged("CustomerNotes");

                if (CaseCommunications != null && !CaseCommunications.IsInitialized)
                {
                    RefreshCaseCommunicationItems();
                }
                if (CustomerNotes != null && !CustomerNotes.IsInitialized)
                {
                    RefreshCustomerNotesItems();
                }


                SaveChangesCommand.RaiseCanExecuteChanged();
                ResolveAndSaveCommand.RaiseCanExecuteChanged();
                ProcessAndSaveCommand.RaiseCanExecuteChanged();

                _isItemsInitialized = true;
                IsModified = false;

                OnPropertyChanged("IsValidForSave");
                OnPropertyChanged("IsValid");
                OnPropertyChanged("InnerItem");
                OnPropertyChanged("CurrentCustomer");


                ShowLoadingAnimation = false;

                OnCaseOrContactStateChanged();
            }
        }
        private async Task DoSaveChanges()
        {
            try
            {
                ShowLoadingAnimation = true;
                await Task.Run(() =>
                    {
                        DoSaveChangesAsync();
                        Repository.UnitOfWork.Commit();
                        UpdateCaseAndContactCommunicationItems();
                        UpdateCaseAndContactLabels();
                    });

                _originalContact = CurrentCustomer;
                _originalItem = InnerItem;

                _oldCasePropertyValues =
                                    Repository.CasePropertyValues.Where(x => x.CaseId == InnerItem.CaseId)
                                               .ToList();

                if (CaseActionState != CaseActionState.None)
                {
                    CaseActionState = CaseActionState.Open;
                }

                ContactActionState = ContactActionState.Open;

                OnUIThread(() =>
                    {
                        OnPropertyChanged("OriginalItem");
                        OnPropertyChanged("OriginalContact");
                        OnPropertyChanged("Status");
                        IsModified = false;
                        if (CaseActionState != CaseActionState.None)
                        {
                            _parentViewModel.Refresh();
                        }
                    });
            }
            catch (Exception ex)
            {
                ShowErrorDialog(ex, string.Format("An error occurred when trying to save changes: {0}".Localize(null, LocalizationScope.DefaultCategory), ex.InnerException.Message));
            }
            finally
            {
                ShowLoadingAnimation = false;
            }

        }