public static Service AsEntity(this ServiceDto serviceDto)
        {
            if (serviceDto == null)
            {
                return(null);
            }

            return(new Service
            {
                ID = serviceDto.Id,
                Name = serviceDto.Name,
                Description = serviceDto.Description,
                MinimumOrderQuantity = serviceDto.MinimumOrderQuantity,
                PriceEXCL = serviceDto.PriceEXCL,
                PriceINCL = serviceDto.PriceINCL,
                PriceMustChange = serviceDto.PriceMustChange,
                PriceExpiryDate = serviceDto.PriceExpiryDate,
                HasExpiryDate = serviceDto.HasExpiryDate,
                ExpiryDate = serviceDto.ExpiryDate,
                Supplier = serviceDto.Supplier.AsEntity(),
                Created = serviceDto.Created,
                CreatedBy = serviceDto.CreatedBy.AsEntity(),
                Modified = serviceDto.Modified,
                ModifiedBy = serviceDto.ModifiedBy.AsEntity(),
                IsActive = serviceDto.IsActive,
                IsDeleted = serviceDto.IsDeleted
            });
        }
示例#2
0
        static ServiceDto mapToService(ServiceRow pServiceRow, RoutingPlanDto pDefaultRoutingPlan, PayphoneSurchargeRow pPayphoneSurchargeRow, ICollection <AccessNumberListRow> pAccessNumberListRows, RatingInfoDto pDefaultRatingInfo)
        {
            if (pServiceRow == null)
            {
                return(null);
            }

            var _service = new ServiceDto
            {
                ServiceId            = pServiceRow.Service_id,
                Name                 = pServiceRow.Name,
                Status               = ((Status)pServiceRow.Status),
                ServiceType          = pServiceRow.ServiceType,
                RetailType           = pServiceRow.RetailType,
                IsShared             = pServiceRow.IsShared,
                RatingType           = pServiceRow.RatingType,
                PinLength            = pServiceRow.Pin_length,
                DefaultRatingInfo    = pDefaultRatingInfo,
                DefaultRoutingPlan   = pDefaultRoutingPlan,
                AccessNumbers        = mapToAccessNumbers(pAccessNumberListRows),
                PayphoneSurcharge    = RetailAccountManager.MapToPayphoneSurcharge(pPayphoneSurchargeRow),
                SweepScheduleId      = pServiceRow.Sweep_schedule_id,
                SweepFee             = pServiceRow.Sweep_fee,
                SweepRule            = pServiceRow.Sweep_rule,
                BalancePromptType    = pServiceRow.BalancePromptType,
                BalancePromptPerUnit = pServiceRow.Balance_prompt_per_unit,
                VirtualSwitchId      = pServiceRow.Virtual_switch_id
            };

            return(_service);
        }
        public ActionResult SaveService(ServiceAbbreviatedModel service)
        {
            IServiceDto newService;

            if (!ModelState.IsValid)             //validate model
            {
                TempData["MessageType"] = WebMessageType.Failure;
                TempData["Message"]     = "Failed to save changes to service";
            }

            try             //update state
            {
                newService = AbbreviatedEntityUpdate.UpdateService(service, _portfolioService.GetService(service.Id));
                //preserve service design documentation
                _portfolioService.ModifyService(UserId, newService, EntityModification.Update);
            }
            catch (Exception exception)
            {
                TempData["MessageType"] = WebMessageType.Failure;
                TempData["Message"]     = $"Failed to save changes to service, error: {exception.Message}";
                newService = new ServiceDto();
                return(View("ShowServices", newService));
            }

            TempData["MessageType"] = WebMessageType.Success;
            TempData["Message"]     = "Successfully saved service";

            return(View("ShowServices", newService));
        }
示例#4
0
        internal static void AddService(Rbr_Db pDb, ServiceDto pService, int[] pSelectedBaseRouteIds)
        {
            //TODO: NEW DAL - VirtualSwitch
            pService.VirtualSwitchId = AppConstants.DefaultVirtualSwitchId;

            if (pService.RetailType == RetailType.PhoneCard)
            {
                if (pService.PayphoneSurcharge != null)
                {
                    pService.PayphoneSurcharge.PayphoneSurchargeId = RetailAccountManager.AddPayphoneSurcharge(pDb, pService.PayphoneSurcharge);
                }
            }
            else
            {
                pService.PayphoneSurcharge = null;
            }

            ServiceRow _serviceRow = mapToServiceRow(pService);

            Add(pDb, _serviceRow);
            pService.ServiceId = _serviceRow.Service_id;

            //Create Default WholesaleRoute
            int _defaultWholesaleRouteId;

            CustomerRouteManager.AddDefault(pDb, pService, out _defaultWholesaleRouteId);
            pService.DefaultRoute.RatedRouteId = _defaultWholesaleRouteId;

            CustomerRouteManager.Add(pDb, pService.ServiceId, pSelectedBaseRouteIds);
        }
        private async Task DoLongPollingRefresh(string appId, string cluster, string dataCenter, CancellationToken cancellationToken)
        {
            var        random         = new Random();
            ServiceDto lastServiceDto = null;

            while (!cancellationToken.IsCancellationRequested)
            {
                var    sleepTime = 50; //default 50 ms
                string url       = null;
                try
                {
                    if (lastServiceDto == null)
                    {
                        var configServices = await _serviceLocator.GetConfigServices().ConfigureAwait(false);

                        lastServiceDto = configServices[random.Next(configServices.Count)];
                    }

                    url = AssembleLongPollRefreshUrl(lastServiceDto.HomepageUrl, appId, cluster, dataCenter);

                    Logger().Debug($"Long polling from {url}");

                    var response = await _httpUtil.DoGetAsync <IList <ApolloConfigNotification> >(url, 600000).ConfigureAwait(false);

                    Logger().Debug($"Long polling response: {response.StatusCode}, url: {url}");
                    if (response.StatusCode == HttpStatusCode.OK && response.Body != null)
                    {
                        UpdateNotifications(response.Body);
                        UpdateRemoteNotifications(response.Body);
                        Notify(lastServiceDto, response.Body);
                        _longPollSuccessSchedulePolicyInMs.Success();
                    }
                    else
                    {
                        sleepTime = _longPollSuccessSchedulePolicyInMs.Fail();
                    }

                    //try to load balance
                    if (response.StatusCode == HttpStatusCode.NotModified && random.NextDouble() >= 0.5)
                    {
                        lastServiceDto = null;
                    }

                    _longPollFailSchedulePolicyInSecond.Success();
                }
                catch (Exception ex)
                {
                    lastServiceDto = null;

                    var sleepTimeInSecond = _longPollFailSchedulePolicyInSecond.Fail();
                    Logger().Warn($"Long polling failed, will retry in {sleepTimeInSecond} seconds. appId: {appId}, cluster: {cluster}, namespace: {string.Join(ConfigConsts.ClusterNamespaceSeparator, _longPollNamespaces.Keys)}, long polling url: {url}, reason: {ex.GetDetailMessage()}");

                    sleepTime = sleepTimeInSecond * 1000;
                }
                finally
                {
                    await Task.Delay(sleepTime, cancellationToken).ConfigureAwait(false);
                }
            }
        }
