Exemple #1
0
        protected virtual void SetupWebRequirements()
        {
            var sessionStateCollection = new Dictionary <string, object>();
            var shimSessionState       = new ShimHttpSessionState();

            shimSessionState.ItemGetString = (argKey) =>
            {
                return(sessionStateCollection.ContainsKey(argKey) ? sessionStateCollection[argKey] : null);
            };
            shimSessionState.ItemSetStringObject = (argKey, argValue) =>
            {
                sessionStateCollection[argKey] = argValue;
            };
            _httpSessionState = shimSessionState.Instance;

            ShimUserControl.AllInstances.SessionGet = (userControl) => { return(_httpSessionState); };
        }
Exemple #2
0
        private void SetupHttpSessionState()
        {
            if (_shimsContext == null)
            {
                throw new InvalidOperationException("_shimsContext local member must be initialized to setup the HttpSessionState shim object");
            }

            _sessionCollection = new FakeSessionStateCollection();

            _shimHttpSessionState = new ShimHttpSessionState();
            _shimHttpSessionState.SessionIDGet        = () => Guid.NewGuid().ToString();
            _shimHttpSessionState.AddStringObject     = (key, value) => _sessionCollection.Add(key, value);
            _shimHttpSessionState.RemoveAll           = () => _sessionCollection.Clear();
            _shimHttpSessionState.RemoveAtInt32       = (index) => _sessionCollection.RemoveAt(index);
            _shimHttpSessionState.RemoveString        = (key) => _sessionCollection.Remove(key);
            _shimHttpSessionState.ItemGetInt32        = (index) => _sessionCollection[index];
            _shimHttpSessionState.ItemSetInt32Object  = (index, value) => _sessionCollection[index] = value;
            _shimHttpSessionState.ItemGetString       = (key) => _sessionCollection[key];
            _shimHttpSessionState.ItemSetStringObject = (key, value) => _sessionCollection[key] = value;
        }
        public void SyncPlantData_SadPath()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                //Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                ShimCurrentUser.AsUserDto = () => new SIMPLTestContext().GetFakeUserDtoObject();

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                ShimErrorLoggingService.AllInstances.LogErrorException = (myClient, myException) => { };

                // Expected Result
                var expectedResult = new
                {
                    status = "error",
                    errorMessage = "There was an error while updating the data -- please try again"
                };

                var fakeCurrentSubscriber = new ShimCurrentSubscriber
                {
                    DpiRegionGet = () => "CT"
                };

                ShimCurrentSubscriber.SessionInstanceGet = () => fakeCurrentSubscriber;

                // Call FacilitiesController SyncPlantData
                var actualResult = FacilitiesControllerForTests.SyncPlantData() as JsonResult;

                // Test Validation
                Assert.IsNotNull(actualResult, "JsonResult returned is null");
                Assert.IsNotNull(actualResult, "JsonResult Data returned is null");
                Assert.AreEqual(expectedResult.ToString(), actualResult.Data.ToString());
            }
        }
        public void A_user_logs_in_when_Single_Concurrent_Login_Feature_is_enabled_and_is_able_to_successfully_log_in()
        {
            using (ShimsContext.Create())
            {
                // Given a known user that is not logged in yet
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "doesNotMatter";

                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                LoginControllerForTests.ControllerContext = new ControllerContext()
                {
                    HttpContext = contextStub
                };

                #endregion LoginModel class, AttemptToLogUserIn method

                // And the Single Concurrent Login Feature is enabled

                // As there are unit tests for IsCheckEnabledActor, I am mocking the reference to IsCheckEnabled
                var wasIsCheckEnabledCalled = false;
                ShimSingleConcurrentLoginRules.AllInstances.IsCheckEnabled = (resultValue) =>
                {
                    wasIsCheckEnabledCalled = true;
                    return true;
                };

                // When that user is trying to log in

                #region LoginModel class, AttemptToLogUserIn method

                var wasASPPAuthenticateCalled = false;
                ShimUserManagement.AllInstances.AuthenticateStringString = (userNameValue, passwordValue, results) =>
                {
                    wasASPPAuthenticateCalled = true;
                    return UserManagement.AuthenticationResults.Success;
                };

                var wasASPPGetUserDetailsCalled = false;
                ShimUserManagement.AllInstances.GetUserDetailsString = (userNameValue, results) =>
                {
                    wasASPPGetUserDetailsCalled = true;
                    return new ASPP_Users();
                };

                var wasASPPGetUserGroupsCalled = false;
                ShimUserManagement.AllInstances.GetUserGroupsString = (userNameValue, results) =>
                {
                    wasASPPGetUserGroupsCalled = true;

                    // need to add at least one group - doing just enough to get beyond the guard in LoginModel.cs
                    var myASPP_Group = new ASPP_Groups
                    {
                        Group_ID = 1
                    };

                    return new List<ASPP_Groups>
                    {
                        myASPP_Group
                    };
                };

                // Then the data is saved correctly

                var wasCreateSIMPLLoginTrackerRecordCalled = false;
                ShimSIMPLSessionEntitiesRepository.AllInstances.CreateSIMPLLoginTrackerRecordStringString = (method, userNameValue, aspNetSessionIdValue) =>
                {
                    wasCreateSIMPLLoginTrackerRecordCalled = true;
                    return new SIMPLLoginTracker { SIMPLUsername = "******", ASPNETSessionId = "doesNotMatter", SIMPLLoginTrackerId = 1, SIMPLLoginTimeUtc = DateTime.UtcNow };
                };

                // And the data is added to the cache correctly

                var wasAddSIMPLLoginTrackerRecordToCacheCalled = false;
                ShimSIMPLSessionEntitiesCache.AddSIMPLLoginTrackerRecordToCacheStringSIMPLLoginTracker = (userNameValue, myLoginTrackerValue) =>
                {
                    wasAddSIMPLLoginTrackerRecordToCacheCalled = true;
                    return true;
                };

                // And the user is logged in successfully

                #region back in the LoginViewModel class, AttemptToLogUserIn method

                var session = new ShimHttpSessionState { SessionIDGet = () => "doesNotMatter"};
                var context = new ShimHttpContext();
                var applicationShim = new ShimHttpApplicationState();
                context.ApplicationGet = () => applicationShim;
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                var wasCurrentUserSetInstanceStringCalled = false;
                var currentUserSetInstanceCount = 0;
                ShimCurrentUser.SetInstanceString = (uniqueId) =>
                {
                    wasCurrentUserSetInstanceStringCalled = true;
                    currentUserSetInstanceCount++;
                };

                var wasCurrentUserSessionInstanceGetCalled = false;
                ShimCurrentUser.SessionInstanceGet = () =>
                {
                    wasCurrentUserSessionInstanceGetCalled = true;
                    return new ShimCurrentUser();
                };

                var wasLoginModelSyncWithOrImportDataFromASPPCalled = false;
                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingServiceValue, userNameSentToLoginModelValue) =>
                {
                    wasLoginModelSyncWithOrImportDataFromASPPCalled = true;
                };

                var wasCurrentUserClearCalled = false;
                ShimCurrentUser.Clear = () =>
                {
                    wasCurrentUserClearCalled = true;
                };

                var wasUserEventsInitializeSessionCalled = false;
                ShimUserEvents.AllInstances.InitializeSessionStringString = (userEvents, uniqueIdValue, userHostAddressValue) =>
                {
                    wasUserEventsInitializeSessionCalled = true;
                };

                var wasFormsAuthenticationSetAuthCookieCalled = false;
                ShimFormsAuthentication.SetAuthCookieStringBoolean = (userNameValue, createPersistentCookieValue) =>
                {
                    wasFormsAuthenticationSetAuthCookieCalled = true;
                };

                #endregion back in the LoginViewModel class, AttemptToLogUserIn method

                var result = LoginControllerForTests.UserLogin(userName, password, returnUrl);
                Assert.IsNotNull(result, "LoginController returned null");
                Assert.IsTrue(result is RedirectResult, "LoginController didn't return a RedirectResult");

                var resultRedirectResult = result as RedirectResult;
                Assert.AreEqual(returnUrl, resultRedirectResult.Url, "URL did not match expected value");

                Assert.IsTrue(wasIsCheckEnabledCalled, "wasIsCheckEnabledCalled is false");
                Assert.IsTrue(wasCreateSIMPLLoginTrackerRecordCalled, "wasCreateSIMPLLoginTrackerRecordCalled is false");
                Assert.IsTrue(wasAddSIMPLLoginTrackerRecordToCacheCalled, "wasAddSIMPLLoginTrackerRecordToCacheCalled is false");

                Assert.IsTrue(wasASPPAuthenticateCalled, "wasASPPAuthenticateCalled is false");
                Assert.IsTrue(wasASPPGetUserDetailsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasASPPGetUserGroupsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasCurrentUserSetInstanceStringCalled, "wasCurrentUserSetInstanceStringCalled is false");
                Assert.AreEqual(2, currentUserSetInstanceCount, "currentUserSetInstanceCount did not match expected value");
                Assert.IsTrue(wasCurrentUserSessionInstanceGetCalled, "wasCurrentUserSessionInstanceGetCalled is false");
                Assert.IsTrue(wasCurrentUserClearCalled, "wasCurrentUserClearCalled is false");
                Assert.IsTrue(wasLoginModelSyncWithOrImportDataFromASPPCalled, "wasLoginModelSyncWithOrImportDataFromASPPCalled is false");
                Assert.IsTrue(wasUserEventsInitializeSessionCalled, "wasUserEventsInitializeSessionCalled is false");
                Assert.IsTrue(wasFormsAuthenticationSetAuthCookieCalled, "wasFormsAuthenticationSetAuthCookieCalled is false");
            }
        }
        public void Index_HappyPath()
        {
            using (ShimsContext.Create())
            {
                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                var customer = new CustomerDto();
                customer.CitizensPostalAddress.AddressTexts.Add(new AddressTextDto() { Address = "TestBillingAddress", SequenceNumber = 0 });
                var billingAccountId = new BillingAccountIdDto();
                billingAccountId.PhoneNumberAsId.TelephoneNumber.Number = "TestBillingNumber";
                ShimCurrentSubscriber.AllInstances.CurrentBillingAccountGet = (myTest) => new CustomerAccountDto()
                {

                    Customer = customer,
                    BillingAccountId = billingAccountId

                };

                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => new ServiceAccountDto
                {
                    Address = new ServiceAddressDto{ Address1 = "TestServiceAddress"},
                    IsBTN = false,
                    SubscriberName = "TestServiceName",
                    TN = "TestServiceNumber",
                    USI = "TestServiceUSI"
                };

                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myTestParam) => "123456789";
                ShimCurrentSubscriber.AllInstances.AddressGet = (myTestParam) => "TestAddressLine1";
                ShimCurrentSubscriber.AllInstances.Address2Get= (myTestParam) => "TestAddressLine2";
                ShimCurrentSubscriber.AllInstances.CityGet= (myTestParam) => "TestCity";
                ShimCurrentSubscriber.AllInstances.StateGet = (myTestParam) => "TestState";
                ShimCurrentSubscriber.AllInstances.ZipGet = (myTestParam) => "TestZip";
                ShimCurrentSubscriber.AllInstances.HeadendCodeGet = (myTestParam) => "TestHeadend";
                ShimCurrentSubscriber.AllInstances.RateCenterGet= (myTestParam) => "TestRateCenter";
                ShimCurrentSubscriber.AllInstances.NetworkLocationCodeGet = (myTestParam) => "TestNetworkCode";
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => "TestSub";
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => "TestSub";

                var accountsController = DependencyResolver.Current.GetService<AccountsController>();
                var result = accountsController.Index();
                Assert.IsTrue(((AccountTuple)result.Model).BillingAccount.Address.AddressLine1.Equals("TestBillingAddress"));
                Assert.IsTrue(((AccountTuple)result.Model).BillingAccount.TN.Equals("TestBillingNumber"));
                Assert.IsTrue(((AccountTuple)result.Model).ServiceAccount.Addresses.ServiceAddress.AddressLine1.Equals("TestServiceAddress"));
                Assert.IsTrue(((AccountTuple)result.Model).ServiceAccount.TN.Equals("TestServiceNumber"));

            }
        }
        public void Index_ProvisioningLocation_withAddresses_withRateCenter_withNetworkLocCode()
        {
            using (ShimsContext.Create())
            {
                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                var customer = new CustomerDto();
                customer.CitizensPostalAddress.AddressTexts.Add(new AddressTextDto() { Address = "TestBillingAddress", SequenceNumber = 0 });
                var billingAccountId = new BillingAccountIdDto();
                billingAccountId.PhoneNumberAsId.TelephoneNumber.Number = "TestBillingNumber";
                ShimCurrentSubscriber.AllInstances.CurrentBillingAccountGet = (myTest) => new CustomerAccountDto()
                {

                    Customer = customer,
                    BillingAccountId = billingAccountId

                };

                // service account
                var serviceAccount = new ServiceAccountDto
                {
                    Address = new ServiceAddressDto{ Address1 = "TestServiceAddress"},
                    IsBTN = false,
                    SubscriberName = "TestServiceName",
                    TN = "TestServiceNumber",
                    USI = "TestServiceUSI",
                };
                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => serviceAccount;

                // Expected provisioning locaton
                var provLocation = new LocationDto
                {
                    ID = "12345666666444",
                    AddressLine1 = "ADDRESS1",
                    AddressLine2 = "ADDRESS2",
                    CityName = "CITY",
                    StateName = "STATE WA",
                    ZipCode = "12345",
                    HeadendCode = "01",
                    NetworkLocationCode = "1234567",
                    RateCenterName = "123456",
                };

                // CurrentSubscriber location
                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myTestParam) => provLocation.ID;
                ShimCurrentSubscriber.AllInstances.AddressGet = (myTestParam) => provLocation.AddressLine1;
                ShimCurrentSubscriber.AllInstances.Address2Get = (myTestParam) => provLocation.AddressLine2;
                ShimCurrentSubscriber.AllInstances.CityGet = (myTestParam) => provLocation.CityName;
                ShimCurrentSubscriber.AllInstances.StateGet = (myTestParam) => provLocation.StateName;
                ShimCurrentSubscriber.AllInstances.ZipGet = (myTestParam) => provLocation.ZipCode;
                ShimCurrentSubscriber.AllInstances.HeadendCodeGet = (myTestParam) => provLocation.HeadendCode;
                ShimCurrentSubscriber.AllInstances.RateCenterGet = (myTestParam) => provLocation.RateCenterName;
                ShimCurrentSubscriber.AllInstances.NetworkLocationCodeGet =
                    (myTestParam) => provLocation.NetworkLocationCode;
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => "TestSub";

                // account controller
                var accountsController = DependencyResolver.Current.GetService<AccountsController>();

                // call Index action method
                var result = accountsController.Index();

                // results is no null
                Assert.IsNotNull(result);

                var accountTuple = (AccountTuple) result.Model;

                // validate billing info
                Assert.IsTrue(accountTuple.BillingAccount.Address.AddressLine1.Equals("TestBillingAddress"));
                Assert.IsTrue(accountTuple.BillingAccount.TN.Equals("TestBillingNumber"));

                // validate service address
                Assert.AreEqual(serviceAccount.Address.Address1, accountTuple.ServiceAccount.Addresses.ServiceAddress.AddressLine1, "Service Address1 does not match");
                Assert.IsTrue(accountTuple.ServiceAccount.TN.Equals("TestServiceNumber"));

                // validate provisioning location;
                var actualProvLocaton = accountTuple.ServiceAccount.Addresses.ProvisioningAddress.Location;
                Assert.AreEqual(provLocation.ID, actualProvLocaton.LocationID, "Location ID does not match");
                Assert.AreEqual(provLocation.AddressLine1, actualProvLocaton.Address1, "Address1 does not match");
                Assert.AreEqual(provLocation.AddressLine2, actualProvLocaton.Address2, "Address2 does not match");
                Assert.AreEqual(provLocation.HeadendCode, actualProvLocaton.Headend, "Headend does not match");
                Assert.AreEqual(provLocation.CityName, actualProvLocaton.City, "City does not match");
                Assert.AreEqual(provLocation.StateName, actualProvLocaton.State, "State does not match");
                Assert.AreEqual(provLocation.RateCenterName, actualProvLocaton.RateCenter, "RateCenter does not match");
                Assert.AreEqual(provLocation.NetworkLocationCode, actualProvLocaton.NetworkLocationCode, "NetworkLocationCode does not match");
            }
        }
        public void UpdateSubscriberServiceStatus_EnableService_ValidateUserAbleToEnableService()
        {
            using (ShimsContext.Create())
            {
                // Given a user that has permission to enable subscriber service
                ShimCurrentUser.AsUserDto = () => new UserDto();

                // And a valid subscriber
                const string subId = "subId";
                const string subName = "subName";

                // And the subscriber has a valid provisioned location
                const string locId = "locId";

                // And the subscriber has service disenabled
                const bool serviceEnabled = false;

                // And the subscriber is not found in billing
                const bool foundInBilling = false;

                // And the user has loaded the subscriber
                var currentSubscriber = new ShimCurrentSubscriber
                {
                    SubIdGet = () => subId,
                    NameGet = () => subName,
                    LocationIdGet = () => locId,
                    ServiceEnabledGet = () => serviceEnabled,
                    FoundInBillingGet = () => foundInBilling,
                    AccountTypeGet = () => AccountTypeDto.Residential,
                    CbrGet = () => "4250010001",
                    EmailGet = () => "*****@*****.**",
                    PINGet = () => "subpin",
                    PPVCapGet = () => "150.00",
                    PPVResetDayGet = () => "15",
                    PPVPrivilegeGet = () => SubscriberEnums.PPVPrivilegeEnum.Capped,
                    ProvisionedServicesListGet = () => new List<ServiceDto>()
                };

                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                ShimCurrentSubscriber.SessionInstanceGet = () => new ShimCurrentSubscriber();
                ShimCurrentSubscriber.GetInstance = () => currentSubscriber;

                // When enabling the service
                var subscriberController = DependencyResolver.Current.GetService<SubscriberController>();

                ShimRosettianClient.AllInstances.UpdateSubscriberSubscriberDtoBooleanUserDto =
                    (myTestClient, mySubscriberDto, overriteService, myUserDto) => true;

                ShimSubscriberExtension.MapToSubDetailsModelCurrentSubscriber =
                    (myCurrentSubscriber) => new SubscriberDetailsModel
                    {
                        USI = subId,
                        Name = subName,
                        CurrentServiceStatus = true,
                        FoundInBilling = false,
                    };

                var actionResponse = subscriberController.UpdateSubscriberServiceStatus(true) as JsonResult;

                // Then the user receives a response
                Assert.IsNotNull(actionResponse, "Json result is null");
                Assert.IsNotNull(actionResponse.Data, "Json result data is null");

                // And the response is successful
                // And the service is enabled
                var jss = new JavaScriptSerializer();
                var expectedResult = new
                {
                    status = "valid",
                    message = @"The customer's account was <span class=""active"">Enabled</span>",
                    returnedPartial = "",
                }.ToJSON();
                Assert.AreEqual(jss.Serialize(expectedResult), jss.Serialize(actionResponse.Data.ToJSON()));
            }
        }
        public void RefreshDevices_HappyPath()
        {
            //Setup
            var myContext = new SIMPLTestContext();

            using (ShimsContext.Create())
            {
                // Given a user
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                ShimCurrentSubscriber.AllInstances.LocationIdGet = (currentSubscriber) => "FakeLocationId";
                ShimCurrentSubscriber.AllInstances.MaxStbGet = (currentSubscriber) => "4";

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                ShimCurrentSubscriber.SessionInstanceGet = () =>  new ShimCurrentSubscriber();

                // A single ONT
                EquipmentDto myEquipmentDto1 = new EquipmentDto();
                myEquipmentDto1.Status = "ACTIVE";
                myEquipmentDto1.Type = new EquipmentTypeDto();
                myEquipmentDto1.Type.ONTModel = new ONTModelDto();
                myEquipmentDto1.Type.ONTModel.Model = "Model";
                myEquipmentDto1.SerialNumber = "SerialNumber1";

                // A single Video Device
                EquipmentDto myEquipmentDto2 = new EquipmentDto();
                myEquipmentDto2.Status = "IGNORE";
                myEquipmentDto2.Type = new EquipmentTypeDto();
                myEquipmentDto2.Type.ONTModel = null;
                myEquipmentDto2.SerialNumber = "SerialNumber2";

                var equipments = new List<EquipmentDto>();
                equipments.Add(myEquipmentDto1);
                equipments.Add(myEquipmentDto2);

                // Fake the RosettianClient.SearchEquipment call
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myRosettianClient, mySubscriberID, myUserObject) => equipments;

                // When loading that device
                var actionResult = SubscriberControllerForTests.RefreshDevices() as PartialViewResult;

                Assert.IsNotNull(actionResult, "ViewResult is null.");
                var equipmentModel = actionResult.Model as SubscriberEquipmentModel;
                Assert.IsNotNull(equipmentModel, "ViewModel is null.");
                Assert.IsNotNull(equipmentModel.ONTList, "ONTList is null");
                Assert.IsTrue(equipmentModel.ONTList.Count >= 0);
                Assert.IsNotNull(equipmentModel.VideoDeviceList, "VideoDeviceList is null");
                Assert.IsTrue(equipmentModel.VideoDeviceList.Count >= 0);
            }
        }
        public void EditResidentialGateway_hasMainRg_hasListOtherRgs_hasIpVideoDevice_ValidateSuccessScenario()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

                //Build FakeDto
                var fakeUserDto = myContext.GetFakeUserDtoObject();

                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = o => session;

                // current location
                const string expectedLocationId = "123456789";

                // expected all devices on current location
                var customFieldsDto = RgTestData_CustomFieldsCollection();
                var mainRg = RgTestData_MainRg(customFieldsDto, expectedLocationId);
                var ipVideoDevice = RgTestData_IpVideoDevice(customFieldsDto, expectedLocationId);
                var otherRgs = RgTestData_OtherRgList(customFieldsDto, expectedLocationId);

                // rg to be updated
                var rgTobeUpdated = otherRgs.First();
                rgTobeUpdated.UnitAddress = "12345678";

                // set location and sub
                ShimCurrentSubscriber.AllInstances.LocationIdGet = o => expectedLocationId;
                ShimCurrentSubscriber.AllInstances.SubIdGet = o => "1234567";
                ShimCurrentSubscriber.AllInstances.WanIpAddressGet = o => "10.10.10.10";

                // set eidt residential gateway to true
                ShimRosettianClient.AllInstances.UpdateONTPortsEquipmentCriteriaCollectionDtoUserDto = (myTestclient, myEquipmentCriteriaDto, userDto) => true;

                // expected search results after Update RG
                var searchEquipmentsResult = new List<EquipmentDto>();
                searchEquipmentsResult.AddRange(mainRg);
                searchEquipmentsResult.AddRange(otherRgs);
                searchEquipmentsResult.Add(ipVideoDevice);

                // set search results to expected
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myTestClient, mySearchFields, myUserDto) => searchEquipmentsResult;

                // expected custom fields
                var equipmentDataDto = mainRg.First(x => x.SerialNumber.EndsWith("D01"));
                equipmentDataDto.CustomFields = customFieldsDto.ToList();

                // set load eqiupment for main RG
                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto =
                    (myTestClient, myEquipmentId, returnExtraData, myUserDto) => equipmentDataDto;

                // set custom fields
                ShimRosettianClient.AllInstances.GetCustomFieldsUserDto = (myTestClient, myUserDto) => customFieldsDto;

                // set ip video device path
                ShimVirtualPathUtility.ToAbsoluteString = (myTestString) => @"http://testapp/images/DVR.png";

                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // RG to be updated
                var model4Update = new ResidentialGatewayModel
                {
                    ID = rgTobeUpdated.SerialNumber,
                    UnitAddress = rgTobeUpdated.UnitAddress
                };

                // call EditResidentialGateway of ResidentialGatewayController
                var result = residentialController.EditResidentialGateway(model4Update) as JsonResult;

                // validate json result
                Assert.IsNotNull(result, "Returned Json result is null");

                dynamic resultData = result.Data;
                var status = resultData.status as string;
                var errorMessage = string.Empty;
                if (status == "error")
                {
                    errorMessage = resultData.errorMessage;
                }
                Assert.AreEqual("valid", status, "status is not valid - {0}", errorMessage);
                var renderedPartial = resultData.returnedPartial as string;
                Assert.IsNotNull(renderedPartial, "Prerendered partial is null.");
            }
        }
        public void AddVideoDevice_ValidateSuccessScenario()
        {
            using (ShimsContext.Create())
            {
                // arrange
                var myContext = new SIMPLTestContext();
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };
                ShimHttpContext.AllInstances.SessionGet = o => session;

                // current subscriber
                const string currentSubscriberId = "CURRENTSUBSCRIBER";

                // current location
                const string currentLocationId = "CURRENTLOCATION";

                // new IP video device to be added
                var customFieldsDto = RgTestData_CustomFieldsCollection();
                var ipVideoDevice = RgTestData_IpVideoDevice(customFieldsDto, "ADIFFERENTLOCATION");

                // set location Id
                ShimCurrentSubscriber.AllInstances.LocationIdGet = o => currentLocationId;

                // set subscriber id
                ShimCurrentSubscriber.AllInstances.SubIdGet = o => currentSubscriberId;

                // set Rosettian LoadEquipment with ipVideoDevice
                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto =
                    (myTestClient, myEquipmentId, returnExtraData, myUserDto) => ipVideoDevice;

                // set Rosettian UpdateEquipment to success
                ShimRosettianClient.AllInstances.UpdateEquipmentEquipmentDtoUserDto =
                    (myTestClient, myEquipmentDto, myUserDto) => true;

                // set Rosettian SearchEquipment to return ipVideoDevice
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myTestClient, myEquipmentDto, myUserDto) => new List<EquipmentDto> { ipVideoDevice };

                //Get Custom Fields
                ShimRosettianClient.AllInstances.GetCustomFieldsUserDto = delegate { return new CustomFieldCollectionDto(); }
                    ;
                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // call AddVideoDevice action method
                var result = residentialController.AddVideoDevice(ipVideoDevice.SerialNumber) as JsonResult;

                // validate returned results
                Assert.IsNotNull(result, "ActionResult is null");
                Assert.IsNotNull(result.Data, "Data is null");
                dynamic actualResult = result.Data;
                Assert.AreEqual("200", actualResult.code);
                Assert.AreEqual("valid", actualResult.status);
            }
        }
        public void AddVideoDevice_DeviceIdDoesNotExist_ValidateFailedScenario()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };
                ShimHttpContext.AllInstances.SessionGet = o => session;

                // current subscriber
                const string currentSubscriberId = "SUBIDWITHANYVALUE";

                // current location
                const string currentLocationId = "LOCIDWITHANYVALUE";

                // deviceId to be added
                const string deviceId = "DEVICEIDDOESNOTEXIST";

                // set location Id
                ShimCurrentSubscriber.AllInstances.LocationIdGet = o => currentLocationId;

                // set subscriber id
                ShimCurrentSubscriber.AllInstances.SubIdGet = o => currentSubscriberId;

                // set LoadEquipment for the IP device to be empty since it does not exist
                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto =
                    (myTestClient, myEquipmentId, returnExtraData, myUserDto) => new EquipmentDto();

                // expected AddVideoDevice Json result
                var expectedResult = new
                {
                    status = "error",
                    errorMessage = string.Format("Error adding device [{0}]: Activation is not allowed, device [{0}] does not exist",
                        deviceId)
                };

                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // call AddVideoDevice action method
                var actualResult = residentialController.AddVideoDevice(deviceId) as JsonResult;

                // validate result
                Assert.IsNotNull(actualResult, "AddVideoDevice Json result is null");
                Assert.IsTrue(actualResult != null && actualResult.Data != null);
                Assert.AreEqual(expectedResult.ToJSON(), actualResult.Data.ToJSON());
            }
        }
        public void UpdateVideoDevices_ValidateSuccessScenario()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

                //Build FakeDto
                var fakeUserDto = myContext.GetFakeUserDtoObject();

                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                ShimBusinessFacade.AllInstances.LoadVideoDevicesSearchFieldsDtoUserDto = (facade, dto, arg3) =>
                    new List<EquipmentDto>();

                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto = (client, s, arg3, arg4) => new EquipmentDto
                {
                    CustomFields = new List<CustomFieldDto> { new CustomFieldDto { Label = "ROOM_LOCATION" } }
                };

                ShimRosettianClient.AllInstances.UpdateEquipmentEquipmentDtoUserDto = (client, dto, arg3) => true;
                ShimErrorLoggingService.AllInstances.LogErrorException = (myClient, myException) => { };

                ShimCurrentSubscriber.AllInstances.LocationIdGet = (mySubscriber) => "0089451";
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();
                var result = residentialController.UpdateVideoDevices("[{\"ID\":\"M77441GA1002\",\"Status\":\"DISABLED\",\"SelectedRoom\":\"GARAGE\",\"GuidInfo\":{\"Guid\":\"454f676e...\",\"Tooltip\":\"454f676e-a1af-474a-a508-8044d505790f\"},\"Model\":{\"ImagePath\":\"/Images/CiscoDVR.png\",\"ModelName\":\"ISB7500\"},\"Type\":\"DVR\"}]");
                Assert.IsNotNull(result, "Partial view result returned is null.");
                Assert.IsTrue(result is JsonResult, "result is not JsonResult");

                var resultJsonResult = result as JsonResult;
                Assert.IsNotNull(resultJsonResult, "Partial view result returned is null.");
                dynamic dynResult = resultJsonResult.Data;
                Assert.AreEqual("valid", dynResult.status, "Status doesn't match expected");
            }
        }
        public void ActivateResidentialGateway_ValidateSuccessScenario()
        {
            using (ShimsContext.Create())
            {
                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                //Arrange
                var myContext = new SIMPLTestContext();

                //Build FakeDto
                var fakeUserDto = myContext.GetFakeUserDtoObject();

                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = o => session;

                var equipmentDto = new CompositeEquipment();

                ShimBusinessFacade.AllInstances.LoadCompositeEquipmentSearchFieldsDtoUserDto = (facade, dto, arg3) =>
                equipmentDto;

                ShimCurrentSubscriber.AllInstances.SubIdGet = o => "89451";
                ShimCurrentSubscriber.AllInstances.LocationIdGet = o => "0000453";
                ShimCurrentSubscriber.AllInstances.WanIpAddressGet = o => "12:12:12:12";
                ShimRosettianClient.AllInstances.LoadSubscriberStringUserDto = (client, subId, userDto) => new SubscriberDto();
                ShimCurrentSubscriber.UpdateWanIpAddressString = (myWanIpAddress) => { };

                ShimRosettianClient.AllInstances.ActivateResidentialGatewayStringStringUserDto =
                    (client, locationId, myDeviceId, userDto) => true;

                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (client, searchFields, userDto) => new List<EquipmentDto>();

                var deviceId = "PACE1122333";

                // create phone controller instance
                var controller = DependencyResolver.Current.GetService<ResidentialGatewayController>();
                var result = controller.ActivateResidentialGateway(deviceId, null);

                // 1st Assert
                Assert.IsNotNull(result, "ResidentialGateway.Update() returned null");

                var jsonResult = result as JsonResult;

                // 2nd Assert
                Assert.IsNotNull(jsonResult, "Cast to JsonResult result in null result");

                // 3rd Assert
                Assert.IsNotNull(jsonResult.Data, "jsonResult.Data is null");

                // 4th Assert
                Assert.AreEqual("valid", ((dynamic)jsonResult.Data).status, "Invalid status code returned from controller");
            }
        }
        public void SwapResidentialGateway_NewRGDoesNotExist_ValidateFailedScenario()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };
                ShimHttpContext.AllInstances.SessionGet = o => session;

                // current location
                const string currentLocationId = "123456789";

                // Set location Id
                ShimCurrentSubscriber.AllInstances.LocationIdGet = o => currentLocationId;

                // expected all devices on current location
                var customFieldsDto = RgTestData_CustomFieldsCollection();
                var mainRg = RgTestData_MainRg(customFieldsDto, currentLocationId);

                // old RG serial number
                var oldRgSerialNumber = mainRg[0].SerialNumber;

                // new RG serial number
                const string newRgSerialNumber = "NONEXISTRGSERIALNUMBER";

                // expected ROZ error message
                var expectedRozErrorMessage =
                    string.Format("Swap is not allowed: New residential gateway [NONEXISTRGSERIALNUMBER] does not exist");

                // set ROZ SwapResidentialGateway exception
                ShimRosettianClient.AllInstances.SwapResidentialGatewayStringStringStringUserDto =
                    (myTestClient, myLocationId, myOldRgSerialNumber, myNewRgSerialNumber, myUserDto) =>
                    {
                        throw new Exception(expectedRozErrorMessage);
                    };

                // expected SwapResidentialGateway Json result
                var expectedResult = new
                {
                    status = "error",
                    errorMessage = string.Format
                    (
                        "Error swapping old Residential Gateway {0} with new Residential Gateway {1}: {2}",
                        oldRgSerialNumber, newRgSerialNumber, expectedRozErrorMessage
                    )
                };

                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // call SwapResidentialGateway action method
                var actualResult = residentialController.SwapResidentialGateway(currentLocationId, oldRgSerialNumber, newRgSerialNumber) as JsonResult;

                // validate result
                Assert.IsNotNull(actualResult, "SwapResidentialGateway Json result is null");
                Assert.IsTrue(actualResult != null && actualResult.Data != null);
                Assert.AreEqual(expectedResult.ToJSON(), actualResult.Data.ToJSON());
            }
        }
        public void ActivateResidentialGateway_hasNoMainRg_hasListOtherRgs_hasIpVideoDevice_ValidateSuccessScenario()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

                //Build FakeDto
                var fakeUserDto = myContext.GetFakeUserDtoObject();

                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = o => session;

                //Expected result
                const string expectedIpAddressLabel = "WAN_IP_ADDR";
                const string expectedIpAddressValue = "10.143.22.1";
                const string expectedBaseModelValue = "A5550";
                const string expectedSerialNumber = "PACE99999991";
                const string expectedUnitAddress = "001E46";
                const string expectedLocationId = "123456789";
                const string expectedRoomLocationLabel = "ROOM_LOCATION";
                const string expectedRoomLocationValue = "TEST ROOM";
                const string expectedMacAddressLable = "ENET_MAC_ADDR";
                const string expectedMacAddressValue = "A0B1C2D3E4F5";
                const string expectedSelectedRoomLabel = "SELECTED_ROOM";
                const string expectedSelectedRoomValue = "MASTER BED ROOM";

                var customFieldsDto = new List<CustomFieldDto>();
                // RG custom fields
                var expectedIpAddressCustomField = new CustomFieldDto
                {
                    Label = expectedIpAddressLabel,
                    Value = expectedIpAddressValue,
                };
                customFieldsDto.Add(expectedIpAddressCustomField);

                var expectedMacAddressCustomField = new CustomFieldDto
                {
                    Label = expectedMacAddressLable,
                    Value = expectedMacAddressValue
                };
                customFieldsDto.Add(expectedMacAddressCustomField);

                // ip video device custom fields
                var expectedRoomLocationCustomField = new CustomFieldDto
                {
                    Label = expectedRoomLocationLabel,
                    Value = expectedRoomLocationValue
                };
                customFieldsDto.Add(expectedRoomLocationCustomField);

                var expectedSelectedRoomCustomField = new CustomFieldDto
                {
                    Label = expectedSelectedRoomLabel,
                    Value = expectedSelectedRoomValue
                };
                customFieldsDto.Add(expectedSelectedRoomCustomField);

                var customFieldsCollection = new CustomFieldCollectionDto
                {
                    expectedIpAddressCustomField,
                    expectedRoomLocationCustomField,
                    expectedMacAddressCustomField
                };

                var rgType = new EquipmentTypeDto
                {
                    ONTModel = new ONTModelDto
                    {
                        BaseModel = expectedBaseModelValue
                    },
                    Category = EquipmentCategoryDto.RGDataPort
                };

                var ipVideoType = new EquipmentTypeDto
                {
                    Model = "ISP7500",
                    Category = EquipmentCategoryDto.DVR,
                    IptvCapable = true
                };

                // main active RG
                var equipmentDataDto = new EquipmentDto
                {
                    SerialNumber = expectedSerialNumber + "D01",
                    CustomFields = customFieldsDto,
                    UnitAddress = expectedUnitAddress,
                    LocationId = expectedLocationId,
                    Type = rgType,
                    Status = "ACTIVE"
                };
                var mainRg = new List<EquipmentDto>
                {
                    equipmentDataDto,
                    new EquipmentDto
                    {
                        SerialNumber = expectedSerialNumber + "P01",
                        CustomFields = customFieldsDto,
                        UnitAddress = expectedUnitAddress,
                        LocationId = expectedLocationId,
                        Type = rgType,
                        Status = "ACTIVE"
                    },
                    new EquipmentDto
                    {
                        SerialNumber = expectedSerialNumber + "P02",
                        CustomFields = customFieldsDto,
                        UnitAddress = expectedUnitAddress,
                        LocationId = expectedLocationId,
                        Type = rgType,
                        Status = "ACTIVE"
                    }
                };

                // ip video device
                var ipVideoDevice = new EquipmentDto
                {
                    SerialNumber = "STBTEST1234",
                    CustomFields = new List<CustomFieldDto> { expectedRoomLocationCustomField },
                    UnitAddress = "1234567890",
                    LocationId = expectedLocationId,
                    Type = ipVideoType,
                    Status = "ACTIVE"
                };

                // other RGs on the account
                var otherRgs = new List<EquipmentDto>
                {
                    new EquipmentDto
                    {
                        SerialNumber = "RGCREATE1234" + "D01",
                        CustomFields = customFieldsDto,
                        UnitAddress = expectedUnitAddress,
                        LocationId = expectedLocationId,
                        Type = rgType,
                        Status = "IGNORE"
                    },
                    new EquipmentDto
                    {
                        SerialNumber = "RGCREATE2345" + "D01",
                        CustomFields = customFieldsDto,
                        UnitAddress = expectedUnitAddress,
                        LocationId = expectedLocationId,
                        Type = rgType,
                        Status = "IGNORE"
                    },
                    new EquipmentDto
                    {
                        SerialNumber = "RGCREATE3456" + "D01",
                        CustomFields = customFieldsDto,
                        UnitAddress = expectedUnitAddress,
                        LocationId = expectedLocationId,
                        Type = rgType,
                        Status = "IGNORE"
                    },
                };

                // set location
                ShimCurrentSubscriber.AllInstances.LocationIdGet = o => expectedLocationId;

                // set WanIpAddress
                ShimCurrentSubscriber.AllInstances.SubIdGet = o => "1234567";
                ShimCurrentSubscriber.AllInstances.WanIpAddressGet = o => "12:12:12:12";
                ShimRosettianClient.AllInstances.LoadSubscriberStringUserDto = (client, subId, userDto) => new SubscriberDto();
                ShimCurrentSubscriber.UpdateWanIpAddressString = (myWanIpAddress) => { };

                // set activate residential gateway to true
                ShimRosettianClient.AllInstances.ActivateResidentialGatewayStringStringUserDto =
                    (myTestclient, mylocationId, myDeviceId, userDto) => true;

                // expected search results after Activate RG
                var searchEquipmentsResult = new List<EquipmentDto>();
                searchEquipmentsResult.AddRange(mainRg);
                searchEquipmentsResult.AddRange(otherRgs);
                searchEquipmentsResult.Add(ipVideoDevice);

                // set search results to expected
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myTestClient, mySearchFields, myUserDto) => searchEquipmentsResult;

                // expected custom fields
                equipmentDataDto.CustomFields = customFieldsDto;

                // set load eqiupment for main RG
                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto =
                    (myTestClient, myEquipmentId, returnExtraData, myUserDto) => equipmentDataDto;

                // set custom fields
                ShimRosettianClient.AllInstances.GetCustomFieldsUserDto = (myTestClient, myUserDto) => customFieldsCollection;

                // set ip video device path
                ShimVirtualPathUtility.ToAbsoluteString = (myTestString) => @"http://testapp/images/DVR.png";

                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // call ActivateResidentialGateway of ResidentialGatewayController
                var result = residentialController.ActivateResidentialGateway(expectedSerialNumber, expectedLocationId) as JsonResult;

                // validate json result
                Assert.IsNotNull(result, "Returned Json result is null");

                dynamic resultData = result.Data;
                var status = resultData.status as string;
                var errorMessage = string.Empty;
                if (status == "error")
                {
                    errorMessage = resultData.errorMessage;
                }
                Assert.AreEqual("valid", status, "status is not valid - {0}", errorMessage);
                var renderedPartial = resultData.returnedPartial as string;
                Assert.IsNotNull(renderedPartial, "Prerendered partial is null.");
            }
        }
        public void SwapIpVideoDevice_SwapOutVAPForNonVAP()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                const string selectedRoomConst = "testroom";
                var myContext = new SIMPLTestContext();
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                ShimCurrentUser.AllInstances.RolesGet = x =>
                {
                    return new List<int>();
                };
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimResidentialGatewayController.AllInstances.ValidateDeviceEquipmentDto = (controller, dto) =>
                {
                    return new RozResponseDto { Code = "200", Message = String.Empty };
                };

                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                ShimHttpContext.AllInstances.SessionGet = o => session;

                // VAP device to test
                EquipmentDto VAPDevice = new EquipmentDto();
                VAPDevice.Type.Category = EquipmentCategoryDto.VideoAccessPoint;

                // Non-VAP device to test
                EquipmentDto NonVAPDevice = new EquipmentDto();
                NonVAPDevice.Type.Category = EquipmentCategoryDto.DVR;

                // current location
                const string currentLocationId = "LOCIDWITHANYVALUE";

                // set location Id
                ShimCurrentSubscriber.AllInstances.LocationIdGet = o => currentLocationId;

                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // Test room
                string selectedRoomValue = "testroom";

                // Try to replace VAP device with a Non-VAP device

                string result =
                    residentialController.SwapIpVideoDevices(VAPDevice, NonVAPDevice, selectedRoomValue).ToJSON();
                XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(
                    Encoding.UTF8.GetBytes(result), new XmlDictionaryReaderQuotas());
                XElement root = XElement.Load(jsonReader);
                int code = Convert.ToInt32(root.XPathSelectElement(@"//code").Value);
                string status = root.XPathSelectElement(@"//status").Value.ToString();
                string selectedRoomReturned = root.XPathSelectElement(@"//sRoom").Value.ToString();
                string errorString = root.XPathSelectElement(@"//errorMessage").Value.ToString();

                if (code != 400 && code != 200 && code != 202)
                {
                    Assert.Inconclusive("Unknown Error.");
                }
                if ((code == 200 || code == 202) && status == "error")
                {
                    Assert.Inconclusive("Device untestable as validation failed.");
                }
                if (code == 400 && status == "error" && errorString == "Cannot swap out a VAP device for a non-VAP device.")
                {
                    Assert.IsTrue(true);
                }

                Assert.AreEqual(selectedRoomConst, selectedRoomReturned, "Selected room changed.");
            }
        }
        public void If_TiVo_Only_Subscriber_Redirect_to_RF_Video_Partial()
        {
            using (ShimsContext.Create())
            {

                //Arrange
                var myContext = new SIMPLTestContext();

                //Build FakeDto
                var fakeUserDto = myContext.GetFakeUserDtoObject();

                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // SIMPL.Session.Fakes.ShimCurrentSubscriber.SessionInstanceGet = () => new ShimCurrentSubscriber();

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                        {
                            return null;
                        }
                        if (s == "Subscriber")
                        {
                            return new List<string>();
                        }
                        return null;
                    }
                };

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = o => session;

                ShimCurrentSubscriber.AllInstances.HasTivoServiceOnlyGet = delegate { return true; };

                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();
                var result = residentialController.Index("subID", "locID", "devID");

                Assert.IsNotNull(result);
                Assert.IsTrue(result is RedirectToRouteResult);

                var action = result as RedirectToRouteResult;

                Assert.AreEqual("LoadVideoMgmt", action.RouteValues["action"], string.Format("The redirect should have been to the LoadVideoMgmt action, instead it redirected to {0}", action.RouteValues["action"]));
                Assert.AreEqual("VideoDevice", action.RouteValues["controller"], string.Format("The redirect should have been to the VideoDevice controller, instead it redirected to {0}", action.RouteValues["controller"]));

            }
        }
        public void UpdateSubID_ValidateUserAbleToUpdateSubscriberID()
        {
            using (ShimsContext.Create())
            {
                // Given a user that has permission to update subscriber id
                ShimCurrentUser.AsUserDto = () => new UserDto();

                // And a valid subscriber
                const string subId = "subId";
                const string subName = "subName";

                var currentSubscriber = new ShimCurrentSubscriber
                {
                    SubIdGet = () => subId,
                    NameGet = () => subName,
                };

                var updateSubIdModel = new UpdateSubIDModel
                {
                    NewSubID = "newsubid",
                    OldSubID = subId,
                };

                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                ShimCurrentSubscriber.SessionInstanceGet = () => new ShimCurrentSubscriber();
                ShimCurrentSubscriber.GetInstance = () => currentSubscriber;

                // When enabling the service
                var subscriberController = DependencyResolver.Current.GetService<SubscriberController>();

                ShimRosettianClient.AllInstances.RenameSubscriberStringStringUserDto =
                    (myTestClient,myOldSubId, myNewSubId, myUserDto) => { };

                var actionResponse = subscriberController.UpdateSubID(updateSubIdModel) as JsonResult;

                // Then the user receives a response
                Assert.IsNotNull(actionResponse, "Json result is null");
                Assert.IsNotNull(actionResponse.Data, "Json result data is null");

                // And the response is successful
                // And the service is enabled
                var jss = new JavaScriptSerializer();
                var expectedResult = new
                {
                    status = "valid",
                    returnedPartial = "",
                }.ToJSON();
                Assert.AreEqual(jss.Serialize(expectedResult), jss.Serialize(actionResponse.Data.ToJSON()));
            }
        }
        public void Index_HappyPath()
        {
            using (ShimsContext.Create())
            {

                //Arrange
                var myContext = new SIMPLTestContext();

                //Build FakeDto
                var fakeUserDto = myContext.GetFakeUserDtoObject();

                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // SIMPL.Session.Fakes.ShimCurrentSubscriber.SessionInstanceGet = () => new ShimCurrentSubscriber();

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = o => session;

                //Expected result
                const string expectedIpAddressLabel = "WAN_IP_ADDR";
                const string expectedIpAddressValue = "10.143.22.1";
                const string expectedBaseModelValue = "A5550";
                const string expectedSerialNumber = "PACE99999991";
                const string expectedUnitAddress = "0D-U9-M6-D2-D7";
                const string expectedLocationId = "locId";
                const string expectedRoomLocationLabel = "ROOM_LOCATION";
                const string expectedRoomLocationValue = "TEST ROOM";
                const string expectedMacAddressLable = "ENET_MAC_ADDR";
                const string expectedMacAddressValue = "A0B1C2D3E4F5";

                var customFieldsDto = new List<CustomFieldDto>();
                var expectedIpAddressCustomField = new CustomFieldDto
                {
                    Label = expectedIpAddressLabel,
                    Value = expectedIpAddressValue,
                };
                customFieldsDto.Add(expectedIpAddressCustomField);

                var expectedRoomLocationCustomField = new CustomFieldDto
                {
                    Label = expectedRoomLocationLabel,
                    Value = expectedRoomLocationValue
                };
                customFieldsDto.Add(expectedRoomLocationCustomField);

                var expectedMacAddressCustomField = new CustomFieldDto
                {
                    Label = expectedMacAddressLable,
                    Value = expectedMacAddressValue
                };
                customFieldsDto.Add(expectedMacAddressCustomField);

                var customFieldsCollection = new CustomFieldCollectionDto
                {
                    expectedIpAddressCustomField,
                    expectedRoomLocationCustomField,
                    expectedMacAddressCustomField
                };

                var RgType = new EquipmentTypeDto
                {
                    ONTModel = new ONTModelDto
                    {
                        BaseModel = expectedBaseModelValue
                    },
                    Category = EquipmentCategoryDto.RGDataPort
                };

                var IPVideoType = new EquipmentTypeDto
                {
                    ONTModel = new ONTModelDto
                    {
                        BaseModel = expectedBaseModelValue
                    },
                    Category = EquipmentCategoryDto.DVR,
                    IptvCapable = true
                };

                var equipmentDataDto = new EquipmentDto
                {
                    SerialNumber = expectedSerialNumber + "D01",
                    CustomFields = customFieldsDto,
                    UnitAddress = expectedUnitAddress,
                    LocationId = expectedLocationId,
                    Type = RgType,
                    Status = "ACTIVE"
                };

                var equipmentPhoneDto = new EquipmentDto
                {
                    SerialNumber = expectedSerialNumber + "P01",
                    CustomFields = customFieldsDto,
                    UnitAddress = expectedUnitAddress,
                    LocationId = expectedLocationId,
                    Type = RgType,
                    Status = "ACTIVE"
                };

                var ipVideoDevice = new EquipmentDto
                {
                    SerialNumber = expectedSerialNumber + "P01",
                    CustomFields = customFieldsDto,
                    UnitAddress = expectedUnitAddress,
                    LocationId = expectedLocationId,
                    Type = IPVideoType,
                    Status = "ACTIVE"
                };

                var searchEquipmentsResult = new List<EquipmentDto>();
                searchEquipmentsResult.Add(equipmentDataDto);
                searchEquipmentsResult.Add(equipmentPhoneDto);
                searchEquipmentsResult.Add(ipVideoDevice);

                var loadSubscriberPhonesResult = new List<PhoneDto>();

                // shim CurrentSubscriber WanIpAddress
                ShimCurrentSubscriber.GetInstance = () => new ShimCurrentSubscriber
                {
                    WanIpAddressGet = () => expectedIpAddressValue,
                    ProvisionedPhonesListGet = () => loadSubscriberPhonesResult
                };

                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myTestClient, mySearchFields, myUserDto) => searchEquipmentsResult;

                equipmentDataDto.CustomFields = customFieldsDto;

                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto =
                    (myTestClient, myEquipmentId, returnExtraData, myUserDto) => equipmentDataDto;

                ShimRosettianClient.AllInstances.GetCustomFieldsUserDto =
                    (myTestClient, myUserDto) => customFieldsCollection;

                ShimVirtualPathUtility.ToAbsoluteString =
                    (myTestString) => @"http://testapp/images/DVR.png";

                ShimDBCache.LocationsGet = delegate { return new List<Location>(); };

                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();
                var result = residentialController.Index("subID", "locID", "devID") as PartialViewResult ?? new PartialViewResult();
                Assert.IsNotNull(result, "Partial view result returned is null.");
                Assert.IsTrue(result.ViewName.Equals("Index"), "View names do not match.");
                Assert.AreEqual(expectedIpAddressValue, ((ResidentialGatewayModel)(result.Model)).IPAddress, "Expected IP does not match with actual IP.");
                Assert.AreEqual(expectedUnitAddress, ((ResidentialGatewayModel)(result.Model)).UnitAddress, "Expected UnitAddress does not match with actual Unit Address.");
                Assert.AreEqual(expectedMacAddressValue, ((ResidentialGatewayModel)(result.Model)).MacAddress, "Expected MacAddress does not match with actual Mac Address.");
                Assert.AreEqual(expectedBaseModelValue, ((ResidentialGatewayModel)(result.Model)).Model, "Expected Model number does not match with actual Model number.");
                Assert.AreEqual(expectedSerialNumber, ((ResidentialGatewayModel)(result.Model)).ID, "Expected serial number does not match with actual serial number.");
                Assert.IsTrue(((ResidentialGatewayModel)(result.Model)).VideoDevices.Any(), "No video devices found.");
                Assert.IsTrue(((ResidentialGatewayModel)(result.Model)).VideoDevices.First().Type.Equals("DVR"), "IP Video device type mismatch.");
                Assert.IsTrue(((ResidentialGatewayModel)(result.Model)).VideoDevices.First().RoomLocation.Any(), "No Room locations found.");
            }
        }
        public void User_can_load_a_location_that_is_not_associated_to_a_subscriber_with_no_devices()
        {
            //Setup
            var myContext = new SIMPLTestContext();
            const string locationId = "9999999";

            using (ShimsContext.Create())
            {
                // Given a user
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the session state for HttpContext
                // http://blog.christopheargento.net/2013/02/02/testing-untestable-code-thanks-to-ms-fakes/
                var session = new ShimHttpSessionState();
                session.ItemGetString = (key) => { if (key == "LoadedLocation") return null; return null; };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                ShimCurrentSubscriber.UpdateSubscriberLocationModel = delegate { };

                // And a known location
                var fakeLocationDto = myContext.GetFakeLocationDtoObject(locationId);

                ShimRosettianClient.AllInstances.LoadLocationStringUserDto = (myRosettianClient, myLocationId, myUserDto) => fakeLocationDto;

                // And the location has no devices
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto = (myRosettianClient, mySearchFields, myUser) => new List<EquipmentDto>();

                // And the location is not associated to a subscriber
                var fakeSubscriberDto = new List<SubscriberDto>();
                ShimRosettianClient.AllInstances.SearchSubscribersSearchFieldsDtoUserDto = (myRosettianClient, mySearchFields, myUserDto) => fakeSubscriberDto;

                // When loading that location
                var actionResult = SubscriberControllerForTests.LoadLocation(locationId) as ViewResult;

                // Then the user receives a response
                Assert.IsNotNull(actionResult, "SubscriberController LoadLocation method returned null");

                // And the response is successful
                Assert.AreEqual("Index2", actionResult.ViewName, "actionResult.RouteValues[\"action\"]");

                // And the response returns the location information
                var expectedModel = fakeLocationDto.MapToSubscriberModel();
                var actualModel = actionResult.Model as SubscriberModel;
                Assert.IsNotNull(actualModel, "The model returned was empty");
                Assert.IsNotNull(actualModel.SubLocationModel, "The sub location model returned was empty");
                Assert.IsTrue(expectedModel.SubLocationModel.Address1.Equals(actualModel.SubLocationModel.Address1), "The Address was different");

                // And the location matches the requested location
                Assert.AreEqual(locationId, actualModel.SubLocationModel.LocationID, "Location Id did not match the one that was searched for.");

                // And the notes tab is the selected tab
                Assert.AreEqual(5, actualModel.SelectedTabIndex, "The default tab was not the notes tab");
            }
        }
        public void Index_hasIpVideoDevices_IpVideoDeviceHasBadUnitAddress()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

                //Build FakeDto
                var fakeUserDto = myContext.GetFakeUserDtoObject();

                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = o => session;
                ShimCurrentSubscriber.AllInstances.HasTivoServiceOnlyGet = delegate { return false; };

                // current location
                const string expectedLocationId = "123456789";

                // expected all devices on current location
                var customFieldsDto = RgTestData_CustomFieldsCollection();
                var mainRg = RgTestData_MainRg(customFieldsDto, expectedLocationId);
                var otherRgs = RgTestData_OtherRgList(customFieldsDto, expectedLocationId);
                var ipVideoDevices = new List<EquipmentDto>
                {
                    RgTestData_IpVideoDevice(customFieldsDto, expectedLocationId),
                    RgTestData_IpVideoDevice2(customFieldsDto, expectedLocationId)
                };
                Assert.IsTrue(ipVideoDevices.Any(x => string.IsNullOrWhiteSpace(x.UnitAddress)), "1 of IP video devices should have null or empty unit address");

                // expected search results
                var searchEquipmentsResult = new List<EquipmentDto>();
                searchEquipmentsResult.AddRange(mainRg);
                searchEquipmentsResult.AddRange(otherRgs);
                searchEquipmentsResult.AddRange(ipVideoDevices);

                // set search results to expected search results
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myTestClient, mySearchFields, myUserDto) => searchEquipmentsResult;

                // set load phones shim
                var loadSubscriberPhonesResult = new List<PhoneDto>();
                ShimCurrentSubscriber.AllInstances.ProvisionedPhonesListGet = o => loadSubscriberPhonesResult;

                // expected custom fields
                var equipmentDataDto = mainRg.First(x => x.SerialNumber.EndsWith("D01"));
                equipmentDataDto.CustomFields = customFieldsDto.ToList();

                // epected RG details
                var expectedIpAddressValue = equipmentDataDto.CustomFields.First(x => x.Label == "WAN_IP_ADDR").Value;
                var expectedBaseModelValue = equipmentDataDto.Type.ONTModel.BaseModel;
                var expectedSerialNumber = equipmentDataDto.SerialNumber.Substring(0, equipmentDataDto.SerialNumber.Length - 3);
                var expectedUnitAddress = equipmentDataDto.UnitAddress;
                var expectedMacAddressValue = equipmentDataDto.CustomFields.First(x => x.Label == "ENET_MAC_ADDR").Value;

                // set WanIpAddress
                ShimCurrentSubscriber.AllInstances.SubIdGet = o => "1234567";
                ShimCurrentSubscriber.AllInstances.WanIpAddressGet = o => expectedIpAddressValue;
                ShimRosettianClient.AllInstances.LoadSubscriberStringUserDto = (client, subId, userDto) => new SubscriberDto();
                ShimCurrentSubscriber.UpdateWanIpAddressString = (myWanIpAddress) => { };

                // set load equipment for main RG
                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto =
                    (myTestClient, myEquipmentId, returnExtraData, myUserDto) => equipmentDataDto;

                ShimRosettianClient.AllInstances.GetCustomFieldsUserDto = (myTestClient, myUserDto) => customFieldsDto;
                ShimVirtualPathUtility.ToAbsoluteString = (myTestString) => @"http://testapp/images/DVR.png";
                ShimDBCache.LocationsGet = delegate { return new List<Location>(); };

                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // call Index of ResidentialGatewayController
                var result = residentialController.Index("12345", expectedLocationId, null) as PartialViewResult ?? new PartialViewResult();

                // validate partial view and model is not null
                Assert.IsNotNull(result, "Partial view result returned is null.");
                Assert.IsTrue(result.ViewName.Equals("Index"), "View names do not match.");

                var residentialGatewayModel = (ResidentialGatewayModel)(result.Model);
                Assert.IsNotNull(residentialGatewayModel);

                // validate the ErrorInfo is null
                Assert.IsNull(residentialGatewayModel.ErrorInfo);

                // validate main RG details
                Assert.AreEqual(expectedIpAddressValue, residentialGatewayModel.IPAddress, "IP does not match.");
                Assert.AreEqual(expectedUnitAddress, residentialGatewayModel.UnitAddress, "UnitAddress does not match.");
                Assert.AreEqual(expectedMacAddressValue, residentialGatewayModel.MacAddress, "MacAddress does not match.");
                Assert.AreEqual(expectedBaseModelValue, residentialGatewayModel.Model, "Model number does not match.");
                Assert.AreEqual(expectedSerialNumber, residentialGatewayModel.ID, "Serial number does not match.");

                // validate other RGs list
                Assert.IsTrue(residentialGatewayModel.OtherRGList.Any(), "No other RGs found.");
                Assert.AreEqual(otherRgs.Count, residentialGatewayModel.OtherRGList.Count, "Other RGs count does not match.");
                otherRgs = otherRgs.OrderBy(x => x.SerialNumber).ToList();
                residentialGatewayModel.OtherRGList = residentialGatewayModel.OtherRGList.OrderBy(x => x.ID).ToList();
                for (int i = 0; i < otherRgs.Count; i++)
                {
                    var expected = otherRgs[i];
                    var actual = residentialGatewayModel.OtherRGList[i];
                    Assert.AreEqual(expected.SerialNumber.Substring(0, expected.SerialNumber.Length - 3), actual.ID, "Other RG serial number does not match.");
                    Assert.AreEqual(expected.LocationId, actual.LocationID, "Other RG location id does not match.");
                    Assert.AreEqual(expected.Status, actual.Status, "Other RG status does not match.");
                    Assert.AreEqual(expected.UnitAddress, actual.UnitAddress, "Other RG UnitAddress does not match.");
                    Assert.AreEqual(expected.Type.ONTModel.BaseModel, actual.Model, "Other RG UnitAddress does not match.");
                }

                // validate ip video device
                Assert.IsTrue(residentialGatewayModel.VideoDevices.Any(), "No video devices found.");
                Assert.AreEqual(ipVideoDevices.Count, residentialGatewayModel.VideoDevices.Count, "IP Video devices count does not match.");
                ipVideoDevices = ipVideoDevices.OrderBy(x => x.SerialNumber).ToList();
                residentialGatewayModel.VideoDevices = residentialGatewayModel.VideoDevices.OrderBy(x => x.ID).ToList();

                Assert.IsTrue(ipVideoDevices.Any(x => string.IsNullOrWhiteSpace(x.UnitAddress)), "1 of expected IP video devices should have null or empty unit address");
                for (var i = 0; i < ipVideoDevices.Count; i++)
                {
                    var expected = ipVideoDevices[i];
                    var actual = residentialGatewayModel.VideoDevices[i];
                    Assert.AreEqual(expected.Type.Category.ToString(), actual.Type, "IP Video device type mismatch.");
                    Assert.AreEqual(expected.Type.Model, actual.Model.ModelName, "IP Video device model mismatch.");
                    Assert.AreEqual(expected.SerialNumber, actual.ID, "IP Video device serial number does not match.");
                    Assert.AreEqual(expected.Status, actual.Status, "IP Video device  does not match.");
                    Assert.AreEqual(expected.UnitAddress, actual.GuidInfo.Tooltip, "IP Video device UnitAddress does not match.");
                    if (string.IsNullOrWhiteSpace(expected.UnitAddress))
                    {
                        Assert.IsTrue(string.IsNullOrWhiteSpace(actual.GuidInfo.Tooltip), "Actual unit address should be null for {0}", actual.ID);
                        Assert.AreEqual("No Data", actual.GuidInfo.Guid, "GUID should be displayed as No Data if unit address is null or empty");
                    }
                }
            }
        }
        public void Index_HasAddressConflict_True()
        {
            using (ShimsContext.Create())
            {

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                var customer = new CustomerDto();
                customer.CitizensPostalAddress.AddressTexts.Add(new AddressTextDto() { Address = "TestBillingAddress", SequenceNumber = 0 });
                var billingAccountId = new BillingAccountIdDto();
                ShimCurrentSubscriber.AllInstances.CurrentBillingAccountGet = (myTest) => new CustomerAccountDto()
                {

                    Customer = customer,
                    BillingAccountId = billingAccountId

                };

                const string subId = "123456789";
                const string headend = "04";
                const string locId = "123456789";
                var address1 = "2345 TEST ADDRESS1";
                var address2 = "APT 2";
                var city = "REDMOND";
                var state = "WA";
                var zip = "98052";

                // Service Address
                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => new ServiceAccountDto
                {
                    Address = new ServiceAddressDto
                    {
                        Address1 = address1,
                        Address2 = address2,
                        Locality = city,
                        StateOrProvince = state,
                        Postcode = zip
                    },
                };

                // Provisioning Service Address
                ShimCurrentSubscriber.AllInstances.HeadendCodeGet = (myTestParam) => headend;
                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myTestParam) => locId;
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => subId;
                ShimCurrentSubscriber.AllInstances.AddressGet = (myTestParam) => address1 + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.Address2Get = (myTestParam) => address2 + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.CityGet = (myTestParam) => city + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.StateGet = (myTestParam) => state + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.ZipGet = (myTestParam) => zip + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.RateCenterGet = (myTestParam) => "TestRateCenter";
                ShimCurrentSubscriber.AllInstances.NetworkLocationCodeGet = (myTestParam) => "TestNetworkCode";

                var accountsController = DependencyResolver.Current.GetService<AccountsController>();
                var result = accountsController.Index();
                Assert.IsNotNull(result);

                // Validate the HasAddressConflict flag
                var hasAddressConflict = ((AccountTuple) result.Model).ServiceAccount.Addresses.ProvisioningAddress.Location.HasAddressConflict;
                Assert.IsTrue(hasAddressConflict, "HasAddressConflict should be false");
            }
        }
        public void LoadPPV_VOD_Mgmt_HasPPVSettings_HasPPVPrivilegeUnlimited_HasVideoDeviceActions_UserAbleToLoadPpvVodMgmt()
        {
            using (ShimsContext.Create())
            {
                // Given a user
                ShimCurrentUser.AsUserDto = () => new UserDto();

                // And a provisioned subscriber
                const string subId = "subid";

                // And the subscriber has valid ppv vod settings
                // And the ppv privilege is unlimited
                // And the subscriber has history of video device actions for drop
                var ppvVodMgmtModel = new PPV_VOD_MgmtModel
                {
                    PIN = "1234",
                    PINRequired = true,
                    PPVCap = "150.00",
                    PPVPrivilege = SubscriberEnums.PPVPrivilegeEnum.Unlimited,
                    PPVResetDay = 15,
                    DeviceActions = new VideoDeviceActionCollectionDto
                    {
                        new VideoDeviceActionDto
                        {
                            DeviceID = "deviceid",
                            DeviceModel = "videodevicemodel",
                            Action = "dropped",
                            ActionDate = DateTime.Now,
                        }
                    }
                };

                // And the user has loaded the subscriber
                var currentSubscriber = new ShimCurrentSubscriber
                {
                    SubIdGet = () => subId,
                    PINGet = () => ppvVodMgmtModel.PIN,
                    PINRequiredGet = () => ppvVodMgmtModel.PINRequired,
                    PPVPrivilegeGet = () => ppvVodMgmtModel.PPVPrivilege,
                    PPVResetDayGet = () => ppvVodMgmtModel.PPVResetDay.ToString(CultureInfo.InvariantCulture),
                    PPVCapGet = () => ppvVodMgmtModel.PPVCap
                };

                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                ShimCurrentSubscriber.SessionInstanceGet = () => new ShimCurrentSubscriber();
                ShimCurrentSubscriber.GetInstance = () => currentSubscriber;

                // When loading the ppv and vod management for the subscriber
                ShimRosettianClient.AllInstances.GetVideoDeviceActionsStringUserDto =
                    (myTestClient, mySubId, myUserDto) => ppvVodMgmtModel.DeviceActions;

                var ppvVodController = DependencyResolver.Current.GetService<PPV_VODController>();
                var actionResponse = ppvVodController.LoadPPV_VOD_Mgmt(subId) as PartialViewResult;

                // Then the user receives a response
                Assert.IsNotNull(actionResponse, "PpvVodControllor PPV_VOD_Mgmt_Partial action method returned null");

                // And the response is successful
                Assert.AreEqual("PPV_VOD_Mgmt_Partial", actionResponse.ViewName);
                var actualPpvVodMgmtModel = actionResponse.Model as PPV_VOD_MgmtModel;
                Assert.IsNotNull(actualPpvVodMgmtModel, "PPV_VOD_MgmtModel is null");

                // And the returned ppv vod info matches with the requested ppv vod info for the subscriber
                Assert.AreEqual(ppvVodMgmtModel.PPVPrivilege, actualPpvVodMgmtModel.PPVPrivilege, "PPVPrivilege does not match");
                Assert.AreEqual(ppvVodMgmtModel.PPVCap, actualPpvVodMgmtModel.PPVCap, "PPVCape does not match");
                Assert.AreEqual(ppvVodMgmtModel.PPVResetDay, actualPpvVodMgmtModel.PPVResetDay, "PPVResetDay does not match");
                Assert.AreEqual(ppvVodMgmtModel.PINRequired, actualPpvVodMgmtModel.PINRequired, "PinRequired does not match");
                Assert.AreEqual(ppvVodMgmtModel.PIN, actualPpvVodMgmtModel.PIN, "PIN does not match");

                // And the returned video devices actions matches with the requestd video devices actions for the subscriber
                var jss = new JavaScriptSerializer();
                Assert.AreEqual(jss.Serialize(ppvVodMgmtModel.DeviceActions), jss.Serialize(actualPpvVodMgmtModel.DeviceActions), "DeviceActions does not match");
            }
        }
        public void List_HappyPath()
        {
            using (ShimsContext.Create())
            {
                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myString) => "SAME";

                var list = new List<ServiceAccountDto>()
                {
                    new ServiceAccountDto
                    {
                        Address = new ServiceAddressDto { Address1 = "TestServiceAddress1", LocationId = "SAME"},
                        IsBTN = false,
                        SubscriberName = "TestServiceName",
                        TN = "TestServiceNumber1",
                        USI = "TestServiceUSI1"
                    },
                    new ServiceAccountDto
                    {
                        Address = new ServiceAddressDto { Address1 = "TestServiceAddress3", LocationId = "DIFFERENT"},
                        IsBTN = false,
                        SubscriberName = "TestServiceName",
                        TN = "TestServiceNumber3",
                        USI = "TestServiceUSI3"
                    }
                };

                ShimCurrentSubscriber.AllInstances.ServiceAccountListGet = (myTest) => list;

                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => new ServiceAccountDto
                {
                    Address = new ServiceAddressDto { Address1 = "TestServiceAddress2", LocationId = "SAME"},
                    IsBTN = false,
                    SubscriberName = "TestServiceName2",
                    TN = "TestServiceNumber2",
                    USI = "TestServiceUSI2"
                };

                var accountsController = DependencyResolver.Current.GetService<AccountsController>();
                var result = accountsController.List(new DataSourceRequest());
                var gridAccounts = new List<GridAccount>(((IEnumerable<GridAccount>)((DataSourceResult)((JsonResult) result).Data).Data));
                Assert.IsTrue(gridAccounts.Any(ga => ga.Address.Contains("TestServiceAddress3")), "Result does not contain expected data.");
                Assert.IsTrue(gridAccounts.Any(ga => !ga.Address.Contains("TestServiceAddress1")), "Result contained service account having a different location id");
            }
        }
        public void UpdatePPVVOD_ValidateUserAbleToUpdatePPVPrivilegeFromCappedToUnlimited()
        {
            using (ShimsContext.Create())
            {
                // Given a user that has permission to update ppv vod settings
                ShimCurrentUser.AsUserDto = () => new UserDto();

                // And a valid  provisioned subscriber
                const string subId = "subId";

                // And the subscriber has ppv vod settings with ppv privilege capped
                var ppvVodModel = new PPV_VOD_SettingsModel
                {
                    PIN = "1234",
                    PINRequired = true,
                    PPVCap = "150.00",
                    PPVPrivilege = SubscriberEnums.PPVPrivilegeEnum.Capped,
                    PPVResetDay = 15
                };

                // And the user has loaded the subscriber
                var currentSubscriber = new ShimCurrentSubscriber
                {
                    SubIdGet = () => subId,
                    NameGet = () => "subname",
                    LocationIdGet = () => "locid",
                    ServiceEnabledGet = () => true,
                    FoundInBillingGet = () => true,
                    AccountTypeGet = () => AccountTypeDto.Residential,
                    CbrGet = () => "4250010001",
                    EmailGet = () => "*****@*****.**",
                    PINGet = () => ppvVodModel.PIN,
                    PPVCapGet = () => ppvVodModel.PPVCap,
                    PPVResetDayGet = () => ppvVodModel.PPVResetDay.ToString(CultureInfo.InvariantCulture),
                    PPVPrivilegeGet = () => ppvVodModel.PPVPrivilege,
                    ProvisionedServicesListGet = () => new List<ServiceDto>()
                };

                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                ShimCurrentSubscriber.SessionInstanceGet = () => new ShimCurrentSubscriber();
                ShimCurrentSubscriber.GetInstance = () => currentSubscriber;

                // And the user edits ppv privilege from capped to unlimited
                var ppvVodModel4Update = new PPV_VOD_SettingsModel
                {
                    PIN = ppvVodModel.PIN,
                    PINRequired = ppvVodModel.PINRequired,
                    PPVCap = ppvVodModel.PPVCap,
                    PPVPrivilege = SubscriberEnums.PPVPrivilegeEnum.Unlimited,
                    PPVResetDay = ppvVodModel.PPVResetDay
                };

                // When updating the ppv vod settings
                var ppvVodController = DependencyResolver.Current.GetService<PPV_VODController>();

                ShimRosettianClient.AllInstances.UpdateSubscriberSubscriberDtoBooleanUserDto =
                    (myTestClient, mySubscriberDto, myOverriteService, myUserDto) => true;

                var actionResponse = ppvVodController.UpdatePPV_VOD(ppvVodModel4Update) as JsonResult;

                // Then the user receives a response
                Assert.IsNotNull(actionResponse, "UpdatePPV_VOD action method returned null");

                // And the response is successful
                var jss = new JavaScriptSerializer();
                var expectedResult = new
                {
                    status = "valid",
                    returnedPartial = "",
                }.ToJSON();
                Assert.AreEqual(jss.Serialize(expectedResult), jss.Serialize(actionResponse.Data.ToJSON()));
            }
        }
        public void Remarks_HappyPath()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

                //Build FakeDto
                var fakeUserDto = myContext.GetFakeUserDtoObject();

                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                var remarks = new List<PlantRemarkDto>();
                remarks.Add(new PlantRemarkDto
                {
                    ServiceOrderNumber = "#1234",
                    RemarkText = "Remarks"
                });

                ShimEnterpriseClient.AllInstances.GetPlantRemarksGetPlantRemarksRequestDtoHeaderArgs =
                    delegate { return remarks; };

                var accountsController = DependencyResolver.Current.GetService<AccountsController>();
                var result = accountsController.Remarks("usi","tn");
                Assert.IsInstanceOfType(result, typeof(PartialViewResult));
                Assert.IsInstanceOfType(result.Model, typeof (IEnumerable<string>));
                var remarkList = new List<string>(((IEnumerable<string>) result.Model));
                Assert.IsTrue(remarkList[0].Contains("#1234") && remarkList[0].Contains("Remarks"));
            }
        }
 private ShimHttpSessionState GetShimmedSession()
 {
     // Fake the session state for HttpContext
     var session = new ShimHttpSessionState
     {
         ItemGetString = s =>
         {
             if (s == "")
                 return null;
             return null;
         }
     };
     return session;
 }
        public void A_user_logs_in_when_Single_Concurrent_Login_Feature_is_enabled_but_error_occurs_when_saving_the_username_and_session_data()
        {
            using (ShimsContext.Create())
            {
                // Given a known user that is not logged in yet
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "doesNotMatter";

                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                LoginControllerForTests.ControllerContext = new ControllerContext()
                {
                    HttpContext = contextStub
                };

                #endregion LoginModel class, AttemptToLogUserIn method

                // And the Single Concurrent Login Feature is enabled

                // As there are unit tests for IsCheckEnabledActor, I am mocking the reference to IsCheckEnabled
                var wasIsCheckEnabledCalled = false;
                ShimSingleConcurrentLoginRules.AllInstances.IsCheckEnabled = (resultValue) =>
                {
                    wasIsCheckEnabledCalled = true;
                    return true;
                };

                // When that user is trying to log in

                #region LoginModel class, AttemptToLogUserIn method

                var wasASPPAuthenticateCalled = false;
                ShimUserManagement.AllInstances.AuthenticateStringString = (userNameValue, passwordValue, results) =>
                {
                    wasASPPAuthenticateCalled = true;
                    return UserManagement.AuthenticationResults.Success;
                };

                var wasASPPGetUserDetailsCalled = false;
                ShimUserManagement.AllInstances.GetUserDetailsString = (userNameValue, results) =>
                {
                    wasASPPGetUserDetailsCalled = true;
                    return new ASPP_Users();
                };

                var wasASPPGetUserGroupsCalled = false;
                ShimUserManagement.AllInstances.GetUserGroupsString = (userNameValue, results) =>
                {
                    wasASPPGetUserGroupsCalled = true;

                    // need to add at least one group - doing just enough to get beyond the guard in LoginModel.cs
                    var myASPP_Group = new ASPP_Groups
                    {
                        Group_ID = 1
                    };

                    return new List<ASPP_Groups>
                    {
                        myASPP_Group
                    };
                };

                // Then the data is not saved correctly

                // Note: the CreateSIMPLLoginTrackerRecord method should be called

                // When the CreateSIMPLLoginTrackerRecord method is called,
                // the SIMPLLoginTrackers.Add line will throw an exception because
                // it cannot find SIMPLEntities connection string in the config;
                // this is fine for our purposes as it throws as exception.

                // And the data is not added to the cache

                // Note: the AddSIMPLLoginTrackerRecordToCache method should not be called
                var wasAddSIMPLLoginTrackerRecordToCacheCalled = false;
                ShimSIMPLSessionEntitiesCache.AddSIMPLLoginTrackerRecordToCacheStringSIMPLLoginTracker = (userNameValue, myLoginTrackerValue) =>
                {
                    wasAddSIMPLLoginTrackerRecordToCacheCalled = true;
                    return true;
                };

                // And the user is not logged in

                #region back in the LoginViewModel class, AttemptToLogUserIn method

                var session = new ShimHttpSessionState { SessionIDGet = () => "doesNotMatter"};
                var context = new ShimHttpContext();
                var applicationShim = new ShimHttpApplicationState();
                context.ApplicationGet = () => applicationShim;
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // Note: the CurrentUser.SetInstance method should not be called
                var wasCurrentUserSetInstanceStringCalled = false;
                var currentUserSetInstanceCount = 0;
                ShimCurrentUser.SetInstanceString = (uniqueId) =>
                {
                    wasCurrentUserSetInstanceStringCalled = true;
                    currentUserSetInstanceCount++;
                };

                // Note: the CurrentUser.SessionInstance method should not be called
                var wasCurrentUserSessionInstanceGetCalled = false;
                ShimCurrentUser.SessionInstanceGet = () =>
                {
                    wasCurrentUserSessionInstanceGetCalled = true;
                    return new ShimCurrentUser();
                };

                // Note: the SyncWithOrImportDataFromASPP method should not be called
                var wasLoginModelSyncWithOrImportDataFromASPPCalled = false;
                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingServiceValue, userNameSentToLoginModelValue) =>
                {
                    wasLoginModelSyncWithOrImportDataFromASPPCalled = true;
                };

                // Note: the CurrentUser.Clear method should not be called
                var wasCurrentUserClearCalled = false;
                ShimCurrentUser.Clear = () =>
                {
                    wasCurrentUserClearCalled = true;
                };

                // Note: the UserEvents.InitializeSession method should not be called
                var wasUserEventsInitializeSessionCalled = false;
                ShimUserEvents.AllInstances.InitializeSessionStringString = (userEvents, uniqueIdValue, userHostAddressValue) =>
                {
                    wasUserEventsInitializeSessionCalled = true;
                };

                // Note: the FormsAuthentication.SetAuthCookie method should not be called
                var wasFormsAuthenticationSetAuthCookieCalled = false;
                ShimFormsAuthentication.SetAuthCookieStringBoolean = (userNameValue, createPersistentCookieValue) =>
                {
                    wasFormsAuthenticationSetAuthCookieCalled = true;
                };

                ShimErrorLoggingService.AllInstances.LogErrorException = (method, myException) =>
                {
                    // Not returning anything, just redirecting the call
                };

                #endregion back in the LoginViewModel class, AttemptToLogUserIn method

                var result = LoginControllerForTests.UserLogin(userName, password, returnUrl);
                Assert.IsNotNull(result, "LoginController returned null");
                Assert.IsTrue(result is ViewResult, "LoginController didn't return a ViewResult");

                var resultViewResult = result as ViewResult;
                Assert.IsNotNull(resultViewResult.Model, "resultViewResult.Model is null");
                Assert.IsTrue(resultViewResult.Model is LoginViewModel, "resultViewResult.Model is not LoginViewModel");

                var resultLoginViewModel = resultViewResult.Model as LoginViewModel;
                Assert.AreEqual("Unable to save the Login Record, please contact support (Single Concurrent Login Enabled)", resultLoginViewModel.Message, "resultLoginViewModel.Message did not have the expected value");

                Assert.IsTrue(wasASPPAuthenticateCalled, "wasASPPAuthenticateCalled is false");
                Assert.IsTrue(wasASPPGetUserDetailsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasASPPGetUserGroupsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasIsCheckEnabledCalled, "wasIsCheckEnabledCalled is false");

                // Not able to check if the CreateSIMPLLoginTrackerRecord method was called because
                // we are not using a Shim for that (as we are calling the live method)

                // These are negative checks to make sure that the other code was not called
                Assert.IsFalse(wasAddSIMPLLoginTrackerRecordToCacheCalled, "wasAddSIMPLLoginTrackerRecordToCacheCalled is true");
                Assert.IsFalse(wasCurrentUserSetInstanceStringCalled, "wasCurrentUserSetInstanceStringCalled is true");
                Assert.AreEqual(0, currentUserSetInstanceCount, "currentUserSetInstanceCount did not match expected value");
                Assert.IsFalse(wasCurrentUserSessionInstanceGetCalled, "wasCurrentUserSessionInstanceGetCalled is true");
                Assert.IsFalse(wasCurrentUserClearCalled, "wasCurrentUserClearCalled is true");
                Assert.IsFalse(wasLoginModelSyncWithOrImportDataFromASPPCalled, "wasLoginModelSyncWithOrImportDataFromASPPCalled is true");
                Assert.IsFalse(wasUserEventsInitializeSessionCalled, "wasUserEventsInitializeSessionCalled is true");
                Assert.IsFalse(wasFormsAuthenticationSetAuthCookieCalled, "wasFormsAuthenticationSetAuthCookieCalled is true");
            }
        }
        public void PageLoad_Called_PropertiesSet()
        {
            // Arrange
            SetupSessionFakes();
            ShimAuthenticationTicket.getTicket         = () => typeof(AuthenticationTicket).CreateInstance();
            ShimECNSession.AllInstances.RefreshSession = (x) => { };
            ShimECNSession.AllInstances.ClearSession   = (x) => { };

            SetDefaultMembers();

            ShimMessageTriggers.AllInstances.MasterGet = triggers =>
            {
                var master = new ecn.communicator.MasterPages.Communicator();
                return(master);
            };

            ShimUserControl.AllInstances.SessionGet = control =>
            {
                var session = new ShimHttpSessionState();
                return((HttpSessionState)session);
            };

            ShimMasterPageEx.AllInstances.HelpTitleSetString   = (_, __) => { };
            ShimMasterPageEx.AllInstances.HeadingSetString     = (_, __) => { };
            ShimMasterPageEx.AllInstances.HelpContentSetString = (_, __) => { };

            var noopRadioLst = new RadioButtonList();

            noopRadioLst.Items.Add(SelectedValueNo);
            noopRadioLst.SelectedIndex = 0;
            _messageTriggersPrivateObject.SetField("NOOP_RadioList", BindingFlags.Instance | BindingFlags.NonPublic, noopRadioLst);

            ShimlayoutExplorer.AllInstances.enableEditMode   = explorer => { };
            ShimlayoutExplorer.AllInstances.enableSelectMode = explorer => { };
            _messageTriggersPrivateObject.SetField("layoutExplorer", new layoutExplorer());
            _messageTriggersPrivateObject.SetField("val_NOOP_EmailFrom", new RequiredFieldValidator());
            _messageTriggersPrivateObject.SetField("imgbtnNOOP", new ImageButton());
            _messageTriggersPrivateObject.SetField("val_NOOP_ReplyTo", new RequiredFieldValidator());
            _messageTriggersPrivateObject.SetField("val_NOOP_EmailFromName", new RequiredFieldValidator());
            _messageTriggersPrivateObject.SetField("val_NOOP_Period", new RequiredFieldValidator());
            _messageTriggersPrivateObject.SetField("val_NOOP_txtHours", new RequiredFieldValidator());
            _messageTriggersPrivateObject.SetField("val_NOOP_txtMinutes", new RequiredFieldValidator());
            _messageTriggersPrivateObject.SetField("rangeval_NOOP_Period", new RangeValidator());
            _messageTriggersPrivateObject.SetField("rangeval_NOOP_txtHours", new RangeValidator());
            _messageTriggersPrivateObject.SetField("rangeval_NOOP_txtMinutes", new RangeValidator());
            _messageTriggersPrivateObject.SetField("rvfCampaingItemNameNO", new RequiredFieldValidator());

            ShimMessageTriggers.AllInstances.BindList = triggers => { };

            ShimLinkAlias.GetLinkAliasDRInt32Int32User = (i, i1, arg3) =>
            {
                var table = new DataTable();
                table.Columns.Add("Alias");
                table.Columns.Add("Link");
                return(table);
            };

            // Act
            _messageTriggersPrivateObject.Invoke("Page_Load", new object[] { null, null });

            // Assert
            var nopRadioList = _messageTriggersPrivateObject.GetField("NOOP_RadioList") as RadioButtonList;
            var userId       = _messageTriggersPrivateObject.GetField("UserId");
            var customerId   = _messageTriggersPrivateObject.GetField("CustomerId");

            nopRadioList.ShouldSatisfyAllConditions(
                () => nopRadioList.ShouldNotBeNull(),
                () => nopRadioList.SelectedValue.ShouldBe(SelectedValueNo),
                () => userId.ShouldBe(UserId),
                () => customerId.ShouldBe(CustomerId)
                );
        }
        public void SyncPlantData_HappyPath()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                 //Expected Result
                var expectedResult = new
                {
                    status = "valid",
                    message = "Success: DPI plant data will be updated in the next 10 minutes."
                };

                var fakeCurrentSubscriber = new ShimCurrentSubscriber
                {
                   LocationIdGet = () => "0089451",
                   DpiRegionGet = ()=>"CT"
                };

                ShimCurrentSubscriber.SessionInstanceGet = () => fakeCurrentSubscriber;

                // Call FacilitiesController SyncPlantData
                ShimEnterpriseClient.AllInstances.SyncPlantDataStringHeaderArgs = delegate { return true; };

                //Act
                var actualResult = FacilitiesControllerForTests.SyncPlantData() as JsonResult;

                // Test Validation
                Assert.IsNotNull(actualResult, "JsonResult returned is null");
                Assert.IsNotNull(actualResult.Data, "JsonResult Data returned is null");
                Assert.AreEqual(expectedResult.ToString(), actualResult.Data.ToString());
            }
        }
        public void Index_When_SubscriberID_Is_WhiteSpace_And_No_Previous_Customer_Is_Loaded_Should_Be_Redirected_To_Search_Page()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                string subscriberID = " ";
                string deviceID = string.Empty;

                // Fake the session state for HttpContext
                // http://blog.christopheargento.net/2013/02/02/testing-untestable-code-thanks-to-ms-fakes/
                var session = new ShimHttpSessionState();
                session.ItemGetString = (key) => { if (key == "Subscriber") return null; return null; };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // Fake the CurrentSubscriber.IsLoad call
                ShimCurrentSubscriber.AllInstances.IsLoadedGet = (myResult) => false;

                // 1st Act
                var result = SubscriberControllerForTests.Index(subscriberID, deviceID);

                // 1st Assert
                Assert.IsNotNull(result, "SubscriberController Index returned null");
                Assert.IsTrue(result is RedirectToRouteResult, "Not a RedirectToRouteResult");

                // 2nd Act
                var resultRedirectToRouteResult = (RedirectToRouteResult)result;

                // 2nd Assert
                Assert.IsNotNull(resultRedirectToRouteResult, "Cast to RedirectToRouteResult is null");
                Assert.AreEqual(2, resultRedirectToRouteResult.RouteValues.Count);
                Assert.AreEqual("Search", resultRedirectToRouteResult.RouteValues["action"], "actionResult.RouteValues[\"action\"]");
                Assert.AreEqual("Search", resultRedirectToRouteResult.RouteValues["controller"], "actionResult.RouteValues[\"controller\"]");
            }
        }
        private void SetUpShims(ServiceDto aServiceDto)
        {
            // Fake the session state for HttpContext
            var session = new ShimHttpSessionState();
            session.ItemGetString = (key) => { if (key == "Subscriber") return null; return null; };

            // Fake the HttpContext
            var context = new ShimHttpContext();
            ShimHttpContext.CurrentGet = () => context;

            // When the Fake HttpContext is called, provide the fake session state
            ShimHttpContext.AllInstances.SessionGet = (o) => session;

            //This is where the fake data is inserted
            ShimCurrentSubscriber.AllInstances.ProvisionedServicesListGet = (myTest) => new List<ServiceDto>
            {
                aServiceDto
            };
        }
        public void SwapIpVideoDevice_SwapOutVAPForAnotherVAP()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                const string selectedRoomConst = "testroom";
                var myContext = new SIMPLTestContext();
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                ShimCurrentUser.AllInstances.RolesGet = x =>
                {
                    return new List<int>();
                };
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimResidentialGatewayController.AllInstances.ValidateDeviceEquipmentDto = (controller, dto) =>
                {
                    return new RozResponseDto { Code = "200", Message = String.Empty };
                };

                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                ShimHttpContext.AllInstances.SessionGet = o => session;

                // VAP device to test
                EquipmentDto VAPDevice1 = new EquipmentDto();
                VAPDevice1.Type.Category = EquipmentCategoryDto.VideoAccessPoint;
                CustomFieldDto cf = new CustomFieldDto();
                cf.Label = "ROOM_LOCATION";
                VAPDevice1.CustomFields.Add(cf);

                // Another VAP device to test
                EquipmentDto VAPDevice2 = new EquipmentDto();
                VAPDevice2.Type.Category = EquipmentCategoryDto.VideoAccessPoint;
                VAPDevice2.CustomFields.Add(cf);

                // Shim Equipment Search
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto = (client, dto, arg3) =>
                {
                    List<EquipmentDto> lst = new List<EquipmentDto>();
                    lst.Add(VAPDevice1);
                    lst.Add(VAPDevice2);
                    return lst;
                };

                ShimRosettianClient.AllInstances.ReturnToHeadendListOfStringUserDto = (client, list, arg3) =>
                {
                    return true;
                };

                // current location
                const string currentLocationId = "LOCIDWITHANYVALUE";

                // set location Id
                ShimCurrentSubscriber.AllInstances.LocationIdGet = o => currentLocationId;

                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // Test for s
                string selectedRoomValue = "testroom";

                ShimRosettianClient.AllInstances.UpdateEquipmentEquipmentDtoUserDto = (client, dto, arg3) =>
                {
                    return true;
                };

                ShimRosettianClient.AllInstances.PerformEquipmentOperationListOfEquipmentOperationDtoUserDto = (client, dtos, arg3) =>
                {
                    return true;
                };

                // Try to replace VAP device with another VAP device

                string result =
                    residentialController.SwapIpVideoDevices(VAPDevice1, VAPDevice2, selectedRoomValue).ToJSON();
                XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(
                    Encoding.UTF8.GetBytes(result), new XmlDictionaryReaderQuotas());
                XElement root = XElement.Load(jsonReader);
                int code = Convert.ToInt32(root.XPathSelectElement(@"//code").Value);
                string status = root.XPathSelectElement(@"//status").Value.ToString();
                string selectedRoomReturned = root.XPathSelectElement(@"//sRoom").Value.ToString();
                string errorString = root.XPathSelectElement(@"//errorMessage").Value.ToString();

                if ((code == 200 || code == 202) && status == "valid")
                {
                    Assert.IsTrue(true);
                }
                else if ((code == 200 || code == 202) && status == "error")
                {
                    Assert.Inconclusive("Device untestable as validation failed.");
                }
                else if (code == 400 && errorString.Contains("Error swapping old video device"))
                {
                    Assert.Inconclusive("Device untestable because endpoint failed.");
                }
                else
                {
                    Assert.Fail("Swap of two VAP devices failed.");
                }
                Assert.AreEqual(selectedRoomConst, selectedRoomReturned, "Selected room changed.");
            }
        }