Exemple #1
0
        /// <summary>
        /// This is the lock free version of uninitilize so we can share
        /// it between the public method and error paths inside initialize.
        /// This should only be called inside a lock(initLock) block.
        /// </summary>
        private static void InternalUninitialize()
        {
            // Update this first so IsInitialized immediately begins returning
            // false.  Since this method should be protected externally by
            // a lock(initLock) we should be able to reset everything else
            // before the next init attempt.
            isFullyInitialized = false;

            LimitManager.UnInitialize();

            if (RuntimeClient.Current != null)
            {
                try
                {
                    RuntimeClient.Current.Reset();
                }
                catch (Exception) { }

                RuntimeClient.Current = null;

                try
                {
                    ClientProviderRuntime.UninitializeSingleton();
                }
                catch (Exception) { }
            }
            outsideRuntimeClient = null;
        }
        protected void AddLimitPolicy(int policyId)
        {
            Limit       limits         = null;
            Limit       limits2        = null;
            PolicyLimit objPolicyLimit = null;

            DataTable tbllimitGet          = HttpContext.Current.Session["Limit"] as DataTable;
            DataTable tblPolicylimitGet    = HttpContext.Current.Session["PolicyLimit"] as DataTable;
            DataTable tblAllPolicylimitGet = HttpContext.Current.Session["tblAllPolicylimit"] as DataTable;

            string type = string.Empty;

            for (int count = 0; count < tbllimitGet.Rows.Count; count++)
            {
                limits                  = new Limit();
                limits.LimitLetter      = tbllimitGet.Rows[count]["LimitLetter"].ToString();
                limits.LimitType        = Convert.ToInt32(tbllimitGet.Rows[count]["LimitType"].ToString());
                limits.LimitDescription = tbllimitGet.Rows[count]["LimitDescription"].ToString();
                limits.IsStatic         = Convert.ToBoolean(tbllimitGet.Rows[count]["IsStatic"].ToString());
                limits2                 = LimitManager.Save(limits);


                objPolicyLimit                        = new PolicyLimit();
                objPolicyLimit.PolicyID               = policyId;
                objPolicyLimit.LimitID                = limits2.LimitID;
                objPolicyLimit.LimitAmount            = Convert.ToDecimal(tblAllPolicylimitGet.Rows[count]["LimitAmount"].ToString());
                objPolicyLimit.LimitDeductible        = Convert.ToDecimal(tblAllPolicylimitGet.Rows[count]["LimitDeductible"].ToString());
                objPolicyLimit.ITV                    = Convert.ToDecimal(tblAllPolicylimitGet.Rows[count]["ITV"].ToString());
                objPolicyLimit.Reserve                = Convert.ToDecimal(tblAllPolicylimitGet.Rows[count]["Reserve"].ToString());
                objPolicyLimit.IsDeleted              = Convert.ToBoolean(tblAllPolicylimitGet.Rows[count]["IsDeleted"].ToString());
                objPolicyLimit.ApplyAcrossAllCoverage = Convert.ToBoolean(tblAllPolicylimitGet.Rows[count]["ApplyAcrossAllCoverage"].ToString());
                objPolicyLimit.ApplyTo                = tblAllPolicylimitGet.Rows[count]["ApplyTo"].ToString();
                PolicyLimitManager.Save(objPolicyLimit);
            }
        }
        protected void btnShowLossTemplate_Click(object sender, EventArgs e)
        {
            //int policyId = 0;

            ClaimManager objClaimManager = new ClaimManager();
            int          policyId        = Convert.ToInt32(hdnPolicyIdDetuctible.Value);

            List <Claim> lstClaim = objClaimManager.GetPolicyClaim(policyId);


            using (TransactionScope scope = new TransactionScope())
            {
                //delete all claim from claim limit
                foreach (var claim in lstClaim)
                {
                    int claimId = claim.ClaimID;
                    ClaimLimitManager.IsDeleted(claimId);
                }


                // delete limit,claimlimit,policylimit data which enter as loss details
                LimitManager.DeletePolicyLimit(policyId);

                //first get all limit
                List <Limit> objLimit = LimitManager.GetAllLimit(true);


                foreach (var limit in objLimit)
                {
                    //enter in
                    PolicyLimit objPolicyLimit = new PolicyLimit();
                    objPolicyLimit.PolicyID = policyId;
                    objPolicyLimit.LimitID  = limit.LimitID;
                    PolicyLimitManager.Save(objPolicyLimit);
                }

                //code for enter in all claim in claim limit
                foreach (var claim in lstClaim)
                {
                    foreach (var limit in objLimit)
                    {
                        ClaimLimit objClaimLimit = new ClaimLimit();
                        objClaimLimit.ClaimID = claim.ClaimID;
                        objClaimLimit.LimitID = limit.LimitID;
                        ClaimLimitManager.Save(objClaimLimit);
                    }
                }

                scope.Complete();
            }

            acrossAllCoverages.Enabled = true;
            coverageSpecific.Enabled   = true;
            txtDeductible.Enabled      = true;


            propertyLimits.bindData(policyId);
            //casualtyLimits.bindData(policyId);
        }
Exemple #4
0
 public static OrleansTaskScheduler CreateTestInstance(int maxActiveThreads)
 {
     return(new OrleansTaskScheduler(
                maxActiveThreads,
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(100),
                NodeConfiguration.ENABLE_WORKER_THREAD_INJECTION,
                LimitManager.GetDefaultLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS)));
 }
Exemple #5
0
    private void Start()
    {
        tempSpeed   = speed;
        gTile       = GameObject.Find("Generator").GetComponent <GenerateTile>();
        lManager    = GameObject.Find("LimitTimeUI").GetComponent <LimitManager>();
        aController = GetComponent <AudioController>();
        animator    = GetComponent <Animator>();

        GetComponentInChildren <Light>().enabled = false;
        GameObject.Find("Camera_2").GetComponent <Camera>().enabled = false;
    }
