/// <summary>
        /// Test initialize
        /// </summary>
        public AssertExamplesBase()
        {
            ILogger <PurchaseOrder> logger = LoggingFactory.UseSerilogToDebug <PurchaseOrder>();

            _purchaseOrder = new PurchaseOrderFactory().CreatePurchaseOrderInstance(logger);
        }
示例#2
0
        /// <summary>
        /// 写单个线圈
        /// </summary>
        /// <param name="requestByteData"></param>
        /// <param name="recevideByteData"></param>
        /// <returns></returns>
        private static AnalyzeRecivedDataReponse AnalyzeRecivedDataByFunNum05(
            DataAnalyzeMode dataAnalyzeMode,
            List <byte> requestByteData,
            List <byte> recevideByteData)
        {
            AnalyzeRecivedDataReponse reponse = new AnalyzeRecivedDataReponse();

            try
            {
                int deviceAddress        = recevideByteData[0];
                int startRegisterAddress = requestByteData[2] * 256 + requestByteData[3];

                //接受侦recevideByteData中寄存器值的数据之前的字节数:
                //deviceAddress、funNum、ecevideByteData[2]个占1个字节
                int byteCountBeforeDataRegion = 4;
                int countOfRegisterToRead     = 1;

                //避免数据返回不完整引发下标溢出
                if (recevideByteData.Count > (byteCountBeforeDataRegion + countOfRegisterToRead * 2) &&
                    requestByteData.Count > (byteCountBeforeDataRegion + countOfRegisterToRead * 2))
                {
                    if (requestByteData[byteCountBeforeDataRegion] == recevideByteData[byteCountBeforeDataRegion] &&
                        requestByteData[byteCountBeforeDataRegion + 1] == recevideByteData[byteCountBeforeDataRegion + 1])
                    {
                        reponse.ModbusReponseSuccess = true;
                    }
                    else
                    {
                        reponse.ModbusReponseSuccess = false;
                    }

                    Register register = new Register();
                    register.DeviceAddress   = deviceAddress;
                    register.RegisterAddress = startRegisterAddress;

                    byte fistByteInRecevide   = recevideByteData[byteCountBeforeDataRegion];
                    byte secondByteInRecevide = recevideByteData[byteCountBeforeDataRegion + 1];

                    byte fistByteInRequest   = requestByteData[byteCountBeforeDataRegion];
                    byte secondByteInRequest = requestByteData[byteCountBeforeDataRegion + 1];

                    if (0xFF == fistByteInRecevide && 0x00 == secondByteInRecevide)
                    {
                        register.RegisterValue = 1; //开:FF00
                    }
                    else if (0x00 == fistByteInRecevide && 0x00 == secondByteInRecevide)
                    {
                        register.RegisterValue = 0; //关:0000
                    }

                    reponse.Registers.Add(register);
                }
            }
            catch (Exception)
            {
                reponse.AnalyzeRecivedDataSuccess = false;
                LoggingFactory.GetLogger().WriteDebugLogger("解析Modbus接收帧时发生异常!");
                return(reponse);
            }

            return(reponse);
        }
示例#3
0
        public void Delete(Guid id)
        {
            Customer customer = _customerRepository.Get(id);

            // Remove Customer from stripe service
            if (!string.IsNullOrEmpty(customer.PaymentCustomerId))
            {
                try
                {
                    if (StripeFactory.GetStripeService().GetCustomer(customer.PaymentCustomerId) != null)
                    {
                        StripeFactory.GetStripeService().DeleteCustomer(customer.PaymentCustomerId);
                    }
                    LoggingFactory.GetLogger().Log("Customer not found", EventLogSeverity.Fatal);
                }catch (Exception ex)
                {
                    LoggingFactory.GetLogger().LogError(ex);
                }
            }

            _unitOfWork.Begin();

            // Delete relations between users and roles
            foreach (var role in customer.Roles)
            {
                role.RoleUsers.Clear();
                _roleRepository.Update(role);
            }

            // Delete Notes
            if (customer.Notes != null)
            {
                foreach (var note in customer.Notes.ToList())
                {
                    _noteRepository.Delete(note);
                }
            }


            // Delete API records
            if (customer.ApiTokens != null)
            {
                foreach (var apiToken in customer.ApiTokens.ToList())
                {
                    _apitokensRepository.Delete(apiToken);
                }
            }

            // Delete IPS records
            if (customer.IPSEntries != null)
            {
                foreach (var ipsEntry in customer.IPSEntries.ToList())
                {
                    _ipsEntryRepository.Delete(ipsEntry);
                }
            }


            //delete all reference list items
            if (customer.ReferenceListItems != null)
            {
                foreach (var item in customer.ReferenceListItems.ToList())
                {
                    _referenceListItemRepository.Delete(item);
                }
            }

            // delete all users
            if (customer.Users != null)
            {
                foreach (var user in customer.Users.ToList())
                {
                    _userRepository.Delete(user);
                }
            }


            //// delete all payments
            //foreach (var payment in _customerPaymentRepository.Query().Where(x => x.CustomerId == id).ToList())
            //{
            //    _customerPaymentRepository.Delete(payment);
            //}

            //// delete all payment refunds
            //foreach (var paymentRefund in _customerPaymentRefundRepository.Query().Where(x => x.CustomerId == id).ToList())
            //{
            //    _customerPaymentRefundRepository.Delete(paymentRefund);
            //}

            _customerRepository.Delete(customer);

            _unitOfWork.End();
        }
