Beispiel #1
0
        public static string GetAppLockerPolicy(PolicyType policyType, string ldapPath = "", bool xmlOutput = false)
        {
            AppLockerPolicy appLockerPolicy;

            if (policyType == PolicyType.Local)
            {
                appLockerPolicy = PolicyManager.GetLocalPolicy();
            }
            else if (policyType == PolicyType.Domain)
            {
                appLockerPolicy = PolicyManager.GetDomainPolicy(ldapPath);
            }
            else
            {
                if (policyType != PolicyType.Effective)
                {
                    throw new InvalidOperationException();
                }
                appLockerPolicy = PolicyManager.GetEffectivePolicy();
            }
            if (xmlOutput)
            {
                return(appLockerPolicy.ToXml());
            }
            return(JsonConvert.SerializeObject(appLockerPolicy, Formatting.Indented));
        }
Beispiel #2
0
        /// <summary>
        /// 生成订单
        /// </summary>
        public string ProduceOrder(Guid policyId, PolicyType policyType, Guid publisher, string officeNo, string source, int choise, bool needAUTH, bool HasSubsidized,
                                   bool IsUsePatPrice, bool forbidChnagePNR)
        {
            var           orderView     = Session["OrderView"] as OrderView;
            var           flights       = Session["ReservedFlights"] as IEnumerable <FlightView>;
            MatchedPolicy matchedPolicy = MatchedPolicyCache.FirstOrDefault(p => p.Id == policyId);

            if (matchedPolicy == null)
            {
                throw new CustomException("政策选择超时");
            }
            if (flights.First().BunkType != null && orderView.Source == OrderSource.PlatformOrder &&
                (flights.First().BunkType == BunkType.Free || matchedPolicy.OriginalPolicy is SpecialPolicyInfo && ((SpecialPolicyInfo)matchedPolicy.OriginalPolicy).Type == SpecialProductType.LowToHigh))
            {
                SpecialPolicy policy = PolicyManageService.GetSpecialPolicy(policyId);
                //低打高返和集团票性质一样 不需要去订坐 2013-4-3 wangsl
                //if (policy != null && (policy.SynBlackScreen||policy.Type==SpecialProductType.LowToHigh))
                if (policy != null && policy.SynBlackScreen)
                {
                    PNRPair pnr = PNRHelper.ReserveSeat(flights, orderView.Passengers);
                    orderView.PNR = pnr;
                }
            }
            Order order = OrderProcessService.ProduceOrder(orderView, matchedPolicy, CurrentUser, BasePage.OwnerOEMId, forbidChnagePNR, (AuthenticationChoise)choise);

            FlightQuery.ClearFlightQuerySessions();
            if (order.Source == OrderSource.PlatformOrder && !PNRPair.IsNullOrEmpty(order.ReservationPNR) && !String.IsNullOrWhiteSpace(order.Product.OfficeNo))
            {
                if (needAUTH)
                {
                    authorize(order.ReservationPNR, officeNo, source, BasePage.OwnerOEMId);
                }
            }
            return(order.Id.ToString());
        }
Beispiel #3
0
        private void setVisible()
        {
            PolicyType policyType = GetPolicyType();

            if ((policyType == PolicyType.ОСАГО) || (policyType == PolicyType.расш_КАСКО))
            {
                lbLimitCost.Visible = false;
                tbLimitCost.Visible = false;
                lbPay2.Visible      = false;
                tbPay2.Visible      = false;
                lbPay2Date.Visible  = false;
                dtpDatePay2.Visible = false;
            }
            if (policyType == PolicyType.КАСКО)
            {
                lbLimitCost.Text    = "Страховая стоимость, руб:";
                lbLimitCost.Visible = true;
                tbLimitCost.Visible = true;
                lbPay2.Visible      = true;
                tbPay2.Visible      = true;
                lbPay2Date.Visible  = true;
                dtpDatePay2.Visible = true;
            }
            else if ((policyType == PolicyType.ДСАГО) || (policyType == PolicyType.GAP))
            {
                lbLimitCost.Text    = "Лимит, руб:";
                lbLimitCost.Visible = true;
                tbLimitCost.Visible = true;
                lbPay2.Visible      = false;
                tbPay2.Visible      = false;
                lbPay2Date.Visible  = false;
                dtpDatePay2.Visible = false;
            }
        }
Beispiel #4
0
        private void LogDelete(PolicyType entity)
        {
            var creator = new LogCreatorApi(this, ActivityLogTypeEnum.DeletePolicyType);

            creator.AddPolicyType(entity.Id);
            creator.SaveToLog(false);
        }