Exemple #6
0
 private static void Host_PostDelNumberInfo(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e)
 {
     try
     {
         int index = e.Arguments[0].IntValue;
         LimitManager.Del(index);
     }
     catch (Exception ex)
     {
         Log4Helper.ErrorInfo(ex.Message, ex);
         ViewCallFunction.ViewAlert(ex.Message);
     }
 }
 public static OrleansTaskScheduler CreateTestInstance(int maxActiveThreads, ICorePerformanceMetrics performanceMetrics, ILoggerFactory loggerFactory)
 {
     return(new OrleansTaskScheduler(
                maxActiveThreads,
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(100),
                NodeConfiguration.ENABLE_WORKER_THREAD_INJECTION,
                LimitManager.GetDefaultLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS),
                performanceMetrics,
                new ExecutorService(),
                loggerFactory));
 }
Exemple #8
0
 private static void Host_PostLimitNumberInfos(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e)
 {
     try
     {
         List <NumberLimit> infos = LimitManager.GetInfos();
         string             json  = Utility.JsonSerializerByArrayData(infos.ToArray());
         e.SetReturnValue(json);
     }
     catch (Exception ex)
     {
         Log4Helper.ErrorInfo(ex.Message, ex);
         ViewCallFunction.ViewAlert(ex.Message);
     }
 }
        private List <PolicyLimit> primeCasualtyLimits()
        {
            List <PolicyLimit> casualtyLimits = null;
            List <Limit>       limits         = null;

            limits = LimitManager.GetAll(LimitType.LIMIT_TYPE_CASUALTY);

            casualtyLimits = (from x in limits
                              select new PolicyLimit {
                LimitID = x.LimitID,
                Limit = x
            }).ToList <PolicyLimit>();

            return(casualtyLimits);
        }
Exemple #10
0
        private List <PolicyLimit> primePropertyLimits()
        {
            List <PolicyLimit> propertyLimits = null;
            List <Limit>       limits         = null;

            limits = LimitManager.GetAll(LimitType.LIMIT_TYPE_PROPERTY);

            propertyLimits = (from x in limits
                              select new PolicyLimit {
                LimitID = x.LimitID,
                Limit = x
            }).ToList <PolicyLimit>();

            return(propertyLimits);
        }
Exemple #11
0
 private static void Host_PostAddNumberInfo(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e)
 {
     try
     {
         string strNumber = e.Arguments[0].StringValue;
         int    number    = Utility.StrToInt(strNumber);
         bool   ret       = LimitManager.Add(number);
         e.SetReturnValue(ret);
     }
     catch (Exception ex)
     {
         Log4Helper.ErrorInfo(ex.Message, ex);
         ViewCallFunction.ViewAlert(ex.Message);
     }
 }
        private List <vw_ClaimLimit> primeCasualtyLimits()
        {
            List <Limit>         limits         = null;
            List <vw_ClaimLimit> casualtyLimits = null;

            limits = LimitManager.GetAll(LimitType.LIMIT_TYPE_CASUALTY);

            casualtyLimits = (from x in limits
                              select new vw_ClaimLimit {
                LimitID = x.LimitID,
                LimitLetter = x.LimitLetter,
                LimitType = x.LimitType,
                LimitDescription = x.LimitDescription
            }).ToList <vw_ClaimLimit>();

            return(casualtyLimits);
        }
        private List <vw_ClaimLimit> primePropertyLimits()
        {
            List <Limit>         limits         = null;
            List <vw_ClaimLimit> propertyLimits = null;

            limits = LimitManager.GetAll(LimitType.LIMIT_TYPE_PROPERTY);

            propertyLimits = (from x in limits
                              select new vw_ClaimLimit {
                LimitID = x.LimitID,
                LimitLetter = x.LimitLetter,
                LimitType = x.LimitType,
                LimitDescription = x.LimitDescription
            }).ToList <vw_ClaimLimit>();

            return(propertyLimits);
        }
Exemple #14
0
        private LimitValue GetMaxEnqueuedRequestLimit()
        {
            if (maxEnqueuedRequestsLimit != null)
            {
                return(maxEnqueuedRequestsLimit);
            }
            if (GrainInstanceType != null)
            {
                string limitName = CodeGeneration.GrainInterfaceData.IsStatelessWorker(GrainInstanceType)
                    ? LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER
                    : LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS;
                maxEnqueuedRequestsLimit = LimitManager.GetLimit(limitName); // Cache for next time
                return(maxEnqueuedRequestsLimit);
            }

            return(LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS));
        }
Exemple #15
0
        /// <summary>
        /// Initializes client runtime from client configuration object.
        /// </summary>
        private static void DoInternalInitialize(ClientConfiguration config, OutsideRuntimeClient runtimeClient = null)
        {
            if (IsInitialized)
            {
                return;
            }

            lock (initLock)
            {
                if (!IsInitialized)
                {
                    try
                    {
                        // this is probably overkill, but this ensures isFullyInitialized false
                        // before we make a call that makes RuntimeClient.Current not null
                        isFullyInitialized = false;
                        grainFactory       = new GrainFactory();

                        ClientProviderRuntime.InitializeSingleton(grainFactory);

                        if (runtimeClient == null)
                        {
                            runtimeClient = new OutsideRuntimeClient(config, grainFactory);
                        }
                        outsideRuntimeClient = runtimeClient;  // Keep reference, to avoid GC problems
                        outsideRuntimeClient.Start();

                        LimitManager.Initialize(config);


                        // this needs to be the last successful step inside the lock so
                        // IsInitialized doesn't return true until we're fully initialized
                        isFullyInitialized = true;
                    }
                    catch (Exception exc)
                    {
                        // just make sure to fully Uninitialize what we managed to partially initialize, so we don't end up in inconsistent state and can later on re-initialize.
                        Console.WriteLine("Initialization failed. {0}", exc);
                        InternalUninitialize();
                        throw;
                    }
                }
            }
        }