示例#4
0
        public PostWebServiceResponse PostAsyncWithMultipleAttachments <T>(T item, List <string> fileNames, List <byte[]> buffers)
        {
            PostWebServiceResponse response = new PostWebServiceResponse();

            try
            {
                //  HttpClient client = new HttpClient();

                //Defining the unique boundary
                string         boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
                HttpWebRequest req      = (HttpWebRequest)WebRequest.Create(RequestUrl);
                req.AllowAutoRedirect = false;

                if (Headers.Count > 0)
                {
                    BuildHeaders(req);
                }
                req.Method      = MethodType;//Post
                req.ContentType = "multipart/form-data; boundary=" + boundary;
                Stream stream = req.GetRequestStream();

                //Body need to be extended for each part of the request
                // Add header for JSON part


                // Body += "Content-Disposition: form-data; name='entity'\r\n";//entity is relative to the object we r sending
                //Body += "Content-Type: application/json\r\n\r\n";//defining the content type for this part of request
                // Add document object data in JSON
                //Body += JsonConvert.SerializeObject(item);
                Body += "\r\n--" + boundary + "\r\n";


                // Body += "Content-Disposition: form-data; name='record'\r\n";
                //  Body += "Content-Type: application/json\r\n\r\n";
                var settings = new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Include, DateTimeZoneHandling = DateTimeZoneHandling.Utc, DateFormatString = "yyyy/MM/dd"
                };
                Body += string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", "record");

                string jsonString = JsonConvert.SerializeObject(item, settings);
                Body += jsonString;

                //Finalized the json part

                byte[] data = System.Text.Encoding.UTF8.GetBytes(Body);
                stream.Write(data, 0, data.Length);

                string additionalFile     = "";
                byte[] additionalFileData = null;
                for (int i = 0; i < buffers.Count; i++)
                {
                    additionalFile  = "";
                    additionalFile += "\r\n--" + boundary + "\r\n";
                    additionalFile += "Content-Disposition: form-data; name=\"picture" + i.ToString() + "\"; filename=\"" + fileNames[i] + "\"\r\n";
                    additionalFile += "Content-Type: application/octet-stream\r\n\r\n";

                    additionalFileData = System.Text.Encoding.UTF8.GetBytes(additionalFile);
                    stream.Write(additionalFileData, 0, additionalFileData.Length);
                    stream.Write(buffers[i], 0, buffers[i].Length);
                }



                //Now we need  to write the headers to the request
                // Add header data to request


                // Add binary file to request


                // Finalizing by adding the footer of the request or what we call trailer
                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                stream.Write(trailer, 0, trailer.Length);
                stream.Close();

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); // *** [2] ***
                stream = resp.GetResponseStream();
                // resp.Close();
                // Do the post and get the response.

                //var r = req.GetResponse();
                //Stream s = r.GetResponseStream();
                StreamReader reader = new StreamReader(stream, true);
                string       x      = reader.ReadToEnd();

                if (Resolver != null)
                {
                    settings.ContractResolver = Resolver;
                }


                response = JsonConvert.DeserializeObject <PostWebServiceResponse>(x, settings);
                return(response);
            }
            catch (Exception ex)
            {
                string exception = BuildLogMessage() + " : " + ex.Message;
                LoggingFactory.GetLogger().Log(exception);
                response.statusId = "0";
                return(response);
            }
        }
示例#5
0
        public static AnalyzeRecivedDataReponse AnalyzeRecivedData(DataAnalyzeMode dataAnalyzeMode, List <byte> requestByteData, List <byte> recevideByteData)
        {
            AnalyzeRecivedDataReponse reponse = new AnalyzeRecivedDataReponse();

            //TODO:暂时注释,调试完后取消注释
            if (!RecivedDataCorrespondToRequesData(requestByteData, recevideByteData))
            {
                reponse.ModbusReponseSuccess = false;
                return(reponse);
            }

            if (recevideByteData.Count < 2 || requestByteData.Count < 2)
            {
                //无法获取设备地址、功能码
                string message = "请求帧或接受帧中不存在设备地址或功能码。";
                LoggingFactory.GetLogger().WriteDebugLogger(message);

                reponse.ModbusReponseSuccess = false;
                return(reponse);
            }

            if (requestByteData[0] != recevideByteData[0] ||
                requestByteData[1] != recevideByteData[1])
            {
                string message = "请求帧与接受帧的设备地址或功能码不对应," +
                                 "请求接受的数据不对应。";
                LoggingFactory.GetLogger().WriteDebugLogger(message);

                reponse.AnalyzeRecivedDataSuccess = false;
                return(reponse);
            }

            int funNum = recevideByteData[1];

            if (1 == funNum)
            {
                reponse = AnalyzeRecivedDataByFunNum01(dataAnalyzeMode, requestByteData, recevideByteData);
            }

            if (3 == funNum)
            {
                reponse = AnalyzeRecivedDataByFunNum03(dataAnalyzeMode, requestByteData, recevideByteData);
            }

            if (5 == funNum)
            {
                reponse = AnalyzeRecivedDataByFunNum05(dataAnalyzeMode, requestByteData, recevideByteData);
            }

            if (6 == funNum)
            {
                reponse = AnalyzeRecivedDataByFunNum06(dataAnalyzeMode, requestByteData, recevideByteData);
            }

            if (15 == funNum)
            {
                reponse = AnalyzeRecivedDataByFunNum015(dataAnalyzeMode, requestByteData, recevideByteData);
            }

            if (16 == funNum)
            {
                reponse = AnalyzeRecivedDataByFunNum16(dataAnalyzeMode, requestByteData, recevideByteData);
            }

            return(reponse);
        }
示例#6
0
        public string GetService(IAccessMappingRepository accessMappingRepository, IServiceRepository serviceRepository, IBusesRepository busesRepository, string providerId, string consumerId, string serviceId)
        {
            //var ourBus = AppSettings.Get<string>("Bus");
            //string[] stringSeparators = new string[] { "$$" };
            //string[] result;
            var map      = accessMappingRepository.GetAccessMappings().ToList();
            var busP     = "";
            var provider = "";

            //if (providerId.Contains("$$"))
            //{
            string[] stringSeparators = new string[] { "$$" };
            string[] result;
            result   = providerId.Split(stringSeparators, StringSplitOptions.None);
            busP     = result[0];
            provider = result[1];
            //}

            //if (String.IsNullOrEmpty(busP))
            // busP = ourBus;
            //if (String.IsNullOrEmpty(provider))
            //provider = providerId;

            //if (!providerId.Contains("$$") && !consumerId.Contains("$$"))
            //{
            //var allAvilableServices = map.Where(x => x.ConsumerCode == consumerId && x.ConsumerBusCode == ourBus && x.ProviderCode == providerId && x.ProviderBusCode == ourBus && x.ServiceCode == serviceId);

            var allAvilableServices = map.Where(x => x.ConsumerCode == consumerId && x.ProviderCode == provider && x.ProviderBusCode == busP && x.ServiceCode == serviceId && x.IsActive);
            var serviceMethodsFromAvilableServices = allAvilableServices.Select(service => service.MethodCode).ToArray();

            if (allAvilableServices.Any())
            {
                //var temp = serviceRepository.GetServices();
                //foreach (var ser in temp)
                //{
                //    if (ser.ParticipantCode.Contains("$$"))
                //    {
                //        string[] stringSeparators = new string[] { "$$" };
                //        string[] result;
                //        result = ser.ParticipantCode.Split(stringSeparators, StringSplitOptions.None);
                //        ser.ParticipantCode = result[1];
                //    }
                //}
                //var temp1 = temp.FirstOrDefault(x => x.ParticipantCode == providerId && x.Code == serviceId);

                var originalWsdl = serviceRepository.GetServices().FirstOrDefault(x => x.ParticipantCode == providerId && x.Code == serviceId).Wsdl;

                if (serviceMethodsFromAvilableServices.Any())
                {
                    return(RecreateWsdl(originalWsdl, serviceMethodsFromAvilableServices));
                }
            }
            //}
            //else if (providerId.Contains("$$"))
            //{
            //    result = providerId.Split(stringSeparators, StringSplitOptions.None);
            //    var busC = result[0];
            //    var busURL = busesRepository.GetBuses().Where(x => x.Code == busC).Select(x => x.Url);
            //    // Make call to external Bus with parametars GetService(ourBus$$consumerId, providerId, ServY)
            //    // get list of strings from the external call
            //    return "";
            //}
            //else if (providerId.Contains("$$") && consumerId.Contains("$$"))
            //{//call from external BUS, to be tested
            //    result = providerId.Split(stringSeparators, StringSplitOptions.None);
            //    var provId = result[1];
            //    result = consumerId.Split(stringSeparators, StringSplitOptions.None);
            //    var consId = result[1];
            //    var consBus = result[0];
            //    var allAvilableServices = map.Where(x => x.ConsumerCode == consId && x.ConsumerBusCode == consBus && x.ProviderCode == provId && x.ProviderBusCode == ourBus && x.ServiceCode == serviceId);
            //    var serviceMethodsFromAvilableServices = allAvilableServices.Select(service => service.MethodCode).ToArray();

            //    if (allAvilableServices.Any())
            //    {
            //        var originalWsdl = serviceRepository.GetServices().FirstOrDefault(x => x.ParticipantCode == provId && x.Code == serviceId).Wsdl;

            //        if (serviceMethodsFromAvilableServices.Any())
            //        {
            //            return RecreateWsdl(originalWsdl, serviceMethodsFromAvilableServices);
            //        }
            //    }
            //}
            var nameLogerError = "GetService_ " + DateTime.Now;

            using (var logger = LoggingFactory.GetNLogger(nameLogerError))
            {
                logger.Info("There is no access maping for that provider and consumer");
            }
            throw new FaultException("There is no access maping for that provider and consumer");
        }
 protected Context_logging_factory()
 {
     defaultMockLogger = new Mock <ILogger>();
     loggingFactory    = new LoggingFactory();
 }