Beispiel #5
0
        public HttpResponseMessage Post(PolicyType model)
        {
            try
            {
                Uow.PolicyTypes.Add(model);

                //// START: Add Default Rebates
                var companyList = GetInsuranceProviders();
                foreach (var company in companyList)
                {
                    var defaultRebateItem = new DefaultRebate
                    {
                        InsuranceProviderId = company.Id,
                        PolicyTypeId        = model.Id,
                        Rate = 0
                    };
                    Uow.DefaultRebates.Add(defaultRebateItem);
                }
                //// END: Add Default Rebates

                Uow.SaveChanges();

                LogAdd(model);

                return(Request.CreateResponse(HttpStatusCode.OK, model));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
Beispiel #6
0
        public void TestMethod1()
        {
            PolicyType ptA = PolicyType.GetPolicyType("A");
            PolicyType ptB = PolicyType.GetPolicyType("B");
            PolicyType ptC = PolicyType.GetPolicyType("C");

            MaturityData maturityData1 = new MaturityData("A001", new DateTime(1989, 1, 1), 10, false, 10, 10);

            Assert.IsTrue(ptA.QualifiesForDiscretionayBonus(maturityData1));
            Assert.IsFalse(ptB.QualifiesForDiscretionayBonus(maturityData1));
            Assert.IsFalse(ptC.QualifiesForDiscretionayBonus(maturityData1));

            MaturityData maturityData2 = new MaturityData("A001", new DateTime(1990, 1, 1), 10, false, 10, 10);

            Assert.IsFalse(ptA.QualifiesForDiscretionayBonus(maturityData2));
            Assert.IsFalse(ptB.QualifiesForDiscretionayBonus(maturityData2));
            Assert.IsFalse(ptC.QualifiesForDiscretionayBonus(maturityData2));

            MaturityData maturityData3 = new MaturityData("A001", new DateTime(1990, 1, 1), 10, true, 10, 10);

            Assert.IsFalse(ptA.QualifiesForDiscretionayBonus(maturityData3));
            Assert.IsTrue(ptB.QualifiesForDiscretionayBonus(maturityData3));
            Assert.IsTrue(ptC.QualifiesForDiscretionayBonus(maturityData3));

            MaturityData maturityData4 = new MaturityData("A001", new DateTime(1989, 1, 1), 10, true, 10, 10);

            Assert.IsTrue(ptA.QualifiesForDiscretionayBonus(maturityData4));
            Assert.IsTrue(ptB.QualifiesForDiscretionayBonus(maturityData4));
            Assert.IsFalse(ptC.QualifiesForDiscretionayBonus(maturityData4));
        }
Beispiel #7
0
        /// <summary>
        /// Obtiene el nombre de una politica de control de excepciones a partir del enumerador
        /// </summary>
        /// <param name="type">Tipo de politica</param>
        /// <returns>Nombre de la politica</returns>
        private static string GetPolicyName(PolicyType type)
        {
            string policyName = null;

            switch (type)
            {
            case PolicyType.Application:
                policyName = PolicyName.Application;
                break;

            case PolicyType.Business:
                policyName = PolicyName.Business;
                break;

            case PolicyType.Data:
                policyName = PolicyName.Data;
                break;

            case PolicyType.Api:
                policyName = PolicyName.Api;
                break;
            }

            return(policyName);
        }
Beispiel #8
0
        private PolicyType queryPolicyType(IEnumerable <DataTransferObject.FlightQuery.FlightView> flights)
        {
            PolicyType policyType = PolicyType.Bargain;

            if (_pnr.IsTeam)
            {
                policyType = PolicyType.Team;
            }
            // 根据舱位的类型来决定政策类型
            if (flights.Any(f => f.BunkType == BunkType.Promotion || f.BunkType == BunkType.Production || f.BunkType == BunkType.Transfer))
            {
                policyType = PolicyType.Bargain;
            }
            else
            {
                switch (flights.First().BunkType)
                {
                case BunkType.Economic:
                case BunkType.FirstOrBusiness:
                    policyType = PolicyType.Normal | PolicyType.Bargain;
                    break;

                case BunkType.Promotion:
                case BunkType.Production:
                case BunkType.Transfer:
                    policyType = PolicyType.Bargain;
                    break;

                default:
                    policyType = PolicyType.Special;
                    break;
                }
            }
            return(policyType);
        }
Beispiel #9
0
        private PurchasePolicy CreateCondition(PolicyType type, string subject, ConditionType cond, string value)
        {
            PurchasePolicy policy = null;

            switch (cond)
            {
            case ConditionType.AddressEqual:
                policy = new AddressEquals(type, subject, value, SessionPolicies.Count);
                break;

            case ConditionType.PriceGreater:
                policy = new PriceGreaterThan(type, subject, value, SessionPolicies.Count);
                break;

            case ConditionType.PriceLesser:
                policy = new PriceLessThan(type, subject, value, SessionPolicies.Count);
                break;

            case ConditionType.QuantityGreater:
                policy = new QuantityGreaterThan(type, subject, value, SessionPolicies.Count);
                break;

            case ConditionType.QuantityLesser:
                policy = new QuantityLessThan(type, subject, value, SessionPolicies.Count);
                break;

            case ConditionType.UsernameEqual:
                policy = new UsernameEquals(type, subject, value, SessionPolicies.Count);
                break;
            }
            SessionPolicies.Add(policy);
            return(policy);
        }
Beispiel #10
0
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     if (Optional.IsDefined(SlackAmount))
     {
         writer.WritePropertyName("slackAmount");
         writer.WriteNumberValue(SlackAmount.Value);
     }
     if (Optional.IsDefined(SlackFactor))
     {
         writer.WritePropertyName("slackFactor");
         writer.WriteNumberValue(SlackFactor.Value);
     }
     if (Optional.IsDefined(DelayEvaluation))
     {
         writer.WritePropertyName("delayEvaluation");
         writer.WriteNumberValue(DelayEvaluation.Value);
     }
     if (Optional.IsDefined(EvaluationInterval))
     {
         writer.WritePropertyName("evaluationInterval");
         writer.WriteNumberValue(EvaluationInterval.Value);
     }
     writer.WritePropertyName("policyType");
     writer.WriteStringValue(PolicyType.ToString());
     writer.WriteEndObject();
 }
Beispiel #11
0
        public async Task <bool> PolicyAppliesToUser(PolicyType policyType, Func <Policy, bool> policyFilter = null,
                                                     string userId = null)
        {
            var policies = await GetAll(policyType, userId);

            if (policies == null)
            {
                return(false);
            }
            var organizations = await _organizationService.GetAllAsync(userId);

            IEnumerable <Policy> filteredPolicies;

            if (policyFilter != null)
            {
                filteredPolicies = policies.Where(p => p.Enabled && policyFilter(p));
            }
            else
            {
                filteredPolicies = policies.Where(p => p.Enabled);
            }

            var policySet = new HashSet <string>(filteredPolicies.Select(p => p.OrganizationId));

            return(organizations.Any(o =>
                                     o.Enabled &&
                                     o.Status >= OrganizationUserStatusType.Accepted &&
                                     o.UsePolicies &&
                                     !isExcemptFromPolicies(o, policyType) &&
                                     policySet.Contains(o.Id)));
        }
        public static string GetAppLockerPolicy(PolicyType policyType, string ldapPath = "", bool xmlOutput = false)
        {
            // Create IAppIdPolicyHandler COM interface
            IAppIdPolicyHandler IAppHandler = new AppIdPolicyHandlerClass();
            string policies;

            switch (policyType)
            {
            case PolicyType.Local:
            case PolicyType.Domain:
                policies = IAppHandler.GetPolicy(ldapPath);
                break;

            case PolicyType.Effective:
                policies = IAppHandler.GetEffectivePolicy();
                break;

            default:
                throw new InvalidOperationException();
            }

            if (xmlOutput)
            {
                return(policies);
            }

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(policies);
            return(JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented, true));
        }