Exemple #16
0
        internal WorkItemGroup(OrleansTaskScheduler sched, ISchedulingContext schedulingContext)
        {
            masterScheduler      = sched;
            SchedulingContext    = schedulingContext;
            state                = WorkGroupStatus.Waiting;
            workItems            = new Queue <Task>();
            lockable             = new Object();
            totalItemsEnQueued   = 0;
            totalItemsProcessed  = 0;
            totalQueuingDelay    = TimeSpan.Zero;
            quantumExpirations   = 0;
            TaskRunner           = new ActivationTaskScheduler(this);
            MaxPendingItemsLimit = LimitManager.GetLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS);
            log = IsSystem ? TraceLogger.GetLogger("Scheduler." + Name + ".WorkItemGroup", TraceLogger.LoggerType.Runtime) : appLogger;

            if (StatisticsCollector.CollectShedulerQueuesStats)
            {
                queueTracking = new QueueTrackingStatistic("Scheduler." + SchedulingContext.Name);
                queueTracking.OnStartExecution();
            }

            if (StatisticsCollector.CollectPerWorkItemStats)
            {
                workItemGroupStatisticsNumber = SchedulerStatisticsGroup.RegisterWorkItemGroup(SchedulingContext.Name, SchedulingContext,
                                                                                               () =>
                {
                    var sb = new StringBuilder();
                    lock (lockable)
                    {
                        sb.Append("QueueLength = " + WorkItemCount);
                        sb.Append(String.Format(", State = {0}", state));
                        if (state == WorkGroupStatus.Runnable)
                        {
                            sb.Append(String.Format("; oldest item is {0} old", workItems.Count >= 0 ? workItems.Peek().ToString() : "null"));
                        }
                    }
                    return(sb.ToString());
                });
            }
        }
        protected void gvLimits2_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int          limitID         = Convert.ToInt32(e.CommandArgument);
            int          policyId        = Convert.ToInt32(Session["policyID"].ToString());
            ClaimManager objClaimManager = new ClaimManager();


            using (TransactionScope scope = new TransactionScope())
            {
                List <Claim> lstClaim = objClaimManager.GetPolicyClaim(policyId);
                foreach (var claim in lstClaim)
                {
                    int claimId = claim.ClaimID;
                    ClaimLimitManager.EditModeDeleteClaimLimit(limitID, claimId);
                }
                PolicyLimitManager.EditModeDeletePolicyLimit(limitID);
                LimitManager.EditModeDeleteLimit(limitID);
                scope.Complete();
            }
            Response.Redirect(Request.RawUrl);
            bindData(policyId);
        }
Exemple #18
0
 private static void Host_PostConfirmClientNumber(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e)
 {
     try
     {
         string          strClientNumber = e.Arguments[0].StringValue;
         int             clientNumber    = Utility.StrToInt(strClientNumber);
         List <UserInfo> infos           = UserManager.GetInfos();
         int             count           = infos.Where(w => w.UserNumber == clientNumber).Count();
         if (count == 0)
         {
             if (LimitManager.NumberInfos == null)
             {
                 LimitManager.GetInfos();
             }
             count = LimitManager.NumberInfos.Where(w => w.LimitNumber == clientNumber).Count();
         }
         e.SetReturnValue(count > 0);
     }
     catch (Exception ex)
     {
         Log4Helper.ErrorInfo(ex.Message, ex);
         ViewCallFunction.ViewAlert(ex.Message);
     }
 }
 public LimitInfoController(LimitManager limit)
 {
     _limitManager = limit;
 }
Exemple #20
0
 public OrleansTaskScheduler(int maxActiveThreads)
     : this(maxActiveThreads, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100),
            NodeConfiguration.INJECT_MORE_WORKER_THREADS, LimitManager.GetDefaultLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS))
 {
 }