示例#6
0
        public ServiceDto UpdateService(ServiceDto serviceDto)
        {
            using (var dbContext = new OmContext())
            {
                try
                {
                    var service = dbContext.Services.FirstOrDefault(s => s.ServiceId == serviceDto.ServiceId);
                    if (service != null)
                    {
                        service.Title = serviceDto.Title;
                        service.Price = serviceDto.Price;
                        dbContext.SaveChanges();
                        return(new ServiceDto()
                        {
                            ServiceId = service.ServiceId,
                            Title = service.Title,
                            Price = service.Price,
                            WorkCategoryId = service.WorkCategoryId
                        });
                    }

                    return(null);
                }
                catch (Exception ex)
                {
                    return(null);
                }
            }
        }
示例#7
0
        public static void Update(ServiceDto pService)
        {
            using (Rbr_Db _db = new Rbr_Db()) {
                using (Transaction _tx = new Transaction(_db, pService)) {
                    ServiceRow _originalServiceRow = ServiceManager.Get(_db, pService.ServiceId);
                    ServiceManager.UpdateService(_db, pService);

                    //TODO: NEW DAL - !!! check the logic
                    if (pService.IsShared && pService.DefaultRoutingPlanId != _originalServiceRow.Default_routing_plan_id)
                    {
                        //NOTE: RoutingPlan changed - set same RoutingPlan for Customers using this Shared Service,
                        //BUT ONLY for those Customers that did NOT overwrote the RoutingPlan
                        CustomerAcctRow[] _customerAcctRows = _db.CustomerAcctCollection.GetByService_id(pService.ServiceId);
                        foreach (CustomerAcctRow _customerAcctRow in _customerAcctRows)
                        {
                            if (_customerAcctRow.Routing_plan_id == _originalServiceRow.Default_routing_plan_id)
                            {
                                _customerAcctRow.Routing_plan_id = pService.DefaultRoutingPlanId;
                                CustomerAcctManager.UpdateAcct(_db, _customerAcctRow);
                            }
                        }
                    }
                    _tx.Commit();
                }
            }
        }
        public void Should_Get()
        {
            IConfiguration    config            = InitConfiguration();
            ServiceController serviceController = new ServiceController(config);

            ServiceDto service = new ServiceDto
            {
                Id      = Guid.Empty,
                Name    = "ServiceNameTestGet",
                Version = "ServiceVersion",
                ApiKey  = "apiKeyTest"
            };

            var farfetchMessage = serviceController.Insert(service);

            Assert.NotNull(farfetchMessage);
            Assert.AreEqual(typeof(FarfetchMessage <ServiceDto>), farfetchMessage.GetType());
            Assert.NotNull(farfetchMessage.Result);
            Assert.AreEqual(service.Name, farfetchMessage.Result.Name);
            Assert.AreEqual(service.Version, farfetchMessage.Result.Version);
            Assert.AreEqual(service.ApiKey, farfetchMessage.Result.ApiKey);

            var farfetchMessage2 = serviceController.Get(farfetchMessage.Result.Id);

            Assert.NotNull(farfetchMessage2);
            Assert.AreEqual(typeof(FarfetchMessage <ServiceDto>), farfetchMessage2.GetType());
            Assert.NotNull(farfetchMessage2.Result);
            Assert.AreEqual(farfetchMessage.Result.Id, farfetchMessage2.Result.Id);
            Assert.AreEqual(service.Name, farfetchMessage2.Result.Name);
            Assert.AreEqual(service.Version, farfetchMessage2.Result.Version);
            Assert.AreEqual(service.ApiKey, farfetchMessage2.Result.ApiKey);
        }
 public IActionResult Edit(ServiceDto serviceDto)
 {
     if (ModelState.IsValid)
     {
         try
         {
             _serviceService.UpdateService(serviceDto);
         }
         catch (DbUpdateConcurrencyException)
         {
             if (!ServiceExists(serviceDto.Id))
             {
                 return(NotFound());
             }
             else
             {
                 throw;
             }
         }
         return(RedirectToAction(nameof(Index)));
     }
     return(View(new ServiceViewModel(_context, _entrepriseService)
     {
         Entreprise = serviceDto.Entreprise,
         Id = serviceDto.Id,
         Name = serviceDto.Name
     }));
 }
        /// <summary>
        /// Gets the vmdir service status.
        /// </summary>
        /// <returns>The infrastructure nodes.</returns>
        /// <param name="serverDto">Server dto.</param>
        private ServiceDto GetVmDirServiceStatus(ServerDto serverDto)
        {
            var dto = new ServiceDto
            {
                HostName      = serverDto.Server,
                ServiceName   = Constants.DirectoryServiceName,
                Description   = Constants.DirectoryServiceDesc,
                LastHeartbeat = System.DateTime.UtcNow
            };

            try
            {
                var message = string.Format("Method: GetVmDirServiceStatus - VmDirGetDCInfos API call for Server: {0} complete", serverDto.Server);
                _logger.Log(message, LogLevel.Info);

                var entries = vmdirClient.Client.VmDirGetDCInfos(serverDto.Server, serverDto.UserName, serverDto.Password);
                dto.Alive = true;

                message = string.Format("Method: GetVmDirServiceStatus -  VmDirGetDCInfos API call for Server: {0} complete", serverDto.Server);
                _logger.Log(message, LogLevel.Info);
            }
            catch (Exception exc)
            {
                dto.Alive = false;
            }
            return(dto);
        }