Beispiel #13
0
        /// <summary>
        /// Setup constructor
		/// </summary>
		/// <param name="policyType">Associated policy type</param>
        /// <param name="name">Policy type display name</param>
        /// <param name="channels">Policy type channels</param>
        /// <param name="available">If policy type is available to be used in the designer</param>
		public PolicyTypeInfo(PolicyType policyType, IPolicyLanguageItem name, ChannelType[] channels, bool available)
		{
			m_PolicyType = policyType;
            m_Name = name;
            m_Channels = channels;
            m_Available = available;
        }
        public IExecutionPolicy GetPolicy(PolicyType type)
        {
            if (!_client.IsConnected)
            {
                throw new InvalidOperationException("Client has not connected to the Neo4j server");
            }

            // todo: this should be a prototype-based object creation
            switch (type)
            {
                case PolicyType.Cypher:
                    return new CypherExecutionPolicy(_client);
                case PolicyType.Gremlin:
                    return new GremlinExecutionPolicy(_client);
                case PolicyType.Batch:
                    return new BatchExecutionPolicy(_client);
                case PolicyType.Rest:
                    return new RestExecutionPolicy(_client);
                case PolicyType.Transaction:
                    return new CypherTransactionExecutionPolicy(_client);
                case PolicyType.NodeIndex:
                    return new NodeIndexExecutionPolicy(_client);
                case PolicyType.RelationshipIndex:
                    return new RelationshipIndexExecutionPolicy(_client);
                default:
                    throw new InvalidOperationException("Unknown execution policy:" + type.ToString());
            }
        }
Beispiel #15
0
        public void sendMailPolicy(Car car, PolicyType type)
        {
            PolicyList policyList = PolicyList.getInstance();
            Policy     policy     = policyList.getItem(car, type);

            if (string.IsNullOrEmpty(policy.File))
            {
                throw new Exception("Не найден файл полиса");
            }
            else
            {
                _subject = "Полис " + type.ToString();

                CreateBodyPolicy(type);

                DriverCarList driverCarList = DriverCarList.getInstance();
                Driver        driver        = driverCarList.GetDriver(car);

                Send(new List <Driver> {
                    driver
                }, new string[] { _authorEmail }, new List <Attachment>()
                {
                    new Attachment(policy.File)
                });
            }
        }
        public void Test(string value, PolicyType policyType, int errorCount)
        {
            SubDomainPolicy tag = (SubDomainPolicy)_parser.Parse(string.Empty, value);

            Assert.That(tag.PolicyType, Is.EqualTo(policyType));
            Assert.That(tag.ErrorCount, Is.EqualTo(errorCount));
        }