示例#8
0
 public EntityDtos <TEntityDto> FindAll()
 {
     LoggingFactory.LogInfo("Invoked FindAll for " + typeof(TEntity).Name);
     return(ExecuteCommand(FindAllCommand));
 }
示例#9
0
 public EntityDtos <TEntityDto> FindByQuery(Query query)
 {
     LoggingFactory.LogInfo("Invoked FindAll for " + typeof(TEntity).Name);
     return(ExecuteCommand(locator => FindByQueryCommand(locator, query)));
 }
示例#10
0
 public CountryDto GetByCountryName(string countryName)
 {
     LoggingFactory.LogInfo("Invoked Country for User");
     return(ExecuteCommand(locator => GetByCountrynameCommand(locator, countryName.Trim())));
 }
        private static ILogger CreateLogger(string[] loggers)
        {
            var loggingFactory = new LoggingFactory();

            return(loggingFactory.Create(loggers));
        }
示例#12
0
 public DtoResponse Delete(long id)
 {
     LoggingFactory.LogInfo("Invoked Delete for " + typeof(TEntity).Name + " : Id : " + id);
     return(ExecuteCommand(locator => DeleteCommand(locator, id)));
 }
示例#13
0
 public TEntityDto Create(TEntityDto entityDto, string userName)
 {
     LoggingFactory.LogInfo("Invoked Create for " + typeof(TEntity).Name);
     return(ExecuteCommand(locator => CreateNewCommand(locator, entityDto, userName)));
 }
示例#14
0
 public CodeCampControl()
 {
     _logger = LoggingFactory.Create(GetType());
 }
示例#15
0
 protected override void OnStart(string[] args)
 {
     LoggingFactory.BuildLogger();
     BuildBus();
 }
示例#16
0
 public EntityDtos <TEntityDto> FindBy(Query query, int pageIndex, int recordsPerPage)
 {
     LoggingFactory.LogInfo("Invoked FindAll for " + typeof(TEntity).Name);
     return(ExecuteCommand(locator => FindByCommand(locator, query, pageIndex, recordsPerPage)));
 }
示例#17
0
        public List <SelectListItem> GetServices(IAccessMappingRepository accessMappingRepository, IBusesRepository busesRepository, IServiceRepository servicesRepository, string providerId, string consumerId)
        {
            //var ourBus = AppSettings.Get<string>("Bus");
            //string[] stringSeparators = new string[] { "$$" };
            //string[] result;

            var nameLogerError = "Vlezni parametri na GetServices" + "_ " + DateTime.Now;

            using (var logger = LoggingFactory.GetNLogger(nameLogerError))
            {
                logger.Info("provider: " + providerId + "; consumer: " + consumerId);
            }

            var output = new List <string>();
            var busP   = "";

            //if (providerId.Contains("$$"))
            //{
            string[] stringSeparators = new string[] { "$$" };
            string[] result;
            result     = providerId.Split(stringSeparators, StringSplitOptions.None);
            busP       = result[0];
            providerId = result[1];
            //}
            //if (String.IsNullOrEmpty(busP))
            //busP = ourBus;

            using (var logger = LoggingFactory.GetNLogger(nameLogerError))
            {
                logger.Info("busP: " + busP + "; providerId: " + providerId);
            }

            output = accessMappingRepository.GetAccessMappings().Where(x => x.ConsumerCode == consumerId && x.ProviderCode == providerId && x.ProviderBusCode == busP && x.IsActive).Select(x => x.ServiceCode).Distinct().ToList();

            using (var logger = LoggingFactory.GetNLogger(nameLogerError))
            {
                logger.Info("output: " + output.Count);
            }

            var allservices = servicesRepository.GetServices();
            var newOutput   = new List <SelectListItem>();

            foreach (var service in allservices)
            {
                if (output.Contains(service.Code))
                {
                    var item = new SelectListItem();

                    item.Value = service.Code;
                    item.Text  = service.Name;
                    newOutput.Add(item);
                }
            }

            //if(!providerId.Contains("$$") && !consumerId.Contains("$$"))
            //{
            //    output = accessMappingRepository.GetAccessMappings().Where(x => x.ConsumerCode == consumerId && x.ProviderCode == providerId && x.ProviderBusCode == ourBus).Select(x => x.ServiceCode).Distinct().ToList();
            //}
            //else if(providerId.Contains("$$"))
            //{
            //result = providerId.Split(stringSeparators, StringSplitOptions.None);
            //var busC = result[0];
            //var busURL = busesRepository.GetBuses().Where(x => x.Code == busC).Select(x => x.Url);
            // Make call to external Bus with parametars GetServices(ourBus$$consumerId, providerId)
            // get list of strings from the external call
            //}
            //else if(providerId.Contains("$$") && consumerId.Contains("$$"))
            //{//call from external BUS, to be tested
            //    result = providerId.Split(stringSeparators, StringSplitOptions.None);
            //    var provId = result[1];
            //    result = consumerId.Split(stringSeparators, StringSplitOptions.None);
            //    var consId = result[1];
            //    var consBus = result[0];
            //    output = accessMappingRepository.GetAccessMappings().Where(x => x.ConsumerCode == consId && x.ConsumerBusCode == consBus && x.ProviderCode == provId && x.ProviderBusCode == ourBus).Select(x => x.ServiceCode).Distinct().ToList();
            //}
            return(newOutput);
        }