示例#11
0
        public ReservationModelDto GetAvailabilityReservationsNewReservation()
        {
            ReservationDto reservation         = new ReservationDto();
            string         responseBodyService = this._clientService.GetResponse(localhostApi + "api/ServiceApi/" + reservation.IdService, "", validJwt).GetAwaiter().GetResult();
            ServiceDto     service             = JsonConvert.DeserializeObject <ServiceDto>(responseBodyService);

            reservation.IdServiceNavigation = service;

            string      responseBodyEmployee = this._clientService.GetResponse(localhostApi + "api/EmployeeApi/" + reservation.IdEmployee, "", validJwt).GetAwaiter().GetResult();
            EmployeeDto employee             = JsonConvert.DeserializeObject <EmployeeDto>(responseBodyEmployee);

            reservation.IdEmployeeNavigation = employee;

            string             responseBodyEmployeesList = this._clientService.GetResponse(localhostApi + "api/EmployeeApi", "", validJwt).GetAwaiter().GetResult();
            List <EmployeeDto> employeesList             = JsonConvert.DeserializeObject <List <EmployeeDto> >(responseBodyEmployeesList);

            reservation.IdUser     = 29;
            reservation.IdService  = 85;
            reservation.IdEmployee = 23;
            reservation.Date       = DateTime.Today;
            ReservationModelDto reseservationModel = new ReservationModelDto();

            reseservationModel.Reservation = reservation;
            string responseBodyReservationAvailabilityList    = this._clientService.GetResponse(localhostApi + "api/ReservationApi/Availability?idEmployee=" + reservation.IdEmployee + "&idService=" + reservation.IdService + "&idUser="******"&datetime=" + reservation.Date.ToString(), "", validJwt).GetAwaiter().GetResult();
            List <ReservationDto> reservationAvailabilityList = JsonConvert.DeserializeObject <List <ReservationDto> >(responseBodyReservationAvailabilityList);

            reseservationModel.Reservations = reservationAvailabilityList;
            return(reseservationModel);
        }
        public IActionResult CreateToken([FromBody] ServiceDto serviceDto)
        {
            if (serviceDto == null)
            {
                throw new ArgumentNullException(nameof(serviceDto));
            }
            if (string.IsNullOrEmpty(serviceDto.Name))
            {
                throw new NullReferenceException("Service Name hasn't been defined");
            }
            if (string.IsNullOrEmpty(serviceDto.Version))
            {
                throw new NullReferenceException("Service Password hasn't been defined");
            }

            IActionResult response = Unauthorized();
            // 1 year
            var claims = new[]
            {
                new Claim(ClaimTypes.Role, "Service"),
                new Claim("ServiceName", serviceDto.Name),
                new Claim("ServiceVersion", serviceDto.Version)
            };
            string tokenString = BuildToken(DateTime.Now.AddMonths(12), claims);

            response = Ok(new { token = tokenString });

            return(response);
        }
        private bool ServicesExists(int id)
        {
            string     responseBody = this._clientService.GetResponse(this._configuration["AppSettings:ApiRest"] + "api/ServiceApi/" + id).GetAwaiter().GetResult();
            ServiceDto service      = JsonConvert.DeserializeObject <ServiceDto>(responseBody);

            return(service != null);
        }
示例#14
0
        public void AddService(ServiceDto dto)
        {
            if (dto == null)
            {
                return;
            }
            if (Services == null)
            {
                Services = new List <ServiceEntity>();
            }
            var service = new ServiceEntity();

            service.ServiceAddress        = dto.ServiceAddress;
            service.MethodName            = dto.MethodName;
            service.OperationContractName = dto.OperationContractName;
            if (dto.Parameters != null)
            {
                service.ServiceParameters = new List <ServiceParameterEntity>();
                foreach (var parameter in dto.Parameters)
                {
                    service.ServiceParameters.Add(new ServiceParameterEntity()
                    {
                        TypeName = parameter.TypeName,
                        Name     = parameter.Name,
                        Value    = parameter.Value
                    });
                }
            }
            Services.Add(service);
        }
示例#15
0
        /// <inheritdoc />
        public FarfetchMessage <ServiceDto> Insert(ServiceDto serviceDto)
        {
            if (_applicationService == null)
            {
                throw new NullReferenceException("Application Service hasn't been defined");
            }

            Service service = Mapper.Map <ServiceDto, Service>(serviceDto);

            if (service == null)
            {
                throw new AutoMapperMappingException("Error mapping types");
            }
            _applicationService.Insert(service);

            service = _applicationService.GetByExpression(x => x.Name == serviceDto.Name && x.Version == serviceDto.Version && x.ApiKey == serviceDto.ApiKey);

            serviceDto = Mapper.Map <Service, ServiceDto>(service);
            if (service == null)
            {
                throw new AutoMapperMappingException("Error mapping types");
            }
            return(new FarfetchMessage <ServiceDto>
            {
                Result = serviceDto,
            });
        }
示例#16
0
        public ServiceDto AddService(ServiceDto serviceDto)
        {
            using (var dbContext = new OmContext())
            {
                try
                {
                    // var serviceCategory = dbContext.Services.Where(w => w.Title == serviceDto.Title);
                    // if (!serviceCategory.Any())
                    {
                        Service newService = new Service
                        {
                            WorkCategoryId = serviceDto.WorkCategoryId,
                            Title          = serviceDto.Title,
                            Price          = serviceDto.Price
                        };

                        dbContext.Services.Add(newService);
                        dbContext.SaveChanges();
                        return(new ServiceDto()
                        {
                            Title = newService.Title,
                            Price = newService.Price,
                            WorkCategoryId = newService.WorkCategoryId,
                            ServiceId = newService.ServiceId
                        });
                    }

                    return(null);
                }
                catch (Exception ex)
                {
                    return(null);
                }
            }
        }