Beispiel #17
0
        /// <summary>
        /// Method for applying discretionary bonus.
        /// </summary>
        /// <param name="policyType"></param>
        /// <param name="membership"></param>
        /// <param name="policyStartDate"></param>
        /// <param name="discretionaryBonus"></param>
        /// <returns>Bonus for the policy type.</returns>
        private static double ApplyDiscretionaryBonus(PolicyType policyType, bool membership, DateTime policyStartDate, double discretionaryBonus)
        {
            double bonus = 0;

            // Convert the policy taken out date as formatted date.
            DateTime policyTakenOutPeriod = DateTime.ParseExact(policyTakenOutDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

            // Based on policy type to verify the bonus is applicable or not.
            switch (policyType)
            {
            case PolicyType.A:
                // For the policy 'A' type to validate the bonus is applicable based on the policy start date is taken out before the policy taken out period.
                bonus = policyStartDate < policyTakenOutPeriod ? discretionaryBonus : bonus;
                break;

            case PolicyType.B:
                // For the policy 'B' type to validate the bonus is applicable based on the policy membership to be 'Y'.
                bonus = membership ? discretionaryBonus : bonus;
                break;

            case PolicyType.C:
                // For the policy 'C' type to validate the bonus is applicable based on the policy start date is taken out after or on the policy taken out period with the policy membership to be 'Y'.
                bonus = (policyStartDate >= policyTakenOutPeriod && membership) ? discretionaryBonus : bonus;
                break;
            }

            return(bonus);
        }
Beispiel #18
0
        internal static bool RequirePat(IEnumerable <FlightView> flights, PolicyType policyType)
        {
            // 普通政策,单程根据时间段来决定是否需要P价格,其他的都要
            // 如果是默认政策,舱位是普通舱位时,判断条件跟普通政策一样。
            FlightView firstFlight = flights.First();

            if (firstFlight.BunkType.HasValue)
            {
                BunkType bunkType = firstFlight.BunkType.Value;
                if (policyType == PolicyType.Normal || policyType == PolicyType.NormalDefault ||
                    (policyType == PolicyType.OwnerDefault && (bunkType == BunkType.Economic || bunkType == BunkType.FirstOrBusiness)))
                {
                    switch (flights.Count())
                    {
                    case 2:
                        return(true);

                    case 1:
                        DateTime today = DateTime.Today;
                        return(SystemParamService.PATTimeZones.Any(item => item.Lower.Date <= today && today <= item.Upper.Date));
                    }
                }
            }
            return(false);
        }
Beispiel #19
0
 public PurchasePolicy(PolicyType type, string subject, int id)
 {
     ID      = id;
     Type    = type;
     Subject = subject;
     IsRoot  = false;
 }
        private async Task ValidateDependentPolicies(PolicyType type, Guid?orgId, bool enabled)
        {
            if (orgId == null)
            {
                throw new ArgumentNullException(nameof(orgId), "OrgId cannot be null");
            }

            switch (type)
            {
            case PolicyType.MasterPassword:
            case PolicyType.PasswordGenerator:
            case PolicyType.TwoFactorAuthentication:
            case PolicyType.OnlyOrg:
                break;

            case PolicyType.RequireSso:
                if (!enabled)
                {
                    break;
                }
                var singleOrg = await _policyRepository.GetByOrganizationIdTypeAsync(orgId.Value, type);

                if (singleOrg?.Enabled != true)
                {
                    ModelState.AddModelError(string.Empty, _i18nService.T("RequireSsoPolicyReqError"));
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #21
0
        public List <PurchasePolicy> GetAllPolicies()
        {
            List <int>            listOfIDs = new List <int>();
            List <PurchasePolicy> result    = new List <PurchasePolicy>();

            using (var dbReader = dbConnection.SelectFromTableWithCondition("ComplexPolicies", "*", "Root = 'true'"))
            {
                while (dbReader.Read())
                {
                    listOfIDs.Add(dbReader.GetInt32(0));
                    int            id      = dbReader.GetInt32(0);
                    PolicyType     type    = PurchasePolicy.GetEnumFromStringValue(dbReader.GetString(2));
                    string         subject = dbReader.GetString(3);
                    PurchasePolicy policy  = FindComplexPolicy(id, type, subject, true);
                    policy.IsRoot = true;
                    result.Add(policy);
                }
            }
            using (var dbReader = dbConnection.SelectFromTableWithCondition("SimplePolicies", "*", "Root = 'true'"))
            {
                while (dbReader.Read())
                {
                    int            id      = dbReader.GetInt32(0);
                    PolicyType     type    = PurchasePolicy.GetEnumFromStringValue(dbReader.GetString(2));
                    string         subject = dbReader.GetString(3);
                    PurchasePolicy policy  = FindSimplePolicy(id, type, subject, true);
                    policy.IsRoot = true;
                    result.Add(policy);
                }
            }
            return(result);
        }
Beispiel #22
0
        public PolicyModel(PolicyType policyType, bool enabled)
        {
            switch (policyType)
            {
            case PolicyType.TwoFactorAuthentication:
                NameKey        = "TwoStepLogin";
                DescriptionKey = "TwoStepLoginDescription";
                break;

            case PolicyType.MasterPassword:
                NameKey        = "MasterPassword";
                DescriptionKey = "MasterPasswordDescription";
                break;

            case PolicyType.PasswordGenerator:
                NameKey        = "PasswordGenerator";
                DescriptionKey = "PasswordGeneratorDescription";
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            PolicyType = policyType;
            Enabled    = enabled;
        }
Beispiel #23
0
        public string GetToken(ApplicationUser user, PolicyType policyType)
        {
            var handler    = new JwtSecurityTokenHandler();
            var key        = Encoding.ASCII.GetBytes(_key);
            var expireDate = DateTimeOffset.UtcNow;

            var claims = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.NameId, user.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.Id.ToString()),
                new Claim("name", user.Id.ToString()),
                new Claim("scope", policyType.ToString()),
                new Claim("CreateAt", expireDate.ToString())
            };

            var securityToken = new JwtSecurityToken(
                issuer: _issuer,
                audience: _audience,
                expires: DateTime.UtcNow.AddSeconds(_seconds),
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key),
                                                           SecurityAlgorithms.HmacSha256Signature),
                claims: claims
                );

            return(handler.WriteToken(securityToken));
        }
Beispiel #24
0
        // Get a policy for given bucket
        private async static Task GetBucketPolicy_Test1(MinioClient minio)
        {
            Console.Out.WriteLine("Test1: GetPolicyAsync ");
            string bucketName = GetRandomName(15);
            string objectName = GetRandomName(10);
            string fileName   = CreateFile(1 * MB);

            await Setup_Test(minio, bucketName);

            await minio.PutObjectAsync(bucketName,
                                       objectName,
                                       fileName);

            await minio.SetPolicyAsync(bucketName,
                                       objectName.Substring(5),
                                       PolicyType.READ_ONLY);

            PolicyType policy = await minio.GetPolicyAsync(bucketName, objectName.Substring(5));

            Assert.IsTrue(policy.Equals(PolicyType.READ_ONLY));
            await minio.RemoveObjectAsync(bucketName, objectName);

            await TearDown(minio, bucketName);

            File.Delete(fileName);
            Console.Out.WriteLine("Test1: GetPolicyAsync Complete");
        }
        /// <summary>
        /// Adds services for the current feature to the specified <see cref="IServiceCollection"/>.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> to add the feature's services to.</param>
        /// <param name="config">The <see cref="IConfiguration"/> elements for the current service.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IServiceCollection AddFeatureServices(this IServiceCollection services, IConfiguration config)
        {
            var policyRegistry = services.AddPolicyRegistry();
            var policies       = new PolicyType[] { PolicyType.Retry, PolicyType.CircuitBreaker };

            // Configure Polly Policies for IContractsApproverService HttpClient
            services
            .AddPolicies <IContractNotificationService>(config, policyRegistry)
            .AddHttpClient <IContractNotificationService, ContractNotificationService, ContractsDataApiConfiguration>(config, policies);

            services.AddAzureServiceBusSender(config);

            // Configure service for audit
            services.AddAuditApiClient(config, policyRegistry);

            // Need to allow resue of Azure AAD auth tokens
            services.AddSingleton <IDateTimeProvider, DateTimeProvider>();
            services.AddTransient(typeof(IAuthenticationService <>), typeof(AuthenticationService <>));

            services.AddScoped(typeof(IContractReminderProcessingService), typeof(ContractReminderProcessingService));
            services.AddScoped(typeof(IServiceBusMessagingService), typeof(ServiceBusMessagingService));

            services.AddScoped <IContractStatusChangePublisher, ContractStatusChangePublisher>();

            services.AddAutoMapper(typeof(FeatureServiceCollectionExtensions).Assembly);

            return(services);
        }
Beispiel #26
0
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("type");
     writer.WriteStringValue(PolicyType.ToString());
     writer.WriteEndObject();
 }