示例#18
0
 protected void Log(string message, string strackTrace)
 {
     LoggingFactory.GetLogger().Log(message);
     LoggingFactory.GetLogger().Log(strackTrace);
 }
示例#19
0
        public List <ProviderCSDTO> GetProviders(IAccessMappingRepository accessMappingRepository, IParticipantRepository participantRepository, IBusesRepository busesRepository, string consumerId)
        {
            var nameLogerError1 = "GetProviders" + "_ " + DateTime.Now;

            using (var logger = LoggingFactory.GetNLogger(nameLogerError1))
            {
                logger.Info("dosol vo get providers za " + consumerId);
            }
            List <ProviderCSDTO> output;

            try
            {
                var accessMappings = accessMappingRepository.GetAccessMappings().Where(x => x.ConsumerCode == consumerId);

                var participants      = participantRepository.GetParticipants();
                var accessMappingList = new List <AccessMapping>();
                foreach (var am in accessMappings)
                {
                    var amm = new AccessMapping()
                    {
                        ProviderCode    = am.ProviderCode,
                        ProviderBusCode = am.ProviderBusCode,
                        ConsumerCode    = am.ConsumerCode
                    };

                    amm.ProviderCode = amm.ProviderBusCode + "$$" + amm.ProviderCode;
                    accessMappingList.Add(amm);
                }
                var accessMappet = accessMappingList.Select(s => s.ProviderCode).Distinct();

                var joinedAccessMappingsAndParticipants = accessMappet.Join(participants, am => am,
                                                                            p => p.Code, (am, p) => new ProviderCSDTO {
                    Code = am, PublicKey = p.PublicKey, Name = p.Name
                }).ToList();

                output = joinedAccessMappingsAndParticipants.ToList();

                //foreach (var k in accessMapBusExt)
                //{
                //    var busURL = k.Url;
                //    //the call is made with MIM1$$consumerId
                //    // get lists from other busses and add them to output
                //}
                // }
                //else
                //{//call from external BUS, to be tested
                //    string[] stringSeparators = new string[] { "$$" };
                //    string[] result;
                //    result = consumerId.Split(stringSeparators, StringSplitOptions.None);
                //    var busC = result[0];
                //    var consumer = result[1];
                //    var accessMappings = accessMappingRepository.GetAccessMappings().Where(x => x.ConsumerCode == consumer);
                //    var accessMapBus = accessMappings.Where(x => x.ProviderBusCode == ourBus && x.ConsumerBusCode == busC);
                //    var accessMappet = accessMapBus.Select(s => s.ProviderCode).Distinct();
                //    var participants = participantRepository.GetParticipants();

                //    var joinedAccessMappingsAndParticipants = accessMappet.Join(participants, am => am,
                //        p => p.Code, (am, p) => new ProviderCSDTO { Code = ourBus + "$$" + am, PublicKey = p.PublicKey }).ToList();
                //    output = joinedAccessMappingsAndParticipants.ToList();
                //}
            }
            catch (Exception ex)
            {
                var nameLogerError = "GetProviders" + "_ " + DateTime.Now;
                using (var logger = LoggingFactory.GetNLogger(nameLogerError))
                {
                    logger.Info("consumerId = " + consumerId);
                }
                throw new FaultException(ex.Message);
            }
            return(output);
        }
示例#20
0
        /// <summary>
        /// Process the incoming Stripe Event
        /// </summary>
        public void ProcessEvent(string customerId, StripeEvent stripeEvent)
        {
            try
            {
                LoggingFactory.GetLogger().Log($"Start ProcessEvent(EventType={stripeEvent.Type})", EventLogSeverity.Debug);

                EmailTemplateCode emailTemplateCode = EmailTemplateCode.None;

                Customer customer = _customerRepository.Query().FirstOrDefault(p => p.PaymentCustomerId == customerId);
                if (customer == null)
                {
                    LoggingFactory.GetLogger().Log("Message.NotFindCustomerByPaymentCustomerId", EventLogSeverity.Error);
                    throw new Exception("Messages.NotFindCustomerByPaymentCustomerId" + customerId);
                }

                StripeSubscription subscription;

                switch (stripeEvent.Type)
                {
                case "charge.succeeded":
                    var charge = Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString());

                    var payment = new CustomerPayment(customer.Id, charge.BalanceTransactionId, false, Convert.ToDecimal(charge.Amount / 100.0), charge.Created);

                    _customerPaymentRepository.Add(payment);

                    LoggingFactory.GetLogger().Log("Customer payment added", EventLogSeverity.Information);

                    emailTemplateCode = EmailTemplateCode.ChargeSuccessfull;

                    break;

                case "charge.refunded":
                    var refundedCharge = Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString());

                    var stripeEventObject = JObject.Parse(stripeEvent.Data.Object.ToString());
                    var refundsData       = stripeEventObject.SelectToken("refunds.data");
                    StripeApplicationFeeRefund[] refunds = Mapper <StripeApplicationFeeRefund[]> .MapFromJson(refundsData.ToString());

                    StripeApplicationFeeRefund lastRefund = refunds[refunds.Length - 1];
                    var amountRefundedInDollars           = (decimal)(lastRefund.Amount / 100.0);

                    var refundPayment = new CustomerPaymentRefund(customer.Id, refundedCharge.BalanceTransactionId,
                                                                  refundedCharge.Id,
                                                                  amountRefundedInDollars, lastRefund.Created);

                    _customerPaymentRefundRepository.Add(refundPayment);

                    // TODO update refund field in payment record
                    //refundedCharge.Refunded
                    LoggingFactory.GetLogger().Log("Customer payment refunding", EventLogSeverity.Information);

                    emailTemplateCode = EmailTemplateCode.ChargeRefunded;

                    break;

                case "charge.failed":

                    // Update the DB

                    emailTemplateCode = EmailTemplateCode.ChargeFailed;
                    LoggingFactory.GetLogger().Log("Customer payment failed", EventLogSeverity.Information);

                    //TODO:

                    break;

                case "customer.subscription.deleted":

                    // look up user details from the Customer
                    subscription = Mapper <StripeSubscription> .MapFromJson(stripeEvent.ToString());

                    customer.PlanCanceledOn = subscription.CanceledAt ?? DateTime.Now;
                    _customerRepository.Update(customer);

                    //TODO:
                    //- Create log entry for Admins
                    emailTemplateCode = EmailTemplateCode.CustomerSubscriptionDeleted;
                    LoggingFactory.GetLogger().Log("Customer subscription deleted", EventLogSeverity.Information);

                    break;

                case "customer.subscription.updated":

                    // look up user details from the Customer
                    subscription = Mapper <StripeSubscription> .MapFromJson(stripeEvent.ToString());

                    customer.PlanUpdatedOn = subscription.Start ?? DateTime.Now;
                    _customerRepository.Update(customer);

                    //TODO:
                    //- Create log entry for Admins
                    emailTemplateCode = EmailTemplateCode.CustomerSubscriptionUpdated;
                    LoggingFactory.GetLogger().Log("Customer subsciption updated", EventLogSeverity.Information);

                    break;

                case "charge.created":
                    //TODO
                    return;
                }


                if (emailTemplateCode != EmailTemplateCode.None)
                {
                    EmailTemplate emailTemplate =
                        _emailTemplatesRepository.GetTemplateByName(
                            Common.Helpers.Utilities.ToDescriptionString(emailTemplateCode));

                    emailTemplate = EmailTemplateFactory.ParseTemplate(emailTemplate, customer);
                    MailMessage mailMessage = MailMessageMapper.ConvertToMailMessage(emailTemplate);
                    bool        result      = EmailServiceFactory.GetEmailService().SendMail(mailMessage);

                    if (result)
                    {
                        _unitOfWork.Commit();
                        LoggingFactory.GetLogger().Log("Payment information saved", EventLogSeverity.Information);
                    }
                    else
                    {
                        LoggingFactory.GetLogger().Log("There is an error creating Customer payment", EventLogSeverity.Fatal);
                        throw new Exception("There is an error creating Customer payment");
                    }
                }

                LoggingFactory.GetLogger().Log("End ProcessEvent({0})", EventLogSeverity.Debug);
            }
            catch (Exception ex)
            {
                LoggingFactory.GetLogger().Log(ex.InnerException + "  " + ex.Message, EventLogSeverity.Error);
            }
        }