示例#17
0
        /// <inheritdoc />
        public FarfetchMessage <ServiceDto> Get(Guid id)
        {
            if (_applicationService == null)
            {
                throw new NullReferenceException("Application Service hasn't been defined");
            }
            Service service = _applicationService.GetById(id);

            if (service == null)
            {
                return(new FarfetchMessage <ServiceDto>
                {
                    Result = null
                });
            }
            ServiceDto serviceDto = Mapper.Map <Models.Service, ServiceDto>(service);

            if (serviceDto == null)
            {
                throw new AutoMapperMappingException("Error mapping types");
            }

            return(new FarfetchMessage <ServiceDto>
            {
                Result = serviceDto
            });
        }
示例#18
0
        public async Task <ActionResult <ServiceDto> > GetService(Guid id)
        {
            ServiceDto servicedto = new ServiceDto();

            try
            {
                servicedto = await serviceRepository.GetService(id);

                return(Ok(new ResponseDto <ServiceDto>()
                {
                    statusCode = "200", data = servicedto
                }));
            }
            catch (Exception e)
            {
                if (e.Message == ErrorMessage.EntityDoesNotExist)
                {
                    return(BadRequest(servicedto));
                }

                //if request got to this point some error occured
                return(StatusCode(500, new ResponseDto <string>()
                {
                    statusCode = "500", message = "server error"
                }));
            }
        }
示例#19
0
        public async Task <ActionResult <ServiceDto> > UpdateService(ServiceDto servicedto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            try
            {
                var service = await serviceRepository.UpdateService(servicedto);

                var resp = new ResponseDto <ServiceDto>()
                {
                    data = service, message = "updated suceessfully", statusCode = "200"
                };
                return(Ok(resp));
            }
            catch (Exception e)
            {
                if (e.Message == ErrorMessage.EntityDoesNotExist)
                {
                    return(BadRequest((new ResponseDto <ServiceDto>()
                    {
                        message = ErrorMessage.EntityDoesNotExist
                    })));
                }

                //if you get to this point something unusual occurred
                return(StatusCode(500));
            }
        }
        public IResult Add(ServiceDto serviceDto)
        {
            var service = Mapper.Map <Entities.Concrete.Service>(serviceDto);

            //var context = new ValidationContext<Service>(service);
            //var validator = new ServiceValidator();
            //var result = validator.Validate(context);

            var errorList = ValidationTool.Validate(new ServiceValidator(), service);

            if (errorList.Any())
            {
                return(new ErrorResult(errorList));
            }

            //var result = BusinessRules.Run(
            //    new ErrorResult("Hata 1"),
            //    new ErrorResult("Hata 2"),
            //    new ErrorResult("Hata 3"),
            //    new SuccessResult(),
            //    new ErrorResult("Hata 4"),
            //    new SuccessResult());

            //if (!result.IsSuccess)
            //    return result;

            _serviceDal.Add(service);

            return(new SuccessResult());
        }
示例#21
0
        /// <summary>
        /// Gets the services.
        /// </summary>
        /// <returns>The services.</returns>
        /// <param name="status">Status.</param>
        public static List <ServiceDto> GetServices(string hostname, VMAFD_HEARTBEAT_STATUS status)
        {
            var services = new List <ServiceDto> ();

            if (status.info != null)
            {
                foreach (var info in status.info)
                {
                    var service = new ServiceDto()
                    {
                        HostName      = hostname,
                        ServiceName   = GetServiceName(info.pszServiceName),
                        Description   = GetServiceDescription(info.pszServiceName),
                        Port          = info.dwPort,
                        Alive         = info.bIsAlive == 1,
                        LastHeartbeat = DateTimeConverter.FromUnixToDateTime(info.dwLastHeartbeat)
                    };
                    services.Add(service);
                }
                var afdService = new ServiceDto()
                {
                    HostName      = hostname,
                    ServiceName   = Constants.AuthFrameworkServiceName,
                    Description   = Constants.AuthFrameworkServiceDesc,
                    Alive         = true,
                    LastHeartbeat = System.DateTime.UtcNow
                };
                services.Add(afdService);
            }
            return(services.OrderBy(x => x.ServiceName).ToList());
        }
示例#22
0
 public async Task <IActionResult> Save(ServiceDto model)
 {
     return(Ok(await Mediator.Send(new SaveServiceCommand()
     {
         Model = model
     })));
 }
示例#23
0
        private FormUrlEncodedContent EncodeContent(ServiceDto service)
        {
            var content = new List <KeyValuePair <string, string> >();

            if (service.ServiceId != 0)
            {
                content.Add(new KeyValuePair <string, string>("service_id", service.ServiceId.ToString()));
            }
            content.Add(new KeyValuePair <string, string>("service_name", service.ServiceName));
            content.Add(new KeyValuePair <string, string>("service_price", service.ServicePrice.ToString()));
            if (service.Active)
            {
                content.Add(new KeyValuePair <string, string>("active_service", service.Active.ToString()));
            }
            if (service.ServiceDiscount.ServiceDiscount > 0)
            {
                if (service.ServiceDiscount.ServiceDiscountId != 0)
                {
                    content.Add(new KeyValuePair <string, string>("service_discount_id", service.ServiceDiscount.ServiceDiscountId.ToString()));
                }
                content.Add(new KeyValuePair <string, string>("discount", service.ServiceDiscount.ServiceDiscount.ToString()));
                content.Add(new KeyValuePair <string, string>("start", service.ServiceDiscount.StartDate.ToString("yyyy-MM-dd")));
                content.Add(new KeyValuePair <string, string>("end", service.ServiceDiscount.EndDate.ToString("yyyy-MM-dd")));
                if (service.ServiceDiscount.Active)
                {
                    content.Add(new KeyValuePair <string, string>("active_discount", service.ServiceDiscount.Active.ToString()));
                }
            }
            return(new FormUrlEncodedContent(content));
        }