Beispiel #27
0
        public IExecutionPolicy GetPolicy(PolicyType type)
        {
            if (!_client.IsConnected)
            {
                throw new InvalidOperationException("Client has not connected to the Neo4j server");
            }

            // todo: this should be a prototype-based object creation
            switch (type)
            {
            case PolicyType.Cypher:
                return(new CypherExecutionPolicy(_client));

            case PolicyType.Gremlin:
                return(new GremlinExecutionPolicy(_client));

            case PolicyType.Batch:
                return(new BatchExecutionPolicy(_client));

            case PolicyType.Rest:
                return(new RestExecutionPolicy(_client));

            case PolicyType.Transaction:
                return(new CypherTransactionExecutionPolicy(_client));

            case PolicyType.NodeIndex:
                return(new NodeIndexExecutionPolicy(_client));

            case PolicyType.RelationshipIndex:
                return(new RelationshipIndexExecutionPolicy(_client));

            default:
                throw new InvalidOperationException("Unknown execution policy:" + type.ToString());
            }
        }
Beispiel #28
0
        /// <summary>
        /// 换出票方
        /// </summary>
        public string ChangeProviderETDZ(Guid policyId, PolicyType policyType, Guid provider, string officeNo, decimal orderId, bool needAUTH, bool forbidChangePNR)
        {
            //string Msg = string.Empty;
            //BasePage.Lock(orderId,LockRole.Platform, "平台换出票方",out Msg);
            //if (Msg != string.Empty) throw new CustomException(Msg);
            var matchedPolicy = MatchedPolicyCache.FirstOrDefault(p => p.Id == policyId);

            if (matchedPolicy == null)
            {
                throw new CustomException("政策选择超时,请刷新政策后重新选择");
            }
            //var order = Service.OrderProcessService.ChangeProvider(orderId, provider, policyId, policyType, CurrentUser.UserName);
            var order = Service.OrderProcessService.ChangeProvider(orderId, matchedPolicy,
                                                                   CurrentUser.UserName, forbidChangePNR, needAUTH);

            BasePage.ReleaseLock(orderId);
            if (!order.IsSpecial && order.Source == OrderSource.PlatformOrder &&
                authorize(order.ReservationPNR, officeNo, FlightReserveModule.ChoosePolicy.ChangeProviderSource, order.OEMID ?? Guid.Empty))
            {
                return(string.Empty);
            }
            else
            {
                return(order.ReservationPNR.PNR);
            }
        }
Beispiel #29
0
 /// <summary>
 /// Constructor (when the policies are returned as TOP_K arrays)
 /// </summary>
 /// <param name="isWDL"></param>
 /// <param name="numPos"></param>
 /// <param name="valueEvals"></param>
 /// <param name="policyIndices"></param>
 /// <param name="policyProbabilties"></param>
 /// <param name="valueHeadConvFlat"></param>
 /// <param name="probType"></param>
 /// <param name="stats"></param>
 public PositionEvaluationBatch(bool isWDL, bool hasM, int numPos, Span <FP16> valueEvals,
                                int topK, Span <int> policyIndices, Span <float> policyProbabilties,
                                float[] valueHeadConvFlat, bool valsAreLogistic,
                                PolicyType probType, TimingStats stats)
     : this(isWDL, hasM, numPos, valueEvals, valueHeadConvFlat, valsAreLogistic, stats)
 {
     Policies = ExtractPoliciesTopK(numPos, topK, policyIndices, policyProbabilties, probType);
 }
Beispiel #30
0
		public PolicySet(PolicyType type, Guid guid, IPolicyLanguageItem name, IPolicyStore policyStore, IPolicyCatalogue policyCatalogue, bool readOnly)
			: base(guid, name, readOnly)
		{
			m_type = type;
			m_policyStore = policyStore;
			m_masterCatalogue = policyCatalogue;
			(m_masterCatalogue as PolicyCatalogue).PolicySet = this;
		}