示例#21
0
        //public PostWebServiceResponse PostAsync<T>(T item)
        //{
        //    PostWebServiceResponse response = new PostWebServiceResponse();
        //    try
        //    {
        //        WebRequest req = HttpWebRequest.Create(RequestUrl);
        //        req.Method = MethodType;


        //        if (Headers.Count > 0)
        //            BuildHeaders(req);
        //        Body = JsonConvert.SerializeObject(item);
        //        Stream stream = req.GetRequestStream();
        //        StreamWriter wr = new StreamWriter(stream);
        //        wr.Write(Body);
        //        wr.Flush();
        //        wr.Close();
        //        stream.Close();
        //        //req.ContentLength = stream.Length;

        //        var r = req.GetResponse();
        //        Stream s = r.GetResponseStream();
        //        StreamReader reader = new StreamReader(s, true);
        //        string x = reader.ReadToEnd();

        //        var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
        //        if (Resolver != null)
        //        {
        //            settings.ContractResolver = Resolver;
        //        }
        //        settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

        //        response = JsonConvert.DeserializeObject<PostWebServiceResponse>(x, settings);
        //        return response;
        //    }
        //    catch (Exception ex)
        //    {

        //        string exception = BuildLogMessage() + " : " + ex.Message;
        //        LoggingFactory.GetLogger().Log(exception);
        //        response.statusId = "0";
        //        return response;
        //    }
        //}
        public PostWebServiceResponse PostAsyncFormData <T>(T item)
        {
            PostWebServiceResponse response = new PostWebServiceResponse();

            try
            {
                //  HttpClient client = new HttpClient();

                //Defining the unique boundary
                string         boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
                HttpWebRequest req      = (HttpWebRequest)WebRequest.Create(RequestUrl);
                req.AllowAutoRedirect = false;
                if (Headers.Count > 0)
                {
                    BuildHeaders(req);
                }
                req.Method      = MethodType;//Post
                req.ContentType = "multipart/form-data; boundary=" + boundary;
                Stream stream = req.GetRequestStream();


                //Body need to be extended for each part of the request
                // Add header for JSON part


                // Body += "Content-Disposition: form-data; name='entity'\r\n";//entity is relative to the object we r sending
                //Body += "Content-Type: application/json\r\n\r\n";//defining the content type for this part of request
                // Add document object data in JSON
                //Body += JsonConvert.SerializeObject(item);
                Body += "\r\n--" + boundary + "\r\n";;


                Body += string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", "record");
                var serSettings = new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore, DateTimeZoneHandling = DateTimeZoneHandling.Utc
                };
                string jsonString = JsonConvert.SerializeObject(item, serSettings);
                Body += jsonString;
                Body += "\r\n--" + boundary + "\r\n";;

                //Now we need to add the header for the binary part inside the body
                byte[] data = System.Text.Encoding.UTF8.GetBytes(Body);
                stream.Write(data, 0, data.Length);

                // Add binary file to request


                // Finalizing by adding the footer of the request or what we call trailr
                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                stream.Write(trailer, 0, trailer.Length);
                stream.Close();


                // Do the post and get the response.

                var          r      = req.GetResponse();
                Stream       s      = r.GetResponseStream();
                StreamReader reader = new StreamReader(s, true);
                string       x      = reader.ReadToEnd();

                var settings = new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore, DateTimeZoneHandling = DateTimeZoneHandling.Utc
                };
                if (Resolver != null)
                {
                    settings.ContractResolver = Resolver;
                }
                settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

                response = JsonConvert.DeserializeObject <PostWebServiceResponse>(x, settings);
                return(response);
            }
            catch (Exception ex)
            {
                string exception = BuildLogMessage() + " : " + ex.Message;
                LoggingFactory.GetLogger().Log(exception);
                response.statusId    = "0";
                response.description = ex.Message;
                return(response);
            }
        }