示例#24
0
        public HttpResponseMessage ProvisionService([FromBody] ServiceDto serviceDto)
        {
            try
            {
                Setup();

                _logger.WriteLogEntry(_tenantId.ToString(), new List <object> {
                    serviceDto
                }, string.Format(MethodBase.GetCurrentMethod().Name + " in " + _name), LogLevelType.Info);
                int orderId   = _iOrderService.RetrieveOrderIdByExtIdAndExtCompanyId(serviceDto.ExternalOrderId, serviceDto.ExternalCompanyId);
                int companyId = _iOrderService.RetrieveCompanyIdByExtCompanyId(serviceDto.ExternalCompanyId);
                int serviceId = _iOrderService.RetrieveServiceIdByExtOrderIdAndExtIdAndExtCompanyId(serviceDto.ExternalOrderId, serviceDto.ExternalServiceId, serviceDto.ExternalCompanyId);
                var task      = _iProvisioningEngineService.ProvisionService(orderId, serviceId, companyId, serviceDto.TestMode, serviceDto.SendResponse, serviceDto.ForceProvision, _user);
                Task.WaitAll(task);
                return(this.Request.CreateResponse(HttpStatusCode.OK, task.Result));
            }
            catch (Exception ex)
            {
                _logger.WriteLogEntry(_tenantId.ToString(), new List <object> {
                    ex.RetrieveEntityExceptionDataAsObjectList()
                },
                                      string.Format(MethodBase.GetCurrentMethod().Name + " in " + _name), LogLevelType.Error, ex.GetInnerMostException());
                throw ex.AddEntityValidationInfo();
            }
        }
示例#25
0
        public void ServiceDto_Extension_AsEntity_Null()
        {
            ServiceDto service = null;
            var        result  = service.AsEntity();

            Assert.IsNull(result);
            Assert.AreEqual(null, result);
        }
 /// <summary>
 /// Called right before the request is sent.
 /// </summary>
 protected override Task RequestReadyAsyncCore(HttpRequestMessage request, ServiceDto requestDto, CancellationToken cancellationToken)
 {
     if (m_authorizationHeader != null)
     {
         request.Headers.Authorization = m_authorizationHeader;
     }
     return(Task.FromResult <object>(null));
 }
示例#27
0
        public async Task <IActionResult> CreateService(ServiceDto serviceDto)
        {
            Console.WriteLine("Crate Service Method Invoked");
            var service = _mapper.Map <Service>(serviceDto);
            await _repo.UpdateData(service);

            return(Ok(serviceDto));
        }
示例#28
0
 /// <summary>
 /// Called right before the request is sent.
 /// </summary>
 protected override Task RequestReadyAsyncCore(HttpRequestMessage httpRequest, ServiceDto requestDto, CancellationToken cancellationToken)
 {
     if (!string.IsNullOrWhiteSpace(m_userAgent))
     {
         httpRequest.Headers.Add("User-Agent", m_userAgent);
     }
     return(Task.CompletedTask);
 }
 /// <summary>
 /// Called right before the request is sent.
 /// </summary>
 protected override Task RequestReadyAsyncCore(HttpRequestMessage request, ServiceDto requestDto, CancellationToken cancellationToken)
 {
     if (!string.IsNullOrWhiteSpace(m_userAgent))
     {
         request.Headers.Add("User-Agent", m_userAgent);
     }
     return(Task.FromResult <object>(null));
 }
 /// <summary>
 /// Called right before the request is sent.
 /// </summary>
 protected override Task RequestReadyAsyncCore(HttpRequestMessage httpRequest, ServiceDto requestDto, CancellationToken cancellationToken)
 {
     if (m_authorizationHeader != null)
     {
         httpRequest.Headers.Authorization = m_authorizationHeader;
     }
     return(Task.CompletedTask);
 }
 public ServiceDto GetServiceByID(int serviceID)
 {
     VeSinhNamHoa.Models.Service sv = database.Services.Where(x => serviceID.Equals(x.ID)).Select(x => x).FirstOrDefault();
     ServiceDto dtoService = null;
     if (this.Cookies == VeSinhNamHoa.Constant.Language.VIETNAMESE)
     {
         dtoService = new ServiceDto() { ID = sv.ID, Detail = sv.ViDetail, Disabled = sv.Disabled, Title = sv.ViTitle, Image = sv.Image };
     }
     else if (this.Cookies == VeSinhNamHoa.Constant.Language.ENGLISH)
     {
         dtoService = new ServiceDto() { ID = sv.ID, Detail = sv.EnDetail, Disabled = sv.Disabled, Title = sv.EnTitle, Image = sv.Image };
     }
     else if (this.Cookies == VeSinhNamHoa.Constant.Language.JAPANESE)
     {
         dtoService = new ServiceDto() { ID = sv.ID, Detail = sv.JaDetail, Disabled = sv.Disabled, Title = sv.JaTitle, Image = sv.Image };
     }
     return dtoService;
 }
示例#32
0
 public RentalListDto ListRentalForInvoice(string sessionKey, string invoiceID)
 {
     RentalListDto retVal = new RentalListDto();
      ServiceDto serviceDto = new ServiceDto { Id = 1, Text = "Telephone", Rate = 5.50M, Cap = 97M, Fee = 7M };
      retVal.Add(new RentalDto { Id = 1, Service = serviceDto, RentDate = DateTime.Now });
      return retVal;
 }