Beispiel #31
0
        public ActionResult DeleteConfirmed(int id)
        {
            PolicyType policyType = db.PolicyTypes.Find(id);

            db.PolicyTypes.Remove(policyType);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #32
0
 /// <summary>
 ///     Constructor that loads all fields from a xml
 /// </summary>
 /// <param name="root">the root node of the xml for this Policy</param>
 public Policy(XElement xmlPolicy)
 {
     Name        = (string)xmlPolicy.Element(XName.Get("name"));
     Description = (string)xmlPolicy.Element(XName.Get("description"));
     Background  = (string)xmlPolicy.Element(XName.Get("background"));
     Solution    = (string)xmlPolicy.Element(XName.Get("solution"));
     Type        = (PolicyType)Enum.Parse(typeof(PolicyType), (string)xmlPolicy.Element(XName.Get("policyType")));
 }
Beispiel #33
0
 public Policy ToPolicy(PolicyType type, Guid organizationId)
 {
     return(ToPolicy(new Policy
     {
         Type = type,
         OrganizationId = organizationId
     }));
 }
 /// <summary>
 /// Registra una regla en la politica con el id proporcionado
 /// </summary>
 /// <param name="policyId"></param>
 /// <param name="rule"></param>
 /// <returns></returns>
 public static IObservable<Rule> RegisterRule(PolicyType policyId, Rule rule)
 {
     return RestEndpointFactory
         .Create<IPoliciesEndpoint>(SessionManager.Instance.CurrentLoggedUser)
             .RegisterRule(policyId.ToString().FromCamelToSnakeCase(), rule,
             rule.Entities.ToString(e => e.Id)).ToObservable()
             .SubscribeOn(NewThreadScheduler.Default)
             .InterpretingErrors();
 }
Beispiel #35
0
        public Policy getItem(Car car, PolicyType policyType)
        {
            var policyList = from policy in list
                         where policy.Car.ID == car.ID && policy.Type == policyType
                         orderby policy.DateEnd descending
                         select policy;

            return (policyList.Count() > 0) ? policyList.First() : car.CreatePolicy();
        }
Beispiel #36
0
 public Policy()
 {
     this.Bvin = string.Empty;
     this.StoreId = 0;
     this.LastUpdated = DateTime.UtcNow;
     this.Title = string.Empty;
     this.SystemPolicy = false;
     this.Blocks = new List<PolicyBlock>();
     this.Kind = PolicyType.TermsAndConditions;
 }
 public double CalculateYearlyPrice(AgeRange AgeRange, TypeOfVehicle TypeOfVehicle, PolicyType PolicyType)
 {
     double price = 0;
     this.ageRange = AgeRange;
     this.typeOfVehicle = TypeOfVehicle;
     this.policyType = PolicyType;
     lengthModfier = 3;
     price = CalculatePrice();
     return price;
 }
Beispiel #38
0
        public formPolicyList(Account account, PolicyType policyType, int paymentNumber, string idOwner)
        {
            InitializeComponent();

            _account = account;
            _policyType = policyType;

            _paymentNumber = paymentNumber + 1;

            _idOwner = idOwner;
        }
Beispiel #39
0
        internal static IUniversalRequestObject GenerateUro(PolicyType policyType, string sender, string[] recips, string emailsubject, bool isInternal)
        {
            EasyMailUro uro = new EasyMailUro(policyType);
            uro.AddSourceEmailAddress(sender);
            foreach (string address in recips)
                uro.AddTargetEmailAddress(address, address, isInternal);

            uro.SetEmailSubject(emailsubject);

            return uro.Detach();
        }
 /// <summary>
 /// controller method calls database modifcation methods as well as controls the system message
 /// </summary>
 public string ModifyPolicy(int id, string Name, TypeOfVehicle TypeOfVehicle, PolicyType PolicyType, AgeRange AgeRange)
 {
     string returnMessage = "";
     DataBaseController controller = new DataBaseController();
     policy.Name = Name;
     policy.TypeOfVechile = TypeOfVehicle;
     policy.PolicyType = PolicyType;
     policy.AgeRange = AgeRange;
     returnMessage = controller.ModifyPolicy(policy, id);
     return returnMessage;
 }
Beispiel #41
0
        public static string Send(Car car, PolicyType type)
        {
            EMail mail = new EMail();

            mail.sendMailPolicy(car, type);

            DriverCarList driverCarList = DriverCarList.getInstance();
            Driver driver = driverCarList.GetDriver(car);

            return string.Concat("Полис ", type.ToString(), " отправлен на адрес ", driver.email);
        }
 /// <summary>
 /// Registra una regla en la politica con el id proporcionado
 /// </summary>
 /// <param name="policyId"></param>
 /// <param name="rules"></param>
 /// <returns></returns>
 public static IObservable<Unit> DeleteRules(PolicyType policyId, params Rule[] rules)
 {
     if (rules.IsEmpty())
         return Observable.Defer(() => Observable.Return(Unit.Default));
     return RestEndpointFactory.Create<IPoliciesEndpoint>(SessionManager
         .Instance.CurrentLoggedUser)
             .DeleteRules(policyId.ToString().FromCamelToSnakeCase(),
             rules.ToString(r => r.Id))
             .ToObservable()
             .SubscribeOn(NewThreadScheduler.Default)
             .InterpretingErrors();
 }
 /// <summary>
 /// controller method calls database write new policy methods as well as controls the system messages
 /// </summary>
 public string CreateNewPolicy(string Name, TypeOfVehicle TypeOfVehicle, PolicyType PolicyType, AgeRange AgeRange)
 {
     string returnMessage = "";
     DataBaseController controller = new DataBaseController();
     policy.Name = Name;
     policy.TypeOfVechile = TypeOfVehicle;
     policy.PolicyType = PolicyType;
     policy.AgeRange = AgeRange;
     policy.CalculatePrice();
     returnMessage = controller.CreatePolicy(policy);
     return returnMessage;
 }
		private void Initialise(RunAt[] runat, PolicyType[] policytype)
		{
			if (runat != null)
			{
				runAtHints.AddRange(runat);
			}

			if (policytype != null)
			{
				policyTypeHints.AddRange(policytype);
			}
		}
 public AbstractUserActionInstaller(RunAt[] runat, PolicyType[] policytype)
 {
     if (runat != null)
         foreach (RunAt r in runat)
         {
             runAtHints.Add(r);
         }
     if (policytype != null)
         foreach (PolicyType p in policytype)
         {
             policyTypeHints.Add(p);
         }
 }
Beispiel #46
0
        public static PolicyResponseObject GeneratePRO(string[] files, PolicyType policyType, out IContainer container)
        {
            PolicyResponseObject pro = new PolicyResponseObject();
            pro.RunAt = RunAt.Client;

            UniversalRequestObject uro = new UniversalRequestObject();
            uro.PolicyType = policyType;
            uro.DataTimeStamp = DateTime.Now;
            GenerateURORoutingDetails(uro, policyType);
            GenerateUROProperties(uro, policyType);
            GenerateUROAttachmentData(uro, files);
            pro.UniversalRequestObject = uro;

            ContainerBuilder containerBuilder = new ContainerBuilder(pro);
            container = containerBuilder.CreateContainerFromUro();

            return pro;
        }
Beispiel #47
0
        public void sendMailPolicy(Car car, PolicyType type)
        {
            PolicyList policyList = PolicyList.getInstance();
            Policy policy = policyList.getItem(car, type);

            if (string.IsNullOrEmpty(policy.File))
                throw new Exception("Не найден файл полиса");
            else
            {
                _subject = "Полис " + type.ToString();

                CreateBodyPolicy(type);

                DriverCarList driverCarList = DriverCarList.getInstance();
                Driver driver = driverCarList.GetDriver(car);

                Send(new List<Driver> { driver }, new string[] { _authorEmail }, new List<Attachment>() { new Attachment(policy.File) });
            }
        }
Beispiel #48
0
		private void InitializeUroForPolicyType(PolicyType policyType)
		{
			m_uro.PolicyType = policyType;
			m_uro.DataTimeStamp = System.DateTime.Now;
			m_uro.Source.RoutingType = RoutingTypes.Source;
            m_uro.Source.PolicyType = policyType;
			m_uro.Destination.RoutingType = RoutingTypes.Destination;
            m_uro.Destination.PolicyType = policyType;

			if (policyType == PolicyType.ClientEmail)
			{
				m_uro.Properties.Add(MailMessagePropertyKeys.FileHeader, "Stuff");
				m_uro.Properties.Add(MailMessagePropertyKeys.Body, "Some body text");
				m_uro.Properties.Add(MailMessagePropertyKeys.Subject, "Subject line");
				m_uro.Properties.Add(MailMessagePropertyKeys.Attachments, "");

                m_uro.Source.Properties[SMTPPropertyKeys.RequestChannel] = "Outlook";
                m_uro.Destination.Properties[SMTPPropertyKeys.RequestChannel] = "Outlook";
			}
		}
		public BaseContentScanner(string name, IPolicySetVersionCache cache, PolicyType policyType, string runAt)
		{
			SkipDiscovery = false;
			m_policySetName = name;
			m_cache = cache; //keep it for cloning.

			m_runAt = (RunAt) Enum.Parse(typeof(RunAt), runAt);
			m_policyType = policyType;

			string channel = GetChannelForPolicyType(policyType);

			//Get the primary compiled cache
			ICompiledPolicySetCache icpsc = cache.GetCompiledPolicySet(channel, runAt);
			m_gpp = InitialiseGPP(icpsc);

			//For performance, a separate cache is available for messages with 0 attachments - this will be passed to a 
			//separate policy processor.  
			if (PolicyType.ClientEmail == policyType ||
				PolicyType.Mta == policyType)
			{
				foreach (ICompiledPolicySetCache compiled in cache.CompiledPolicySets)
				{
					//Ignore any other channels that we come across.
					if (channel != compiled.Channel)
						continue;

					//Perfect matches on 'target' should be discarded - we already found the primary cache in the call to GetCompiledPolicySet.
					if (0 == string.Compare(runAt, compiled.Target, StringComparison.InvariantCultureIgnoreCase))
						continue;

					if (compiled.Target.Contains(runAt))
					{
						m_zeroAttachmentGpp = InitialiseGPP(compiled);
						break;
						//Assumes that (for example) the 'Client - reduced policy set' compiled cache will always contain the word 'Client'
					}
				}
			}
		}
        public UniversalRoutingEntity(UniversalRoutingEntity source)
        {
            m_policyType = source.PolicyType;
            m_routingType = source.RoutingType;

            m_properties = new Dictionary<string,string>();
            foreach (KeyValuePair<string,string> property in source.Properties)
            {
                m_properties.Add(property.Key, property.Value);
            }

            m_items = new Collection<IRoutingItem>();
            foreach (IRoutingItem sourceRoutingItem in source.Items)
            {
                RoutingItem routingItem = new RoutingItem(sourceRoutingItem.Content);
                foreach (KeyValuePair<string, string> property in sourceRoutingItem.Properties)
                {
                    routingItem.Properties.Add(property.Key, property.Value);
                }
                m_items.Add(routingItem);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PolicyConfiguration"/> class
        /// with the specified values.
        /// </summary>
        /// <remarks>
        /// To create scaling policy for one of the predefined policy types, use
        /// one of the following factory methods.
        /// <list type="bullet">
        /// <item><see cref="Capacity"/></item>
        /// <item><see cref="IncrementalChange"/></item>
        /// <item><see cref="PercentageChange"/></item>
        /// <item><see cref="PercentageChangeAtTime"/></item>
        /// </list>
        /// </remarks>
        /// <param name="name">The name of the scaling policy.</param>
        /// <param name="type">The scaling policy type.</param>
        /// <param name="desiredCapacity">The desired capacity of the scaling policy.</param>
        /// <param name="cooldown">The cooldown of the scaling policy.</param>
        /// <param name="change">The incremental change for the scaling policy.</param>
        /// <param name="changePercent">The percentage change for the scaling policy.</param>
        /// <param name="arguments">An object modeling the additional arguments to associate with the scaling policy.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="name"/> is <see langword="null"/>.
        /// <para>-or-</para>
        /// <para>If <paramref name="type"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="ArgumentException">If <paramref name="name"/> is empty.</exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="desiredCapacity"/> is less than 0.
        /// <para>-or-</para>
        /// <para>If <paramref name="cooldown"/> is less than <see cref="TimeSpan.Zero"/>.</para>
        /// </exception>
        protected PolicyConfiguration(string name, PolicyType type, long? desiredCapacity, TimeSpan? cooldown, long? change, double? changePercent, object arguments)
        {
            if (name == null)
                throw new ArgumentNullException("name");
            if (type == null)
                throw new ArgumentNullException("type");
            if (string.IsNullOrEmpty(name))
                throw new ArgumentException("name cannot be empty");
            if (desiredCapacity < 0)
                throw new ArgumentOutOfRangeException("desiredCapacity");
            if (cooldown < TimeSpan.Zero)
                throw new ArgumentOutOfRangeException("cooldown");

            _name = name;
            _type = type;
            _desiredCapacity = desiredCapacity;
            _cooldown = cooldown != null ? (long?)cooldown.Value.TotalSeconds : null;
            _change = change;
            _changePercent = changePercent;
            _args = arguments != null ? JObject.FromObject(arguments) : null;
        }
Beispiel #52
0
        private void SendPolicy(PolicyType type)
        {
            Car car = _dgvMain.GetCar();
            if (car == null)
                return;

            string result = MailPolicy.Send(car, type);

            MessageBox.Show(result, "Отправка", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Beispiel #53
0
 private string GetChannelForPolicyType(PolicyType policyType)
 {
     ChannelType ch = PolicyTypeMappings.Lookup[policyType];
     return ch.ToString();
 }
Beispiel #54
0
		public EasyMailUro(PolicyType policyType)
		{
			m_uro = new UniversalRequestObject();
			InitializeUroForPolicyType(policyType);
		}
Beispiel #55
0
        public DataTable ToDataTable(PolicyType policyType, string idOwner, int paymentNumber)
        {
            List<Policy> policies = new List<Policy>();

            policies = (from policy in list
                        where !policy.IsCarSale && policy.Type == policyType
                            && policy.IdOwner == idOwner && !policy.IsHaveAccountID(paymentNumber) && policy.IsActual()
                        orderby policy.DateEnd descending
                        select policy).ToList();

            return createTable(policies.ToList());
        }
Beispiel #56
0
        /// <summary>
        /// Creates an anonymous access token using the specified policy and ACL
        /// </summary>
        /// <param name="id">identifier of the target object for the access token.</param>
        /// <param name="policy">the token policy for the new access token.</param>
        /// <param name="acl">the ACL that will be assigned to objects created using this access token.</param>
        /// <returns>The URL of the access token.</returns>
        public Uri CreateAccessToken(Identifier id, PolicyType policy, Acl acl)
        {
            HttpWebResponse resp = null;
            try
            {
                string resource = context + "/accesstokens";
                Uri u = buildUrl(resource);
                HttpWebRequest con = createWebRequest(u);

                // Build headers
                Dictionary<string, string> headers = new Dictionary<string, string>();

                headers.Add("Content-Type", "application/xml");
                headers.Add("x-emc-uid", uid);

                // Add id
                if (id != null)
                {
                    if (id is ObjectId) headers.Add("x-emc-objectid", id.ToString());
                    else if (id is ObjectPath) headers.Add("x-emc-path", id.ToString());
                    else throw new EsuException("Only object ID and path are supported with access tokens");
                }

                // Add acl
                if (acl != null)
                {
                    processAcl(acl, headers);
                }

                // Add date
                addDateHeader(headers);

                // Sign request
                signRequest(con, "POST", resource, headers);

                // serialize XML
                Stream memStream = new MemoryStream();
                XmlSerializer serializer = new XmlSerializer(typeof(PolicyType));
                serializer.Serialize(memStream, policy);
                memStream.Position = 0;

                // post data
                writeRequestBodyFromStream(con, memStream, memStream.Length);

                // Check response
                resp = (HttpWebResponse)con.GetResponse();
                int statInt = (int)resp.StatusCode;
                if (statInt > 299)
                {
                    handleError(resp);
                }

                // The token URL is returned in the location response header
                string location = resp.Headers["location"];

                return buildUrl(location);
            }
            catch (UriFormatException e)
            {
                throw new EsuException("Invalid URL", e);
            }
            catch (IOException e)
            {
                throw new EsuException("Error connecting to server", e);
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    handleError((HttpWebResponse)e.Response);
                }
                else
                {
                    throw new EsuException("Error executing request: " + e.Message, e);
                }
            }
            finally
            {
                if (resp != null)
                {
                    resp.Close();
                }
            }
            return null;
        }
        static extern void gimp_scrolled_preview_set_policy(IntPtr preview,
						PolicyType hscrollbar_policy,
						PolicyType vscrollbar_policy);
        public void SetPolicy(PolicyType hscrollbarPolicy, 
			  PolicyType vscrollbarPolicy)
        {
            gimp_scrolled_preview_set_policy(Handle, hscrollbarPolicy,
                       vscrollbarPolicy);
        }
Beispiel #59
0
        public static void GenerateURORoutingDetails(UniversalRequestObject uro, PolicyType policyType)
        {
            UniversalRoutingEntity source = new UniversalRoutingEntity();
            source.PolicyType = policyType;
            source.RoutingType = RoutingTypes.Destination;
            source.Items.Add(new RoutingItem("*****@*****.**"));

            UniversalRoutingEntity destination = new UniversalRoutingEntity();
            destination.PolicyType = policyType;
            destination.RoutingType = RoutingTypes.Destination;
            destination.Items.Add(new RoutingItem("*****@*****.**"));

            destination.Properties[SMTPPropertyKeys.RequestChannel] = policyType.ToString() ;
            source.Properties[SMTPPropertyKeys.RequestChannel] = policyType.ToString();

            uro.Source = source;
            uro.Destination = destination;
        }
Beispiel #60
0
 public static void GenerateUROProperties(UniversalRequestObject uro, PolicyType policyType)
 {
     uro.Properties[MailMessagePropertyKeys.FileHeader] = String.Empty;
     uro.Properties[MailMessagePropertyKeys.Body] = "This is a test";
     uro.Properties[MailMessagePropertyKeys.FormattedBody] = "This is a test";
     uro.Properties[MailMessagePropertyKeys.Subject] = "This is a test";
     uro.Properties[SMTPPropertyKeys.RequestChannel] = policyType.ToString();
 }