示例#22
0
        /// <summary>
        /// Sign up a user to a plan
        /// </summary>
        /// <param name="request">Sign up request</param>
        public PlanSignUpResponse PlanSignUp(PlanSignUpRequest request)
        {
            try
            {
                // Begin transaction
                _unitOfWork.Begin("PlanSignUp");

                var response = new PlanSignUpResponse();
                var dbPlan   = _planRepository.Query().FirstOrDefault(p => p.PlanCode.ToLower() == request.PlanName.ToLower());
                if (dbPlan == null)
                {
                    response.HasError  = true;
                    response.ErrorCode = ErrorCode.PlanNotFound;
                    return(response);
                }

                if (request.SignUpModel.Domain != null)
                {
                    if (
                        _customerRepository.Query().Any(
                            t => t.Hostname.ToLower() == request.SignUpModel.Domain.ToLower()))
                    {
                        response.ErrorCode = ErrorCode.DomainAlreadyExists;
                        response.HasError  = true;
                        return(response);
                    }
                }

                // Customer
                var customer = new Customer(request.SignUpModel.FullName, request.SignUpModel.Domain,
                                            request.SignUpModel.Company);
                _customerRepository.Add(customer);

                // Role
                var role = new Role(customer, "Administrator", true, UserType.SystemUser);
                _roleRepository.Add(role);

                // Setup the User
                var user = new User(customer, request.SignUpModel.Email, request.SignUpModel.FirstName,
                                    request.SignUpModel.LastName, request.SignUpModel.Password);
                _userRepository.Add(user);

                role.AddUser(user);

                customer.UpdateAdminUser(user);

                // Security questions
                var referenceList = _referenceListRepository.Query().FirstOrDefault(l => l.SystemName == "Security Questions");
                if (referenceList == null)
                {
                    throw new NullReferenceException("Security questions reference list is null");
                }

                foreach (var securityQuestion in SecurityQuestions.Questions)
                {
                    referenceList.AddItem(customer, securityQuestion);
                }

                // User security questions
                user.AddSecurityQuestion("a", "a");
                user.AddSecurityQuestion("b", "b");
                user.AddSecurityQuestion("c", "c");

                // Create customer in stripe
                var stripeCustomer = StripeFactory.GetStripeService().CreateCustomer(request.SignUpModel.FullName,
                                                                                     request.SignUpModel.Email);
                customer.PaymentCustomerId = stripeCustomer.Id;

                // Associate plan
                var result = StripeFactory.GetStripeService().AssignCustomerPlan(customer.PaymentCustomerId,
                                                                                 dbPlan.PlanCode,
                                                                                 request.SignUpModel.CardNumber,
                                                                                 request.SignUpModel.SecurityCode,
                                                                                 int.Parse(
                                                                                     request.SignUpModel.Expiration.
                                                                                     Substring(0, 2)),
                                                                                 int.Parse(
                                                                                     request.SignUpModel.Expiration.
                                                                                     Substring(3, 2)));

                if (result != "active")
                {
                    throw new Exception($"Incorrect assigning plan result for Customer {customer.FullName}");
                }

                customer.UpdatePlan(dbPlan);
                _customerRepository.Update(customer);

                // End transaction
                _unitOfWork.End();

                // Send email
                var emailTemplate =
                    _emailTemplatesRepository.GetTemplateByName(
                        EmailTemplateCode.SignUpGreeting.ToDescriptionString());

                emailTemplate = EmailTemplateFactory.ParseTemplate(emailTemplate, customer);
                var mailMessage = MailMessageMapper.ConvertToMailMessage(emailTemplate);
                var emailResult = EmailServiceFactory.GetEmailService().SendMail(mailMessage);

                if (!emailResult)
                {
                    throw new Exception("Problem sending email");
                }

                return(response);
            }
            catch (StripeException ex)
            {
                LoggingFactory.GetLogger().LogError(ex);
                throw new Exception("Assigning customer plan error", ex);
            }
            catch (Exception ex)
            {
                LoggingFactory.GetLogger().LogError(ex);
                throw;
            }
        }
示例#23
0
        private static AnalyzeRecivedDataReponse AnalyzeRecivedDataByFunNum01(
            DataAnalyzeMode dataAnalyzeMode,
            List <byte> requestByteData,
            List <byte> recevideByteData)
        {
            AnalyzeRecivedDataReponse reponse = new AnalyzeRecivedDataReponse();

            try
            {
                int deviceAddress = requestByteData[0];

                int startRegisterAddress  = requestByteData[2] * 256 + requestByteData[3];
                int countOfRegisterToRead = requestByteData[4] * 256 + requestByteData[5];


                //接受侦recevideByteData中寄存器值的数据之前的字节数:
                //deviceAddress、funNum、recevideByteData[2]个占1个字节
                int byteCountBeforeDataRegion = 3;
                //数据区表示寄存器值的字节数
                int registerValueByteCount = recevideByteData[2];

                //避免数据返回不完整引发下标溢出
                if (recevideByteData.Count > (byteCountBeforeDataRegion + recevideByteData[2]))
                {
                    byte          byteData     = 0;
                    List <UInt16> totalRecvVal = new List <ushort>();
                    for (int k = 0; k < registerValueByteCount; k++)
                    {
                        byteData = recevideByteData[byteCountBeforeDataRegion + k];

                        //解析01功能码的顺序是从每个返回字节的低位到高位
                        totalRecvVal.Add((UInt16)(byteData & 0x01));         //一个字节中的最低位
                        totalRecvVal.Add((UInt16)((byteData & 0x02) >> 1));
                        totalRecvVal.Add((UInt16)((byteData & 0x04) >> 2));
                        totalRecvVal.Add((UInt16)((byteData & 0x08) >> 3));
                        totalRecvVal.Add((UInt16)((byteData & 0x10) >> 4));
                        totalRecvVal.Add((UInt16)((byteData & 0x20) >> 5));
                        totalRecvVal.Add((UInt16)((byteData & 0x40) >> 6));
                        totalRecvVal.Add((UInt16)((byteData & 0x80) >> 7));  //一个字节中的最高位,先加入高位data
                    }

                    //条件:i < countOfRegisterToRead 是要求实际要读多少个寄存器的值,就存储多少个值
                    //totalRecvVal中可能存在不表示寄存器值的多余数据,
                    //通过条件:i < countOfRegisterToRead,提取有效数据,剔除无效数据
                    for (int i = 0; i < totalRecvVal.Count && i < countOfRegisterToRead; i++)
                    {
                        Register register = new Register();
                        register.DeviceAddress   = deviceAddress;
                        register.RegisterAddress = startRegisterAddress;
                        register.RegisterValue   = totalRecvVal[i];

                        reponse.Registers.Add(register);
                        ++startRegisterAddress;
                    }
                }
            }
            catch (Exception)
            {
                reponse.AnalyzeRecivedDataSuccess = false;
                LoggingFactory.GetLogger().WriteDebugLogger("解析Modbus接收帧时发生异常!");
                return(reponse);
            }


            return(reponse);
        }
示例#24
0
 private void LogDebug(string message)
 {
     LoggingFactory.GetLogger().Log(LogLevel.Debug, message);
 }