示例#33
0
        public void Remove_E911_Terms_of_Service_Block_Success()
        {
            using (ShimsContext.Create())
            {
                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => new SIMPLTestContext().GetFakeUserDtoObject();

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

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = delegate
                {
                    return new ShimHttpSessionState
                    {
                        ItemGetString = s => null
                    };
                };

                // Fake CurrentSubscriber
                var cfmtosService = new ServiceDto
                {
                    ClassName = "OVERRIDE",
                    Name = "CFM911",
                    Description = "CONFIRM 911"
                };
                var fakeProvisioningServiceList = new List<ServiceDto>
                {
                    cfmtosService,
                    new ServiceDto
                    {
                        ClassName = "VOICE",
                        Name = "CVOIP",
                        Description = "CONSUMER VOIP"
                    }
                };
                var fakeCurrentSubscriber = new ShimCurrentSubscriber
                {
                    SubIdGet = () => "test_subscriber",
                    VoiceProductTypeGet = () => SubscriberEnums.VoiceProductType.CVoip,
                    VoiceEnabledGet = () => true,
                    GeneralTermsOfServiceStatusGet = () => TOSStatus.None,
                    E911TermsOfServiceStatusGet = () => TOSStatus.None
                };
                ShimCurrentSubscriber.SessionInstanceGet = () => fakeCurrentSubscriber;
                ShimCurrentSubscriber.UpdateSubscriberDto = delegate
                {
                    fakeProvisioningServiceList.Remove(cfmtosService);
                };
                fakeCurrentSubscriber.ProvisionedServicesListGet = () => fakeProvisioningServiceList;

                // Fake RosettianClient
                ShimRosettianClient.AllInstances.UpdateSubscriberSubscriberDtoBooleanUserDto = delegate { return true; };

                // Fake ConfigurationManager
                ShimConfigurationManager.AppSettingsGet = () => new NameValueCollection
                {
                    { "RemoveE911TosBlockEnabled", "true" }
                };

                // Fake Permissions.UserHasGrant
                ShimPermissions.UserHasGrantGrant = delegate { return true; };

                var result = ServicesControllerForTests.RemoveTermsOfServiceBlock(TOSTypeDto.E911TOS);
                Assert.IsNotNull(result, "Partial view result returned is null.");
                Assert.IsTrue(result is PartialViewResult, "Result is of type PartialViewResult");

                var viewResult = result as PartialViewResult;
                Assert.IsNotNull(viewResult, "PartialViewResult returned is null.");
                Assert.IsNotNull(viewResult.Model, "PartialViewResult.Model is null.");

                var model = (ServiceStatusViewModel)viewResult.Model;
                Assert.IsFalse(model.VoiceServiceStatusTemplate.ShouldShowRemoveE911TermsOfServiceBlockButton);
                Assert.IsTrue(model.E911TermsOfServiceBlockRemoved);
            }
        }
示例#34
0
        public void AddServicesTest()
        {
            using (var client = new RosettianClient())
            {
                // initialize
                MyTestInitialize();

                // get test subscriber
                var testSubscriber = IntegrationTest.Data.Data.GetSIMPLSubscriber04CPE01();

                // create existing service list
                string existingServiceClassName = ServiceClassType.ProvisionedOntDataPort.GetStringValue();
                const string existingServiceName = "ENET";
                const string existingServiceDescription = "RJ-45 ETHERNET PORT";
                var existingService = new ServiceDto
                {
                    ClassName = existingServiceClassName,
                    Name = existingServiceName,
                    Description = existingServiceDescription
                };
                var existingServicesList = new List<ServiceDto> {existingService};

                // set current subscriber
                testSubscriber.Accounts.First().Services = existingServicesList.ToCollection();
                CurrentSubscriber.SetInstance(testSubscriber);

                // create service to add
                const string serviceToAddClassName = "DATA - FTTH SPEED";
                const string serviceToAddName = "F50M20M";
                const string serviceToAddDescription = "50M DOWN 20M UP";
                var serviceToAdd = new ServiceDto
                {
                    ClassName = serviceToAddClassName,
                    Name = serviceToAddName,
                    Description = serviceToAddDescription
                };
                var serviceToAddAsJSON = "[" + new JavaScriptSerializer().Serialize(serviceToAdd) + "]";

                // create expected service list (includes existing service and service to add)
                var expectedServicesListAfterAdd = new List<ServiceDto> {existingService, serviceToAdd};

                // create controller reference
                var servicesController = DependencyResolver.Current.GetService<ServicesController>();

                // ACT
                var actualJsonResult = servicesController.AddServices(serviceToAddAsJSON) as JsonResult;

                // ASSERT
                Assert.IsNotNull(actualJsonResult);
                Assert.IsInstanceOfType(actualJsonResult, typeof (JsonResult));

                // Verify the returned JSON
                dynamic actualJson = actualJsonResult.Data;
                var status = actualJson.status as string;
                Assert.IsNotNull(status);
                if (status == "error")
                {
                    var exceptionMessage = actualJson.errorMessage;

                    // Failure in action method -- report exception
                    Assert.Fail("Add Service test - unexpected JsonResult values, code = {0}\r\nmessage = {1}", status, exceptionMessage);
                }
                Assert.AreEqual("success", status, "Add Service test - unexpected status from update operation");

                // load updated subscriber
                var updatedSubscriber = client.LoadSubscriber(testSubscriber.ID, CurrentUser.AsUserDto());

                // verify the services list
                Assert.IsTrue(updatedSubscriber.Accounts.First().Services.SequenceEqual(expectedServicesListAfterAdd, new ServiceComparer()));
            }
        }