Exemple #21
0
        internal Silo(string name, SiloType siloType, ClusterConfiguration config, ILocalDataStore keyStore)
        {
            SystemStatus.Current = SystemStatus.Creating;

            CurrentSilo = this;

            var startTime = DateTime.UtcNow;

            this.siloType = siloType;
            Name          = name;

            siloTerminatedEvent = new ManualResetEvent(false);

            OrleansConfig = config;
            globalConfig  = config.Globals;
            config.OnConfigChange("Defaults", () => nodeConfig = config.GetConfigurationForNode(name));

            if (!TraceLogger.IsInitialized)
            {
                TraceLogger.Initialize(nodeConfig);
            }

            config.OnConfigChange("Defaults/Tracing", () => TraceLogger.Initialize(nodeConfig, true), false);
            LimitManager.Initialize(nodeConfig);
            ActivationData.Init(config);
            StatisticsCollector.Initialize(nodeConfig);
            SerializationManager.Initialize(globalConfig.UseStandardSerializer);
            initTimeout = globalConfig.MaxJoinAttemptTime;
            if (Debugger.IsAttached)
            {
                initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), globalConfig.MaxJoinAttemptTime);
                stopTimeout = initTimeout;
            }

            IPEndPoint here       = nodeConfig.Endpoint;
            int        generation = nodeConfig.Generation;

            if (generation == 0)
            {
                generation            = SiloAddress.AllocateNewGeneration();
                nodeConfig.Generation = generation;
            }
            TraceLogger.MyIPEndPoint = here;
            logger = TraceLogger.GetLogger("Silo", TraceLogger.LoggerType.Runtime);
            logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing {0} silo on {1} at {2}, gen {3} --------------", siloType, nodeConfig.DNSHostName, here, generation);
            logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0} with runtime Version='{1}' Config= \n{2}", name, RuntimeVersion.Current, config.ToString(name));

            if (keyStore != null)
            {
                // Re-establish reference to shared local key store in this app domain
                LocalDataStoreInstance.LocalDataStore = keyStore;
            }
            healthCheckParticipants = new List <IHealthCheckParticipant>();

            BufferPool.InitGlobalBufferPool(globalConfig);
            PlacementStrategy.Initialize(globalConfig);

            UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnobservedExceptionHandler);
            AppDomain.CurrentDomain.UnhandledException +=
                (obj, ev) => DomainUnobservedExceptionHandler(obj, (Exception)ev.ExceptionObject);

            typeManager = new GrainTypeManager(here.Address.Equals(IPAddress.Loopback));

            // Performance metrics
            siloStatistics = new SiloStatisticsManager(globalConfig, nodeConfig);
            config.OnConfigChange("Defaults/LoadShedding", () => siloStatistics.MetricsTable.NodeConfig = nodeConfig, false);

            // The scheduler
            scheduler = new OrleansTaskScheduler(globalConfig, nodeConfig);
            healthCheckParticipants.Add(scheduler);

            // Initialize the message center
            var mc = new MessageCenter(here, generation, globalConfig, siloStatistics.MetricsTable);

            if (nodeConfig.IsGatewayNode)
            {
                mc.InstallGateway(nodeConfig.ProxyGatewayEndpoint);
            }

            messageCenter = mc;

            // Now the router/directory service
            // This has to come after the message center //; note that it then gets injected back into the message center.;
            localGrainDirectory = new LocalGrainDirectory(this);

            // Now the activation directory.
            // This needs to know which router to use so that it can keep the global directory in synch with the local one.
            activationDirectory = new ActivationDirectory();

            // Now the consistent ring provider
            RingProvider = GlobalConfig.UseVirtualBucketsConsistentRing ?
                           (IConsistentRingProvider) new VirtualBucketsRingProvider(SiloAddress, GlobalConfig.NumVirtualBucketsConsistentRing)
                : new ConsistentRingProvider(SiloAddress);

            Action <Dispatcher> setDispatcher;

            catalog = new Catalog(Constants.CatalogId, SiloAddress, Name, LocalGrainDirectory, typeManager, scheduler, activationDirectory, config, out setDispatcher);
            var dispatcher = new Dispatcher(scheduler, messageCenter, catalog, config);

            setDispatcher(dispatcher);

            RuntimeClient.Current = new InsideRuntimeClient(
                dispatcher,
                catalog,
                LocalGrainDirectory,
                SiloAddress,
                config,
                RingProvider,
                typeManager);
            messageCenter.RerouteHandler       = InsideRuntimeClient.Current.RerouteMessage;
            messageCenter.SniffIncomingMessage = InsideRuntimeClient.Current.SniffIncomingMessage;
            messageCenter.ClientDropHandler    = grainIds =>
            {
                catalog.DeleteGrainsLocal(grainIds).Ignore();
                scheduler.RunOrQueueAction(() =>
                {
                    // Consider: batch delete
                    foreach (var id in grainIds)
                    {
                        LocalGrainDirectory.DeleteGrain(id).Ignore();
                    }
                }, catalog.SchedulingContext);
            };

            siloStatistics.MetricsTable.Scheduler           = scheduler;
            siloStatistics.MetricsTable.ActivationDirectory = activationDirectory;
            siloStatistics.MetricsTable.ActivationCollector = catalog.ActivationCollector;
            siloStatistics.MetricsTable.MessageCenter       = messageCenter;

            DeploymentLoadPublisher.CreateDeploymentLoadPublisher(this, globalConfig);
            PlacementDirectorsManager.CreatePlacementDirectorsManager(globalConfig);

            // Now the incoming message agents
            incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, dispatcher);
            incomingPingAgent   = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, dispatcher);
            incomingAgent       = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, dispatcher);

            membershipFactory = new MembershipFactory();
            reminderFactory   = new LocalReminderServiceFactory();

            SystemStatus.Current = SystemStatus.Created;

            StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME,
                                              () => TraceLogger.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs.

            TestHookup = new TestHookups(this);

            logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            _bw.ReportProgress(0, "init...");


            //宣告
            Dictionary <fbUser, int?> tmp_FriendList = new Dictionary <fbUser, int?>();
            //HashSet<fbUser> tmp_FriendList = new HashSet<fbUser>();
            int    p          = 0;
            string profile_id = e.Argument as string;

            //初始化目標使用者的Class
            //TGTfbUser = new targetFBUser(profile_id, FBCrawler.getFBNameByUid(profile_id));

            //找出為目標User的CoverPhoto點讚的User集合
            _bw.ReportProgress(0, "Getting Entry Friend List...");

            HashSet <fbUser> userWhoLikesCoverPhoto = FBCrawler.getEntryFriendList(profile_id);

            //反查, 並初始化目標的好友清單集合
            foreach (fbUser user in userWhoLikesCoverPhoto)
            {
                p++;
                _bw.ReportProgress(0, "Checking Friends [" + p + " / " + userWhoLikesCoverPhoto.Count + "] - " + user.profile_id);

                if (!LimitManager.isVaild())
                {
                    _bw.ReportProgress(0, "次數已達上限");
                    break;
                }

                //排除目標自己按讚
                if (user.profile_id.Equals(profile_id))
                {
                    continue;
                }

                //加入處裡順序
                if (!TGTfbUser.processList.Contains(user.profile_id))
                {
                    TGTfbUser.processList.Add(user.profile_id);
                }

                //加入統計
                if (!TGTfbUser.dataList.Contains(user.profile_id))
                {
                    TGTfbUser.dataList.Add(user.profile_id, countHasFriend(user.profile_id, TGTfbUser.checkedFriendList) + " / " + TGTfbUser.checkedFriendList.Count.ToString());
                }

                user.friends          = FBCrawler.getFriendList(user.profile_id);
                user.friends_isCached = (user.friends.Count > 0) ? true : false;
                user.friends_isPublic = (user.friends.Count > 0) ? true : false;
                user.distance         = 1;

                //加入Precision and recall
                if (TGTfbUser.answerFriendList.Count > 0)
                {
                    Precision_Recall.addPrecisionRecallItem(LimitManager.Count.getFriendList, user, TGTfbUser.answerFriendList, (user.friends.Count > 0));
                }

                if (user.friends_isPublic)
                {
                    //好友名單可見, 反查目標
                    if (user.hasFriend(profile_id))
                    {
                        //有, 加入[確定清單]
                        TGTfbUser.checkedFriendList.Add(user);
                        //TGTfbUser.dataList.Add(user.profile_id, "-" );
                    }
                    else
                    {
                        //沒有, 丟棄
                        TGTfbUser.dropFriendList.Add(user);
                        //TGTfbUser.dataList.Add(user.profile_id, "-");
                        continue;

                        //沒有, 但是很可能認識目標, 加入[可能清單]
                        //過濾重複

                        /*if (TGTfbUser.IsInFriendList(user.profile_id, TGTfbUser.possibleFriendList)) continue;
                         * TGTfbUser.possibleFriendList.Add(user);*/
                    }
                }
                else
                {
                    //好友名單不可見, 加入[可能清單], 這些人機率很大
                    //過濾重複
                    if (TGTfbUser.IsInFriendList(user.profile_id, TGTfbUser.possibleFriendList))
                    {
                        continue;
                    }
                    TGTfbUser.possibleFriendList.Add(user);

                    TGTfbUser.possibleFriendListScore.Add(user.profile_id, "1");
                    // [加入時該User的層數](1>2>3...) |
                }
            }

            //新增方法 - 分別比對第一層確認的人之好友名單
            //確認"確定是好友的User"是有結果的
            if (TGTfbUser.checkedFriendList.Count > 0 && flagMutualFriends)
            {
                HashSet <fbUser> userInMutualFriends = new HashSet <fbUser>();
                HashSet <string> uidInMutualFriends  = new HashSet <string>();
                HashSet <string> uidUsedList         = new HashSet <string>();

                p = 0;
                foreach (fbUser user in TGTfbUser.checkedFriendList)
                {
                    p++;
                    _bw.ReportProgress(0, "Checking Mutual Friends [" + p + " / " + TGTfbUser.checkedFriendList.Count + "] - " + user.profile_id);

                    if ((!user.profile_id.Equals(profile_id)) && (!uidUsedList.Contains(user.profile_id)))
                    {
                        HashSet <fbUser> tmp = FBCrawler.getMutualFriendList(profile_id, user.profile_id);
                        if (tmp.Count == 0)
                        {
                            continue;
                        }
                        foreach (fbUser new_user in tmp)
                        {
                            if (TGTfbUser.IsInFriendList(new_user.profile_id, userInMutualFriends))
                            {
                                continue;
                            }
                            if (uidInMutualFriends.Contains(new_user.profile_id))
                            {
                                continue;
                            }

                            //加入處裡順序
                            if (!TGTfbUser.processList.Contains(new_user.profile_id))
                            {
                                TGTfbUser.processList.Add(new_user.profile_id);
                            }

                            new_user.friends          = FBCrawler.getFriendList(user.profile_id);
                            new_user.friends_isCached = (user.friends.Count > 0) ? true : false;
                            new_user.friends_isPublic = (user.friends.Count > 0) ? true : false;
                            new_user.distance         = 1;

                            userInMutualFriends.Add(new_user);
                            uidInMutualFriends.Add(new_user.profile_id);
                        }
                        uidUsedList.Add(user.profile_id);
                        _bw.ReportProgress(0, "Checking Mutual Friends [" + p + " / " + TGTfbUser.checkedFriendList.Count + "] - " + user.profile_id + " (" + userInMutualFriends.Count + ")");
                        System.Threading.Thread.Sleep(3000);
                    }
                }

                foreach (fbUser user in userInMutualFriends)
                {
                    if (user.profile_id.Equals(profile_id))
                    {
                        continue;
                    }
                    //已經在目標的確定好友名單集合中
                    if (TGTfbUser.IsInFriendList(user.profile_id, TGTfbUser.checkedFriendList))
                    {
                        continue;
                    }
                    TGTfbUser.possibleFriendList.RemoveWhere(u => u.profile_id.Equals(user.profile_id));

                    //加入統計
                    if (!TGTfbUser.dataList.Contains(user.profile_id))
                    {
                        TGTfbUser.dataList.Add(user.profile_id, countHasFriend(user.profile_id, TGTfbUser.checkedFriendList) + " / " + TGTfbUser.checkedFriendList.Count.ToString());
                    }

                    TGTfbUser.checkedFriendList.Add(user);
                }
            }

            //確認"確定是好友的User"是有結果的
            if (TGTfbUser.checkedFriendList.Count > 0)
            {
                int loop = 1;
                while (loop <= layer || FBCrawler.flag_cancel)
                {
                    //第一層
                    if (loop == 1)
                    {
                        //逐一檢查"確定是好友的User"的好友名單
                        p = 0;
                        foreach (fbUser user in TGTfbUser.checkedFriendList)
                        {
                            p++;
                            _bw.ReportProgress(0, "逐一檢查與目標確定是好友的User的好友名單 (loop:" + loop.ToString() + ")[" + p + "/" + TGTfbUser.checkedFriendList.Count + "] - " + user.profile_id);

                            if (!LimitManager.isVaild())
                            {
                                _bw.ReportProgress(0, "次數已達上限");
                                tmp_FriendList.Clear();
                                break;
                            }

                            //排除目標
                            if (user.profile_id.Equals(profile_id))
                            {
                                continue;
                            }

                            //加入處裡順序
                            if (!TGTfbUser.processList.Contains(user.profile_id))
                            {
                                TGTfbUser.processList.Add(user.profile_id);
                            }

                            user.friends          = FBCrawler.getFriendList(user.profile_id);
                            user.friends_isCached = (user.friends.Count > 0) ? true : false;
                            user.friends_isPublic = (user.friends.Count > 0) ? true : false;

                            foreach (String uid in user.friends)
                            {
                                //排除目標
                                if (uid.Equals(profile_id))
                                {
                                    continue;
                                }
                                //已經在目標的確定好友名單集合中
                                if (TGTfbUser.IsInFriendList(uid, TGTfbUser.checkedFriendList))
                                {
                                    continue;
                                }
                                //已經在暫存好友名單集合中
                                if (TGTfbUser.IsInFriendList(uid, new HashSet <fbUser>(tmp_FriendList.Keys)))
                                {
                                    continue;
                                }

                                //加入暫存好友名單集合, 並計算該使用者在"確定是好友的User"好友名單中的次數
                                tmp_FriendList.Add(new fbUser(uid, FBCrawler.getFBNameByUid(uid), loop), countHasFriend(uid, TGTfbUser.checkedFriendList));
                            }
                        }
                        //排序
                        tmp_FriendList = tmp_FriendList.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
                    }
                    //第一層以上
                    else if (loop > 1)
                    {
                        //逐一檢查在暫存好友名單集合內的好友
                        p = 0;
                        while (tmp_FriendList.Count > 0 || FBCrawler.flag_cancel)
                        {
                            if (!LimitManager.isVaild())
                            {
                                _bw.ReportProgress(0, "次數已達上限");
                                tmp_FriendList.Clear();
                                break;
                            }

                            fbUser user = tmp_FriendList.Keys.ElementAt(0); //取得這次檢查的人
                            //加入處裡順序
                            if (!TGTfbUser.processList.Contains(user.profile_id))
                            {
                                TGTfbUser.processList.Add(user.profile_id);
                            }

                            if (!TGTfbUser.dataList.Contains(user.profile_id))
                            {
                                TGTfbUser.dataList.Add(user.profile_id, tmp_FriendList[user].Value.ToString() + " / " + TGTfbUser.checkedFriendList.Count.ToString());
                            }

                            //加入Precision and recall
                            if (TGTfbUser.answerFriendList.Count > 0)
                            {
                                Precision_Recall.addPrecisionRecallItem(LimitManager.Count.getFriendList, user, TGTfbUser.answerFriendList, (user.friends.Count > 0));
                            }

                            tmp_FriendList.Remove(tmp_FriendList.Keys.ElementAt(0)); //移除這次檢查的人

                            p++;
                            _bw.ReportProgress(0, "逐一檢查在暫存好友名單集合內的好友 (loop:" + loop.ToString() + ")[" + p + "/" + (tmp_FriendList.Count + p - 1) + "] - " + user.profile_id);

                            //排除目標
                            if (user.profile_id.Equals(profile_id))
                            {
                                continue;
                            }

                            user.friends          = FBCrawler.getFriendList(user.profile_id);
                            user.friends_isCached = (user.friends.Count > 0) ? true : false;
                            user.friends_isPublic = (user.friends.Count > 0) ? true : false;

                            if (user.friends_isPublic)
                            {
                                //好友名單可見, 反查目標
                                if (user.hasFriend(profile_id))
                                {
                                    //有, 加入[確定清單]
                                    //檢查重複
                                    if (!TGTfbUser.IsInFriendList(user.profile_id, TGTfbUser.checkedFriendList))
                                    {
                                        user.distance = 1;
                                        TGTfbUser.checkedFriendList.Add(user);

                                        //新增方法 - 分別比對第一層確認的人之好友名單
                                        if (flagMutualFriends)
                                        {
                                            HashSet <fbUser> mlist = FBCrawler.getMutualFriendList(profile_id, user.profile_id);
                                            if (mlist.Count > 0)
                                            {
                                                foreach (fbUser new_user in mlist)
                                                {
                                                    if (new_user.profile_id.Equals(profile_id))
                                                    {
                                                        continue;
                                                    }
                                                    if (TGTfbUser.IsInFriendList(new_user.profile_id, TGTfbUser.checkedFriendList))
                                                    {
                                                        continue;
                                                    }

                                                    TGTfbUser.possibleFriendList.RemoveWhere(u => u.profile_id.Equals(new_user.profile_id));

                                                    //加入處裡順序
                                                    if (!TGTfbUser.processList.Contains(new_user.profile_id))
                                                    {
                                                        TGTfbUser.processList.Add(new_user.profile_id);
                                                    }

                                                    //加入統計
                                                    if (!TGTfbUser.dataList.Contains(user.profile_id))
                                                    {
                                                        TGTfbUser.dataList.Add(user.profile_id, countHasFriend(user.profile_id, TGTfbUser.checkedFriendList) + " / " + TGTfbUser.checkedFriendList.Count.ToString());
                                                    }

                                                    new_user.friends          = FBCrawler.getFriendList(user.profile_id);
                                                    new_user.friends_isCached = (user.friends.Count > 0) ? true : false;
                                                    new_user.friends_isPublic = (user.friends.Count > 0) ? true : false;
                                                    new_user.distance         = 1;

                                                    TGTfbUser.checkedFriendList.Add(new_user);
                                                }
                                            }
                                        }

                                        //已確認的好友名單有變動, 重新計算並排序
                                        foreach (fbUser tmp in new HashSet <fbUser>(tmp_FriendList.Keys))
                                        {
                                            if (user.hasFriend(tmp.profile_id))
                                            {
                                                tmp_FriendList[tmp] += 1;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //沒有, 丟棄
                                    TGTfbUser.dropFriendList.Add(user);
                                    continue;

                                    //沒有, 檢查層數限制, 加入擴散對象 或 丟棄

                                    /*if ((user.distance + 1) >= layer)
                                     * {
                                     *  //層數限制, 丟棄
                                     *  continue;
                                     * }
                                     * else
                                     * {
                                     *  //加入擴散對象
                                     *  user.distance += 1;
                                     *  if (!TGTfbUser.IsInFriendList(user.profile_id, new HashSet<fbUser>(tmp_FriendList.Keys)))
                                     *  {
                                     *      tmp_FriendList.Add(user, calcPoint(user.profile_id, TGTfbUser.checkedFriendList));
                                     *  }
                                     * }*/
                                }
                            }
                            else
                            {
                                //好友名單不可見, 加入[可能清單], 這些人機率不高
                                user.distance += 1;
                                if (TGTfbUser.IsInFriendList(user.profile_id, TGTfbUser.possibleFriendList))
                                {
                                    continue;
                                }
                                TGTfbUser.possibleFriendList.Add(user);
                                TGTfbUser.possibleFriendListScore.Add(user.profile_id, loop.ToString());
                            }

                            //重新排序
                            tmp_FriendList = tmp_FriendList.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
                        }
                    }

                    loop++;
                }
            }
            else
            {
                //沒有結果...死路!
            }

            p = 0;
            foreach (fbUser user in TGTfbUser.possibleFriendList)
            {
                p++;
                _bw.ReportProgress(0, "Calc F's FList Score[" + p + "/" + TGTfbUser.possibleFriendList.Count + "] - " + user.profile_id);
                try
                {
                    if (TGTfbUser.possibleFriendListScore[user.profile_id] == null)
                    {
                        TGTfbUser.possibleFriendListScore.Add(user.profile_id, calcScore(user.profile_id, -1, TGTfbUser.checkedFriendList));
                    }
                    else
                    {
                        string tmp   = TGTfbUser.possibleFriendListScore[user.profile_id].ToString();
                        string score = calcScore(user.profile_id, Int16.Parse(tmp), TGTfbUser.checkedFriendList);
                        TGTfbUser.possibleFriendListScore[user.profile_id] = score;
                        TGTfbUser.possibleFriendSortedList.Add(user, (Int16.Parse(tmp) > 1 ? Int16.Parse(score.Substring(score.IndexOf('|') + 1)) : 100));
                    }
                }
                catch (Exception) { }
            }

            _bw.ReportProgress(50, "Sorting Possible Friend List...");
            //排序
            TGTfbUser.possibleFriendSortedList = TGTfbUser.possibleFriendSortedList.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

            _bw.ReportProgress(100, "Finished!!");
            flagFinished = true;
        }
Exemple #23
0
        public void saveLimits(int policyID)
        {
            int policyLimitID = 0;
            int limitID       = 0;
            //int claimLimitID = 0;
            int myClaimID      = 0;
            int myClaimLimitID = 0;
            int myLimitId      = 0;                 //anything prefaced with "my" is new; OC

            myClaimID = SessionHelper.getClaimID(); //Convert.ToInt32(Session["ClaimID"]);
            PolicyLimit limit         = null;
            PolicyLimit myPolicyLimit = null;
            Limit       myLimit       = null;
            // ClaimLimit myClaimLimit = null;
            //added new; OC 9/11/2014: put in place to add new row to the policy limits grid. took the old 3 column one out.
            //crete the footer controls available for use here :OC 9/12/14
            WebTextEditor    txtMyCoverage         = (WebTextEditor)gvLimits.FooterRow.FindControl("txtMyCoverage");
            WebTextEditor    txtMyDescription      = (WebTextEditor)gvLimits.FooterRow.FindControl("txtMyDescription");
            WebNumericEditor txtMyLimit            = (WebNumericEditor)gvLimits.FooterRow.FindControl("txtMyLimit");
            WebNumericEditor txtMyDeductible       = (WebNumericEditor)gvLimits.FooterRow.FindControl("txtMyDeductible");
            WebTextEditor    txtMyCATDeductible    = (WebTextEditor)gvLimits.FooterRow.FindControl("txtMyCATDeductible");
            WebDropDown      ddlMySettlementType   = (WebDropDown)gvLimits.FooterRow.FindControl("ddlMySettlementType");
            WebPercentEditor txtMyCoInsuranceLimit = (WebPercentEditor)gvLimits.FooterRow.FindControl("txtMyCoInsuranceLimit");
            WebPercentEditor txtMyITV           = (WebPercentEditor)gvLimits.FooterRow.FindControl("txtMyITV");
            WebNumericEditor txtMyReserve       = (WebNumericEditor)gvLimits.FooterRow.FindControl("txtMyReserve");
            WebTextEditor    txtMyWHDeductible  = (WebTextEditor)gvLimits.FooterRow.FindControl("txtMyWHDeductible");
            WebNumericEditor txtMyLossAmountACV = (WebNumericEditor)gvLimits.FooterRow.FindControl("txtMyLossAmountACV");
            WebNumericEditor txtMyLossAmountRCV = (WebNumericEditor)gvLimits.FooterRow.FindControl("txtMyLossAmountRCV");
            WebNumericEditor txtMyOverage       = (WebNumericEditor)gvLimits.FooterRow.FindControl("txtMyOverage");

            if (txtMyCoverage.Text != "")//TODO: change this condition to something more stable (checkbox or something)
            {
                //LIMIT TABLE STUFF
                myLimit                  = new Limit();
                myLimit.LimitLetter      = txtMyCoverage.Text;
                myLimit.LimitType        = 1;//need to change to user input and create text boxes
                myLimit.LimitDescription = txtMyDescription.Text;
                myLimit.IsStatic         = false;
                try
                {
                    LimitManager.Save(myLimit);
                }
                catch (Exception ex)
                {
                    Core.EmailHelper.emailError(ex);
                }

                var a = LimitManager.GetLatest(); //need to get the lastly created limit id from the insert we just did above
                myLimitId = Convert.ToInt32(a.LimitID);

                //CLAIM LIMIT STUFF
                //myClaimLimit = new ClaimLimit();
                //myClaimLimit.LimitID = myLimitId;
                //myClaimLimit.ClaimID = myClaimID;
                //myClaimLimit.PolicyID = policyID;
                //myClaimLimit.LossAmountACV = txtMyLossAmountACV.Value == null ? 0 : Convert.ToDecimal(txtMyLossAmountACV.Text);
                //myClaimLimit.LossAmountRCV = txtMyLossAmountRCV.Value == null ? 0 : Convert.ToDecimal(txtMyLossAmountRCV.Text);
                //myClaimLimit.OverageAmount = txtMyOverage.Value == null ? 0 : Convert.ToDecimal(txtMyOverage.Text);
                //try
                //{
                //    ClaimLimitManager.Save(myClaimLimit);
                //}
                //catch (Exception ex)
                //{

                //}
                //var b = ClaimLimitManager.GetLatest();
                //myClaimLimitID = Convert.ToInt32(b.ClaimLimitID);

                //POLICY LIMIT STUFF
                myPolicyLimit                 = new PolicyLimit();
                myPolicyLimit.PolicyID        = policyID;
                myPolicyLimit.LimitID         = myLimitId;
                myPolicyLimit.ClaimLimitID    = myClaimLimitID;
                myPolicyLimit.LimitAmount     = txtMyLimit.Value == null ? 0 : Convert.ToDecimal(txtMyLimit.Text); //= Convert.ToDecimal(txtMyLimit.Text);
                myPolicyLimit.LimitDeductible = txtMyDeductible.Value == null ? 0 : Convert.ToDecimal(txtMyDeductible.Text);
                myPolicyLimit.CATDeductible   = txtMyCATDeductible.Text;
                if (ddlMySettlementType.SelectedItemIndex > 0)
                {
                    myPolicyLimit.ApplyTo = ddlMySettlementType.SelectedItem.Text;
                }
                else
                {
                    myPolicyLimit.ApplyTo = null;
                }

                myPolicyLimit.ConInsuranceLimit = Convert.ToDecimal(txtMyCoInsuranceLimit.Value);
                myPolicyLimit.ITV                = Convert.ToDecimal(txtMyITV.Value);
                myPolicyLimit.Reserve            = Convert.ToDecimal(txtMyReserve.Value);
                myPolicyLimit.WindHailDeductible = txtMyWHDeductible.Text;
                myPolicyLimit.LossAmountACV      = txtMyLossAmountACV.Value == null ? 0 : Convert.ToDecimal(txtMyLossAmountACV.Text);
                myPolicyLimit.LossAmountRCV      = txtMyLossAmountRCV.Value == null ? 0 : Convert.ToDecimal(txtMyLossAmountRCV.Text);
                myPolicyLimit.OverageAmount      = txtMyOverage.Value == null ? 0 : Convert.ToDecimal(txtMyOverage.Text);

                try
                {
                    PolicyLimitManager.Save(myPolicyLimit);
                }
                catch (Exception ex)
                {
                }
            }

            else //run the regular stuff it was doing before
            {
                //original code
                foreach (GridViewRow row in gvLimits.Rows)
                {
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        //Label txtLimitLetter = row.FindControl("txtLimitLetter") as Label;
                        //Label txtDescription = row.FindControl("txtDescription") as Label;
                        WebNumericEditor txtLimit            = row.FindControl("txtLimit") as WebNumericEditor;
                        WebNumericEditor txtDeductible       = row.FindControl("txtDeductible") as WebNumericEditor;
                        WebTextEditor    txtWHDeductible     = row.FindControl("txtWHDeductible") as WebTextEditor;//new
                        WebTextEditor    txtCATDeductible    = row.FindControl("txtCATDeductible") as WebTextEditor;
                        WebTextEditor    txtSettlementType   = row.FindControl("txtSettlementType") as WebTextEditor;
                        WebNumericEditor txtCoInsuranceLimit = row.FindControl("txtCoInsuranceLimit") as WebNumericEditor;
                        WebDropDown      ddlSettlementType   = row.FindControl("ddlSettlementType") as WebDropDown;
                        WebPercentEditor txtITV           = row.FindControl("txtITV") as WebPercentEditor;           //new
                        WebNumericEditor txtReserve       = row.FindControl("txtReserve") as WebNumericEditor;       //new
                        WebNumericEditor txtLossAmountACV = row.FindControl("txtLossAmountACV") as WebNumericEditor; //new
                        WebNumericEditor txtLossAmountRCV = row.FindControl("txtLossAmountRCV") as WebNumericEditor; //new
                        WebNumericEditor txtOverage       = row.FindControl("txtOverage") as WebNumericEditor;       //new
                        policyLimitID = (int)gvLimits.DataKeys[row.RowIndex].Values[0];
                        limitID       = (int)gvLimits.DataKeys[row.RowIndex].Values[1];

                        //claimLimitID = (int)gvLimits.DataKeys[row.RowIndex].Values[2];
                        //claimLimitID = (int)gvLimits.DataKeys[row.RowIndex].Values[2];
                        //if ((txtLossAmountACV.Text != "" ||
                        //    txtLossAmountRCV.Text != "" ||
                        //    txtOverage.Text != "" )&&
                        //   ( txtOverage.Text != "0.00" ||
                        //    txtLossAmountRCV.Text != "0.00" ||
                        //    txtLossAmountACV.Text != "0.00"))
                        //{
                        //CLAIM LIMIT STUFF
                        //myClaimLimit = new ClaimLimit();
                        //myClaimLimit.ClaimLimitID = claimLimitID;
                        //myClaimLimit.LimitID = limitID;
                        //myClaimLimit.ClaimID = myClaimID;
                        //myClaimLimit.PolicyID = policyID;
                        //myClaimLimit.PolicyLimitID = policyLimitID;
                        //myClaimLimit.LossAmountACV = txtLossAmountACV.Value == null ? 0 : Convert.ToDecimal(txtLossAmountACV.Text);
                        //myClaimLimit.LossAmountRCV = txtLossAmountRCV.Value == null ? 0 : Convert.ToDecimal(txtLossAmountRCV.Text);
                        //myClaimLimit.OverageAmount = txtOverage.Value == null ? 0 : Convert.ToDecimal(txtOverage.Text);
                        //try
                        //{
                        //    ClaimLimitManager.Save(myClaimLimit);
                        //}
                        //catch (Exception ex)
                        //{

                        //}
                        ////    var b = ClaimLimitManager.GetLatest2(policyLimitID);
                        ////    myClaimLimitID = Convert.ToInt32(b.ClaimLimitID);
                        ////}
                        if (policyLimitID == 0)
                        {
                            limit = new PolicyLimit();
                        }
                        else
                        {
                            limit = PolicyLimitManager.Get(policyLimitID);
                        }

                        limit.PolicyLimitID = policyLimitID;
                        limit.LimitID       = limitID;
                        //limit.ClaimLimitID = claimLimitID;
                        limit.PolicyID           = policyID;
                        limit.LimitAmount        = txtLimit.Value == null ? 0 : Convert.ToDecimal(txtLimit.Value);
                        limit.LimitDeductible    = txtDeductible.Value == null ? 0 : Convert.ToDecimal(txtDeductible.Value);
                        limit.CATDeductible      = txtCATDeductible.Text;
                        limit.WindHailDeductible = txtWHDeductible.Text;
                        limit.ConInsuranceLimit  = txtCoInsuranceLimit.Value == null ? 0 : Convert.ToDecimal(txtCoInsuranceLimit.Value);
                        limit.ITV           = Convert.ToDecimal(txtITV.Value);
                        limit.Reserve       = Convert.ToDecimal(txtReserve.Value);
                        limit.LossAmountACV = txtLossAmountACV.Value == null ? 0 : Convert.ToDecimal(txtLossAmountACV.Text);
                        limit.LossAmountRCV = txtLossAmountRCV.Value == null ? 0 : Convert.ToDecimal(txtLossAmountRCV.Text);
                        limit.OverageAmount = txtOverage.Value == null ? 0 : Convert.ToDecimal(txtOverage.Text);
                        if (ddlSettlementType.SelectedItemIndex > 0)
                        {
                            //limit.SettlementType = ddlSettlementType.SelectedValue;
                            limit.ApplyTo = ddlSettlementType.SelectedValue;
                        }
                        else
                        {
                            limit.ApplyTo = null;
                        }

                        try
                        {
                            PolicyLimitManager.Save(limit);
                        }
                        catch (Exception ex)
                        {
                            Core.EmailHelper.emailError(ex);
                        }
                    }
                }
            }
            cbAddNewPolicy.Checked = false;
            disableNewRow();
        }