示例#25
0
        private static AnalyzeRecivedDataReponse AnalyzeRecivedDataByFunNum03(
            DataAnalyzeMode dataAnalyzeMode,
            List <byte> requestByteData,
            List <byte> recevideByteData)
        {
            AnalyzeRecivedDataReponse reponse = new AnalyzeRecivedDataReponse();

            try
            {
                //接受侦recevideByteData中寄存器值的数据之前的字节数:
                //deviceAddress、funNum、recevideByteData[2]个占1个字节
                int byteCountBeforeDataRegion = 3;

                //避免数据返回不完整引发下标溢出
                if (recevideByteData.Count > (byteCountBeforeDataRegion + recevideByteData[2]))
                {
                    int deviceAddress        = requestByteData[0];
                    int startRegisterAddress = requestByteData[2] * 256 + requestByteData[3];

                    //寄存器的个数
                    int countOfRegisterHadRead = recevideByteData[2] / 2;

                    for (int i = 0; i < countOfRegisterHadRead; i++)
                    {
                        Register register = new Register();
                        register.DeviceAddress   = deviceAddress;
                        register.RegisterAddress = startRegisterAddress;

                        if (dataAnalyzeMode == DataAnalyzeMode.DataHighToLow)
                        {
                            //HL HL
                            register.RegisterValue =
                                (ushort)(recevideByteData[2 * i + byteCountBeforeDataRegion] * 256 +
                                         recevideByteData[2 * i + byteCountBeforeDataRegion + 1]);

                            //先加入低位
                            register.LowToHighDataBytes.Add(recevideByteData[2 * i + byteCountBeforeDataRegion + 1]);
                            //后加入高位
                            register.LowToHighDataBytes.Add(recevideByteData[2 * i + byteCountBeforeDataRegion]);
                        }
                        else
                        {
                            //LH LH
                            register.RegisterValue =
                                (ushort)(recevideByteData[2 * i + byteCountBeforeDataRegion] +
                                         recevideByteData[2 * i + byteCountBeforeDataRegion + 1] * 256);

                            //先加入低位
                            register.LowToHighDataBytes.Add(recevideByteData[2 * i + byteCountBeforeDataRegion]);
                            //后加入高位
                            register.LowToHighDataBytes.Add(recevideByteData[2 * i + byteCountBeforeDataRegion + 1]);
                        }

                        ;
                        reponse.Registers.Add(register);
                        ++startRegisterAddress;
                    }
                }
            }
            catch (Exception)
            {
                reponse.AnalyzeRecivedDataSuccess = false;
                LoggingFactory.GetLogger().WriteDebugLogger("解析Modbus接收帧时发生异常!");
                return(reponse);
            }

            return(reponse);
        }
示例#26
0
 private void LogError(string message)
 {
     LoggingFactory.GetLogger().Log(LogLevel.Error, message);
 }
示例#27
0
        /// <summary>
        /// 写单个寄存器
        /// </summary>
        /// <param name="requestByteData"></param>
        /// <param name="recevideByteData"></param>
        /// <returns></returns>
        private static AnalyzeRecivedDataReponse AnalyzeRecivedDataByFunNum06(
            DataAnalyzeMode dataAnalyzeMode,
            List <byte> requestByteData,
            List <byte> recevideByteData)
        {
            AnalyzeRecivedDataReponse reponse = new AnalyzeRecivedDataReponse();

            try
            {
                int deviceAddress = recevideByteData[0];

                //byte[] startRegisterByte = new byte[] { recevideByteData[2], recevideByteData[3] };
                //int startRegisterAddress = BitConverter.ToUInt16(startRegisterByte, 0);
                int startRegisterAddress = requestByteData[2] * 256 + requestByteData[3];

                //byte[] valueToSetByte = new byte[] { requestByteData[4], requestByteData[5] };
                //double valueToSet = BitConverter.ToDouble(valueToSetByte, 0);

                //接受侦recevideByteData中寄存器值的数据之前的字节数:
                //deviceAddress、funNum、ecevideByteData[2]个占1个字节
                int byteCountBeforeDataRegion = 4;
                int countOfRegisterToRead     = 1;

                //避免数据返回不完整引发下标溢出
                if (recevideByteData.Count > (byteCountBeforeDataRegion + countOfRegisterToRead * 2) &&
                    requestByteData.Count > (byteCountBeforeDataRegion + countOfRegisterToRead * 2))
                {
                    if (requestByteData[byteCountBeforeDataRegion] == recevideByteData[byteCountBeforeDataRegion] &&
                        requestByteData[byteCountBeforeDataRegion + 1] == recevideByteData[byteCountBeforeDataRegion + 1])
                    {
                        reponse.ModbusReponseSuccess = true;
                    }
                    else
                    {
                        reponse.ModbusReponseSuccess = false;
                    }

                    Register register = new Register();
                    register.DeviceAddress   = deviceAddress;
                    register.RegisterAddress = startRegisterAddress;

                    //byte[] bytevalues = new byte[]
                    //    {
                    //         recevideByteData[byteCountBeforeDataRegion],
                    //         recevideByteData[byteCountBeforeDataRegion + 1],
                    //    };

                    //register.RegisterValue = BitConverter.ToUInt16(bytevalues, 0);
                    if (dataAnalyzeMode == DataAnalyzeMode.DataHighToLow)
                    {
                        //HL HL
                        register.RegisterValue = (ushort)(recevideByteData[byteCountBeforeDataRegion] * 256 +
                                                          recevideByteData[byteCountBeforeDataRegion + 1]);


                        register.LowToHighDataBytes.Add(recevideByteData[byteCountBeforeDataRegion + 1]); //低位
                        register.LowToHighDataBytes.Add(recevideByteData[byteCountBeforeDataRegion]);     //高位
                    }
                    else
                    {
                        //LH LH
                        register.RegisterValue = (ushort)(recevideByteData[byteCountBeforeDataRegion] +
                                                          recevideByteData[byteCountBeforeDataRegion + 1] * 256);

                        register.LowToHighDataBytes.Add(recevideByteData[byteCountBeforeDataRegion]);     //低位
                        register.LowToHighDataBytes.Add(recevideByteData[byteCountBeforeDataRegion + 1]); //高位
                    }


                    reponse.Registers.Add(register);
                }
            }
            catch (Exception)
            {
                reponse.AnalyzeRecivedDataSuccess = false;
                LoggingFactory.GetLogger().WriteDebugLogger("解析Modbus接收帧时发生异常!");
                return(reponse);
            }

            return(reponse);
        }
        public void ProcessRequest(HttpContext context)
        {
            var soapAction = context.Request.ContentType; //_requestExtensionMethods.GetSoapAction(context);
            var soapBody   = _requestExtensionMethods.GetSoapBody(context);
            var logSoap    = AppSettings.Get <bool>("LogSoap");

            if (logSoap)
            {
                var nameLoger = "Request_" + DateTime.Now;
                using (var logger = LoggingFactory.GetNLogger(nameLoger))
                {
                    logger.Info(soapBody + "-------soap action ContentType:" + soapAction);
                }
            }
            if (string.IsNullOrEmpty(soapBody))
            {
                context.Response.StatusCode = 400;
                context.Response.End();
            }

            #region Log SOAP Request Message


            if (logSoap)
            {
                var nameLoger = "Request_" + DateTime.Now;
                using (var logger = LoggingFactory.GetNLogger(nameLoger))
                {
                    logger.Info(soapBody);
                }
            }

            #endregion

            //var url = "";
            //var participantCode = _externalCcRequestHelper.GetParticipantCode(soapBody);
            //var exists = _cacheHelper.Exists(participantCode);
            //if (exists)
            //{
            //    url = _cacheHelper.Get<string>(participantCode);
            //}
            //else
            //{
            //    url = _externalCcRequestHelper.GetParticipantUri(participantCode);
            //    _cacheHelper.Add(url, participantCode);
            //}

            MIMBody mimBody = new MIMBody();

            mimBody.Message = soapBody;

            //var test = new ServiceClient();
            //test.InvokeWebMethod(ref mimBody);

            var responseFromExternalCs = "";
            var urlToExternalBus       = AppSettings.Get <string>("UrlToExternalBus");
            //var url = "https://externalcc.interop.st/ExternalCC/Service.svc";
            //var dictionary = new Dictionary<string, string>();
            try
            {
                System.Net.ServicePointManager.ServerCertificateValidationCallback =
                    ((sender, certificate, chain, sslPolicyErrors) => true);//sertifikatot ne im e u red za toa go stavam ova za da go ignorira
                responseFromExternalCs = _externalCcRequestHelper.ResentExternalCCRequest(null, soapBody, urlToExternalBus);
            }
            catch (Exception ex)
            {
                var nameLoger = "Error_" + DateTime.Now;
                using (var logger = LoggingFactory.GetNLogger(nameLoger))
                {
                    logger.Error(ex.Message);
                }
                //_cacheHelper.ClearAll();
                //dictionary = _externalCcRequestHelper.GetAllParticipantsUri();
                //foreach (var participant in dictionary)
                //{
                //    _cacheHelper.Add(participant.Value, participant.Key);
                //}
                //exists = _cacheHelper.Exists(participantCode);
                //if (exists)
                //{
                //    url = _cacheHelper.Get<string>(participantCode);
                //}
                //else
                //{
                //    url = _externalCcRequestHelper.GetParticipantUri(participantCode);
                //    _cacheHelper.Add(url, participantCode);
                //}
                //responseFromExternalCs = _externalCcRequestHelper.ResentExternalCCRequest(soapAction, soapBody, url);
            }


            #region Log SOAP Request Message

            if (logSoap)
            {
                var nameLoger = "Response_" + DateTime.Now;
                using (var logger = LoggingFactory.GetNLogger(nameLoger))
                {
                    logger.Info(responseFromExternalCs);
                }
            }

            #endregion

            var xDoc = XDocument.Parse(responseFromExternalCs);
            //change AdditionalHeader in soapBody
            if (AppSettings.Get <bool>("SwitchAdditionalHeader"))
            {
                XNamespace defaultNs = "http://mioa.gov.mk/interop/mim/v1";
                xDoc.Descendants(defaultNs + "MIMadditionalHeader").Descendants().Remove();
                xDoc.Descendants().SingleOrDefault(x => x.Name.LocalName == "MIMadditionalHeader").Add(new XElement(defaultNs + "Status", ""), new XElement(defaultNs + "StatusMessage", ""), new XElement(defaultNs + "ProviderEndpointUrl", ""), new XElement(defaultNs + "ExternalEndpointUrl", ""), new XElement(defaultNs + "WebServiceUrl", ""), new XElement(defaultNs + "ConsumerBusCode", ""), new XElement(defaultNs + "TimeStampToken", ""), new XElement(defaultNs + "IsInteropTestCommunicationCall", false));
                responseFromExternalCs = xDoc.ToString();

                var nameLoger = "Switch items in additional header" + DateTime.Now;
                using (var logger = LoggingFactory.GetNLogger(nameLoger))
                {
                    logger.Info(responseFromExternalCs);
                }
            }

            HttpContext.Current.Response.ContentType = "application/soap+xml";
            context.Response.Write(responseFromExternalCs);
        }