示例#35
0
        public void Remove_General_Terms_of_Service_Block_Success()
        {
            using (ShimsContext.Create())
            {
                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => new SIMPLTestContext().GetFakeUserDtoObject();

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

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = delegate
                {
                    return new ShimHttpSessionState
                    {
                        ItemGetString = s => null
                    };
                };

                // Fake CurrentSubscriber
                var cfmtosService = new ServiceDto
                {
                    ClassName = "OVERRIDE",
                    Name = "CFMTOS",
                    Description = "CONFIRM TERMS"
                };
                var fakeProvisioningServiceList = new List<ServiceDto>
                {
                    cfmtosService,
                    new ServiceDto
                    {
                        ClassName = "DATA - DSL SPEED",
                        Name = "D24M3M",
                        Description = "24MBPS / 3MBPS"
                    }
                };
                var fakeCurrentSubscriber = new ShimCurrentSubscriber
                {
                    SubIdGet = () => "test_subscriber",
                    DataProductTypeGet = () => SubscriberEnums.DataProductType.XDsl,
                    DataEnabledGet = () => true,
                    GeneralTermsOfServiceStatusGet = () => TOSStatus.None,
                    E911TermsOfServiceStatusGet = () => TOSStatus.None
                };
                ShimCurrentSubscriber.SessionInstanceGet = () => fakeCurrentSubscriber;
                ShimCurrentSubscriber.UpdateSubscriberDto = delegate
                {
                    fakeProvisioningServiceList.Remove(cfmtosService);
                };
                fakeCurrentSubscriber.ProvisionedServicesListGet = () => fakeProvisioningServiceList;

                // Fake RosettianClient
                ShimRosettianClient.AllInstances.UpdateSubscriberSubscriberDtoBooleanUserDto = delegate { return true; };

                var result = ServicesControllerForTests.RemoveTermsOfServiceBlock(TOSTypeDto.GeneralTOS);
                Assert.IsNotNull(result, "Partial view result returned is null.");
                Assert.IsTrue(result is PartialViewResult, "Result is of type PartialViewResult");

                var viewResult = result as PartialViewResult;
                Assert.IsNotNull(viewResult, "PartialViewResult returned is null.");
                Assert.IsNotNull(viewResult.Model, "PartialViewResult.Model is null.");

                var model = (ServiceStatusViewModel)viewResult.Model;
                Assert.IsFalse(model.ShouldShowRemoveGeneralTermsOfServiceBlockButton);
                Assert.IsTrue(model.GeneralTermsOfServiceBlockRemoved);
            }
        }
示例#36
0
        public void InitializeBlockedServicesMethod_OneBlocked_BlockedServicesListAsJSONIsNotEmpty()
        {
            // Arrange
            const string ExpectedServiceClassName = "Service ClassName";
            const string ExpectedServiceName = "Service Name";
            const string ExpectedServiceDescription = "Service Description";
            ServiceDto myBlockedService1 = new ServiceDto { ClassName = ExpectedServiceClassName, Description = ExpectedServiceDescription, Name = ExpectedServiceName };
            List<ServiceDto> blockedServices = new List<ServiceDto> { myBlockedService1 };
            string expectedJSON = string.Format("[{{\"ClassName\":\"{0}\",\"Name\":\"{1}\",\"Description\":\"{2}\"}}]", ExpectedServiceClassName, ExpectedServiceName, ExpectedServiceDescription);
            var myServicesController = DependencyResolver.Current.GetService<ServicesController>();
            const string ExpectedSubscriberIdDoesNotMatter = "doesNotMatter";
            const string ExpectedDeviceIdDoesNotMatter = "doesNotMatter";

            using (ShimsContext.Create())
            {
                ShimServices.AsCategorizedServiceDictionaryListOfServiceDto = (listOfBlockedServices) =>
                {
                    // not testing this particular Fake in this test, so no local boolean variable checking to see if this was called
                    Dictionary<string, string> serviceNameDictionary = new Dictionary<string, string>();
                    Dictionary<string, Dictionary<string, string>> categorizedDictionary = new Dictionary<string, Dictionary<string, string>>();
                    serviceNameDictionary.Add(ExpectedServiceClassName, ExpectedServiceDescription);
                    categorizedDictionary.Add(ExpectedServiceClassName, serviceNameDictionary);
                    return categorizedDictionary;
                };

                // Act
                var resultInitializeBlockedServices = myServicesController.InitializeBlockedServices(blockedServices, ExpectedSubscriberIdDoesNotMatter, ExpectedDeviceIdDoesNotMatter);

                // Assert
                Assert.IsNotNull(resultInitializeBlockedServices, "resultInitializeBlockedServices");
                var myResult = resultInitializeBlockedServices as PartialViewResult;
                Assert.IsNotNull(myResult, "myResult");
                var actualServicesModel = myResult.Model as ServicesModel;
                Assert.IsNotNull(actualServicesModel, "actualServicesModel is null");
                Assert.AreEqual(expectedJSON, actualServicesModel.BlockedServicesAsJSON, "actualServicesModel.BlockedServicesAsJSON");
            }
        }
示例#37
0
        public void InitializeBlockedServicesMethod_OneBlocked_BlockedServicesListIsNotEmpty()
        {
            // Arrange
            const string ExpectedServiceClassName = "Service ClassName";
            const string ExpectedServiceDescription = "Service Description";
            const string ExpectedServiceName = "Service Name";
            var myBlockedService1 = new ServiceDto { ClassName = ExpectedServiceClassName, Description = ExpectedServiceDescription, Name = ExpectedServiceName };
            var blockedServices = new List<ServiceDto> { myBlockedService1 };
            var myServicesController = DependencyResolver.Current.GetService<ServicesController>();
            const string ExpectedSubscriberIdDoesNotMatter = "doesNotMatter";
            const string ExpectedDeviceIdDoesNotMatter = "doesNotMatter";
            bool wasAsCategorizedServiceDictionaryCalled = false;

            using (ShimsContext.Create())
            {
                ShimServices.AsCategorizedServiceDictionaryListOfServiceDto = (listOfBlockedServices) =>
                    {
                        var serviceNameDictionary = new Dictionary<string, string>();
                        var categorizedDictionary = new Dictionary<string, Dictionary<string, string>>();
                        serviceNameDictionary.Add(ExpectedServiceClassName, ExpectedServiceDescription);
                        categorizedDictionary.Add(ExpectedServiceClassName, serviceNameDictionary);
                        wasAsCategorizedServiceDictionaryCalled = true;
                        return categorizedDictionary;
                    };

                // Act
                var resultInitializeBlockedServices = myServicesController.InitializeBlockedServices(blockedServices, ExpectedSubscriberIdDoesNotMatter, ExpectedDeviceIdDoesNotMatter);

                // Assert
                Assert.IsNotNull(resultInitializeBlockedServices, "resultInitializeBlockedServices");
                var myResult = resultInitializeBlockedServices as PartialViewResult;
                Assert.IsNotNull(myResult, "myResult");
                var actualServicesModel = myResult.Model as ServicesModel;
                Assert.IsNotNull(actualServicesModel, "actualServicesModel is null");
                Assert.IsTrue(wasAsCategorizedServiceDictionaryCalled, "wasAsCategorizedServiceDictionaryCalled");
                //Assert.IsNotNull(actualServicesModel.BlockedServicesList);
                //Assert.AreEqual(1, actualServicesModel.BlockedServicesList.Count, "BlockedServicesList.Count != 1");
            }
        }
示例#38
0
        public void AddServices_ValidateSuccessScenario()
        {
            using (ShimsContext.Create())
            {
                // current subId
                const string subId = "sub12345";

                // current locationId
                const string locId = "loc12345";

                // current service list
                var existingService = new ServiceDto
                {
                    ClassName = ServiceClassType.ProvisionedOntDataPort.GetStringValue(),
                    Name = "ENET",
                    Description = "RJ-45 ETHERNET PORT"
                };
                var existingServicesList = new List<ServiceDto> { existingService };

                // current subscriber with service list
                var currentSubscriber = new ShimCurrentSubscriber
                {
                    SubIdGet = () => subId,
                    LocationIdGet = () => locId,
                    ProvisionedServicesListGet = () => existingServicesList
                };

                // set values
                ShimCurrentSubscriber.GetInstance = () => currentSubscriber;
                ShimCurrentUser.AsUserDto = () => new UserDto();

                // service to be added
                var serviceToAdd = new ServiceDto
                {
                    ClassName = "DATA - FTTH SPEED",
                    Name = "F50M20M",
                    Description = "50M DOWN 20M UP"
                };
                var serviceToAddAsJson = "[" + new JavaScriptSerializer().Serialize(serviceToAdd) + "]";

                // expected service list (includes existing service and service to add)
                var expectedServicesListAfterAdd = new List<ServiceDto> { existingService, serviceToAdd };

                // expected SubscriberServiceModel after service add succeed
                var expectedSubscriberServiceModel = new SubscriberServicesModel
                {
                    SubscriberID = subId,
                    LocationID = locId,
                    ProvisionedServicesList = expectedServicesListAfterAdd
                };

                // set ROZ UpdateSubscriber succeed
                ShimRosettianClient.AllInstances.UpdateSubscriberSubscriberDtoBooleanUserDto =
                    (myTestClient, mySubscriberDto, overWriteServices, myUserDto) => true;

                // set CurrentSubscriber UpdateSubscriber succeed
                ShimCurrentSubscriber.UpdateSubscriberDto =
                    (mySubscriberDto) => { };

                // set MapToSubServicesModel
                ShimSubscriberExtension.MapToSubServicesModelCurrentSubscriber =
                    (myCurrentSubscriber) => expectedSubscriberServiceModel;

                // get service for ServicesController
                var servicesController = DependencyResolver.Current.GetService<ServicesController>();

                // call AddServices action method
                var actualJsonResult = servicesController.AddServices(serviceToAddAsJson) as JsonResult;

                // verify returned JsonResult is not null
                Assert.IsNotNull(actualJsonResult);

                // verify the result
                dynamic actualJson = actualJsonResult.Data;
                var status = actualJson.status as string;
                Assert.AreEqual("success", status, "AddServices returned Json result status does not match");
            }
        }
示例#39
0
        public void InitializeBlockedServicesMethod_OneBlocked_ValidateServicesActionResult()
        {
            // Arrange
            const string ExpectedServiceClassName = "Service ClassName";
            const string ExpectedServiceDescription = "Service Description";
            const string ExpectedServiceName = "Service Name";
            var myBlockedService1 = new ServiceDto { ClassName = ExpectedServiceClassName, Description = ExpectedServiceDescription, Name = ExpectedServiceName };
            var blockedServices = new List<ServiceDto> { myBlockedService1 };
            var myServicesController = DependencyResolver.Current.GetService<ServicesController>();
            const string ExpectedSubscriberIdDoesNotMatter = "doesNotMatter";
            const string ExpectedDeviceIdDoesNotMatter = "doesNotMatter";

            using (ShimsContext.Create())
            {
                ShimServices.AsCategorizedServiceDictionaryListOfServiceDto = (listOfBlockedServices) =>
                {
                    // not testing this particular Fake in this test, so no local boolean variable checking to see if this was called
                    var serviceNameDictionary = new Dictionary<string, string>();
                    var categorizedDictionary = new Dictionary<string, Dictionary<string, string>>();
                    serviceNameDictionary.Add(ExpectedServiceClassName, ExpectedServiceDescription);
                    categorizedDictionary.Add(ExpectedServiceClassName, serviceNameDictionary);
                    return categorizedDictionary;
                };

                // Act
                var resultInitializeBlockedServices = myServicesController.InitializeBlockedServices(blockedServices, ExpectedSubscriberIdDoesNotMatter, ExpectedDeviceIdDoesNotMatter);

                // Assert
                Assert.IsNotNull(resultInitializeBlockedServices, "resultInitializeBlockedServices");
                var myResult = resultInitializeBlockedServices as PartialViewResult;
                Assert.IsNotNull(myResult, "myResult");
                var actualServicesModel = myResult.Model as ServicesModel;
                Assert.IsNotNull(actualServicesModel, "actualServicesModel is null");
                Assert.IsTrue(actualServicesModel.ServicesActionResult.Success, "ServicesActionResult.Success is False");
                Assert.IsTrue(string.IsNullOrEmpty(actualServicesModel.ServicesActionResult.ErrorMessage), "ErrorMessage has a value");
                Assert.IsTrue(string.IsNullOrEmpty(actualServicesModel.ServicesActionResult.Result), "Result has a value");
            }
        }