示例#29
0
        public SetupPaymentPlanReponse SetupPaymentPlan(PlanSetupModel planModel)
        {
            var response = new SetupPaymentPlanReponse();

            try
            {
                Customer customer = _customerRepository.Get(Guid.Parse(planModel.CustomerId));
                if (customer == null)
                {
                    throw new Exception("Incorrect Customer identifier");
                }

                if (customer.Plan != null)
                {
                    response.HasPlan = true;
                    var status = StripeFactory.GetStripeService().CloseCustomerPlan(customer.PaymentCustomerId);
                    response.Status = status;

                    //return response;
                }

                Plan dbPlan =
                    _planRepository.Query().FirstOrDefault(p => p.PlanCode.ToLower() == planModel.StripePlanId.ToLower());
                if (dbPlan == null)
                {
                    throw new Exception("Incorrect plan identifier");
                }

                var result = StripeFactory.GetStripeService().AssignCustomerPlan(
                    planModel.PaymentCustomerId, planModel.StripePlanId, planModel.CreditCardNumber,
                    planModel.Cvc, planModel.CardExpirationMonth, planModel.CardExpirationYear);

                if (result != "active")
                {
                    response.IsStatusActive = false;
                    return(response);
                }
                else
                {
                    //dbPlan.Customers.
                    response.IsStatusActive = true;
                }

                customer.UpdatePlan(dbPlan);
                _unitOfWork.Commit();

                return(response);
            }
            catch (StripeException ex)
            {
                LoggingFactory.GetLogger().LogError(ex);
                response.HasError  = true;
                response.ErrorCode = ErrorCode.StripeSetupError;
                response.Message   = ex.Message;
            }
            catch (Exception ex)
            {
                LoggingFactory.GetLogger().LogError(ex);
                response.HasError  = true;
                response.ErrorCode = ErrorCode.StripeSetupError;
                response.Message   = ErrorCode.StripeSetupError.ToString();
            }
            return(response);
        }
示例#30
0
        public ChangeSubscriptionResponse ChangeSubscription(ChangeSubscriptionRequest request)
        {
            var response = new ChangeSubscriptionResponse();

            try
            {
                Customer customer = _customerRepository.Get(request.CustomerId);

                if (customer.Plan != null)
                {
                    var status = StripeFactory.GetStripeService().CloseCustomerPlan(customer.PaymentCustomerId);
                    if (status.ToLower() == "active")
                    {
                        response.IsStatusActive = true;
                        return(response);
                    }
                }

                Plan plan =
                    _planRepository.Query().SingleOrDefault(p => p.PlanCode.ToLower() == request.PlanId.ToLower());

                if (plan == null)
                {
                    response.ErrorCode = ErrorCode.IncorrectPlanIdentifier;
                    return(response);
                }

                string result = StripeFactory.GetStripeService().AssignCustomerPlan(customer.PaymentCustomerId,
                                                                                    request.ChangeSubscriptionModel.PlanId,
                                                                                    request.ChangeSubscriptionModel.CardNumber,
                                                                                    request.ChangeSubscriptionModel.SecurityCode,
                                                                                    request.ChangeSubscriptionModel.ExpirationMonth,
                                                                                    request.ChangeSubscriptionModel.ExpirationYear);


                if (result != "active")
                {
                    response.Result = result;
                    return(response);
                }

                customer.UpdatePlan(plan);

                _unitOfWork.Commit();
            }
            catch (StripeException ex)
            {
                LoggingFactory.GetLogger().LogError(ex);
                response.HasError  = true;
                response.ErrorCode = ErrorCode.StripeSetupError;
                response.Message   = ex.Message;
            }
            catch (Exception ex)
            {
                LoggingFactory.GetLogger().LogError(ex);
                response.HasError  = true;
                response.ErrorCode = ErrorCode.StripeSetupError;
                response.Message   = ErrorCode.StripeSetupError.ToString();
            }


            return(response);
        }