Ejemplo n.º 1
0
 public Activity Create(System.Windows.DependencyObject target)
 {
     Type t = typeof(GetElement);
     var wfdesigner = Plugin.client.Window.LastDesigner;
     WFHelper.DynamicAssemblyMonitor(wfdesigner.WorkflowDesigner, t.Assembly.GetName().Name, t.Assembly, true);
     var fef = new GetElement();
     var aa = new ActivityAction<NMElement>();
     var da = new DelegateInArgument<NMElement>();
     da.Name = "item";
     fef.Body = aa;
     aa.Argument = da;
     return fef;
 }
Ejemplo n.º 2
0
        public Activity Create(System.Windows.DependencyObject target)
        {
            Type t          = typeof(WaitForText);
            var  wfdesigner = global.OpenRPAClient.CurrentDesigner;

            WFHelper.DynamicAssemblyMonitor(wfdesigner.WorkflowDesigner, t.Assembly.GetName().Name, t.Assembly, true);
            var fef = new WaitForText();
            var aa  = new ActivityAction <bool>();
            var da  = new DelegateInArgument <bool>();

            da.Name     = "item";
            aa.Handler  = new System.Activities.Statements.Sequence();
            fef.Body    = aa;
            aa.Argument = da;
            return(fef);
        }
Ejemplo n.º 3
0
        public Activity Create(System.Windows.DependencyObject target)
        {
            Type t          = typeof(TerminalSession);
            var  wfdesigner = global.OpenRPAClient.CurrentDesigner;

            WFHelper.DynamicAssemblyMonitor(wfdesigner.WorkflowDesigner, t.Assembly.GetName().Name, t.Assembly, true);
            var fef = new TerminalSession();
            // fef.Variables = new System.Collections.ObjectModel.Collection<Variable>();
            var aa = new ActivityAction <Interfaces.VT.ITerminalSession>();
            var da = new DelegateInArgument <Interfaces.VT.ITerminalSession>();

            da.Name     = "_session";
            aa.Handler  = new System.Activities.Statements.Sequence();
            fef.Body    = aa;
            aa.Argument = da;
            return(fef);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 获取组织机构路径
        /// </summary>
        private void GetAllPath()
        {
            string GroupId  = RequestData.Get("GroupID") + "";
            string reResult = "";

            //string sql = @"select *  from SysGroup where GroupId='{0}' ";
            //sql = string.Format(sql, GroupId);
            //DataTable Dt = DataHelper.QueryDataTable(sql);
            if (!string.IsNullOrEmpty(GroupId))
            {
                string Result = WFHelper.getCzlxDG1(GroupId, ref reResult);
                this.PageState.Add("State", Result);
            }
            else
            {
                this.PageState.Add("State", "");
            }
        }
Ejemplo n.º 5
0
        public Activity Create(System.Windows.DependencyObject target)
        {
            Type t          = typeof(GetElement);
            var  wfdesigner = Plugin.client.Window.LastDesigner;

            WFHelper.DynamicAssemblyMonitor(wfdesigner.WorkflowDesigner, t.Assembly.GetName().Name, t.Assembly, true);
            var fef = new GetImage();

            fef.Variables.Add(new Variable <int>("Index", 0));
            fef.Variables.Add(new Variable <int>("Total", 0));
            var aa = new ActivityAction <ImageElement>();
            var da = new DelegateInArgument <ImageElement>();

            da.Name     = "item";
            fef.Body    = aa;
            aa.Argument = da;
            return(fef);
        }
Ejemplo n.º 6
0
        public void ProcessRequest(RequestBase baseRequest, HandlerResponse response)
        {
            if (baseRequest == null)
            {
                throw new ArgumentNullException(nameof(baseRequest));
            }
            var request = baseRequest as OrdinaryCurveGenRequest;

            if (request == null)
            {
                throw new InvalidCastException(
                          $"{typeof(RequestBase).Name} is not a {typeof(OrdinaryCurveGenRequest).Name}");
            }
            CurveSelection[] curveSelectors = request.CurveSelector ?? new List <CurveSelection>().ToArray();
            response.ItemCount = curveSelectors.Length;
            DateTime lastStatusPublishedAt = DateTime.Now;

            // check for workflow cancellation
            if (Cancelled)
            {
                throw new OperationCanceledException(CancelReason);
            }
            // iterate selected curves
            foreach (CurveSelection curveSelector in curveSelectors)
            {
                // publish 'intermediate' in-progress result (throttled)
                if ((DateTime.Now - lastStatusPublishedAt) > TimeSpan.FromSeconds(5))
                {
                    lastStatusPublishedAt = DateTime.Now;
                    response.Status       = RequestStatusEnum.InProgress;
                    Context.Cache.SaveObject(response);
                }
                string nameSpace       = curveSelector.NameSpace;
                string inputMarketName = curveSelector.MarketName;
                string inputCurveName  = curveSelector.CurveName;
                string inputCurveType  = curveSelector.CurveType;
                // given a curve definition, this workflow generates:
                // - a live base curve using current market data
                // load curve definition
                Context.Logger.LogDebug("Building ordinary curve: {0}.{1}.{2}", inputMarketName, inputCurveType, inputCurveName);
                string curveUniqueId =
                    $"Configuration.PricingStructures.{inputMarketName}.{inputCurveType}.{inputCurveName}";
                //TODO This does not work for MArket=Test_EOD because the market date propeerty
                //is not included in the identifier and unique identifier!
                ICoreItem marketItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, curveUniqueId);
                // check data is not mutated
                //AssertNotModified<Market>(marketItem);
                // note: we must clone the definition to avoid updating it in the cache!
                var market = marketItem.GetData <Market>(true);
                //AssertSomeQuotesMissing(((YieldCurveValuation)(cachedMarket.Items1[0])).inputs);
                //Market clonedMarket = BinarySerializerHelper.Clone<Market>(cachedMarket);
                PricingStructure          ps  = market.Items[0];
                PricingStructureValuation psv = market.Items1[0];
                // supply base data and  build datetime
                psv.baseDate = new IdentifiedDate {
                    Value = request.BaseDate
                };
                QuotedAssetSet curveDefinition;
                if (psv is YieldCurveValuation curveValuation)
                {
                    curveDefinition = curveValuation.inputs;
                }
                else
                {
                    if (psv is FxCurveValuation valuation)
                    {
                        curveDefinition = valuation.spotRate;
                    }
                    else
                    {
                        throw new NotSupportedException("Unsupported PricingStructureValuation type: " + psv.GetType().Name);
                    }
                }
                //AssertSomeQuotesMissing(curveDefinition);
                // default outputs
                var    curveDefProps      = new NamedValueSet(marketItem.AppProps);
                var    curveType          = PropertyHelper.ExtractPricingStructureType(curveDefProps);//.GetValue<string>(CurveProp.PricingStructureType, true));
                var    curveName          = curveDefProps.GetValue <string>(CurveProp.CurveName, true);
                string marketDataItemName = String.Format(FunctionProp.QuotedAssetSet.ToString() + ".{0}.{1}.{2}", inputMarketName, curveType, curveName);
                curveDefProps.Set("BootStrap", true);
                curveDefProps.Set(CurveProp.BaseDate, request.BaseDate);
                IPricingStructureIdentifier liveCurveId = PricingStructureIdentifier.CreateMarketCurveIdentifier(curveDefProps, inputMarketName, null, null, null, null);
                NamedValueSet liveCurveProps            = liveCurveId.Properties;
                var           liveCurveItemName         = liveCurveProps.GetValue <string>(CurveProp.UniqueIdentifier, true);
                var           liveCurve = new Market(); // empty
                try
                {
                    // build a request/response map (indexed by instrument id)
                    var instrumentMap = new Dictionary <string, Asset>();
                    foreach (Asset asset in curveDefinition.instrumentSet.Items)
                    {
                        instrumentMap[asset.id.ToLower()] = asset;
                    }
                    int bavNum = 0;
                    foreach (BasicAssetValuation quoteInstr in curveDefinition.assetQuote)
                    {
                        if (quoteInstr.objectReference?.href == null)
                        {
                            throw new ApplicationException($"Missing objectReference in BasicAssetValuation[{bavNum}]");
                        }
                        string instrId = quoteInstr.objectReference.href;
                        if (!instrumentMap.TryGetValue(instrId.ToLower(), out _))
                        {
                            throw new ApplicationException($"Cannot find instrument '{instrId}' for assetQuote");
                        }
                        bavNum++;
                    }
                    // request market data from MDS
                    QuotedAssetSet marketData;
                    if (request.UseSavedMarketData)
                    {
                        // get saved market data
                        marketData = Context.Cache.LoadObject <QuotedAssetSet>(nameSpace + "." + marketDataItemName);
                        if (marketData == null)
                        {
                            throw new ApplicationException(
                                      $"Could not load saved market data with name: '{marketDataItemName}'");
                        }
                    }
                    else
                    {
                        //throw new NotImplementedException();
                        using (var mdc = MarketDataFactory.Create(Reference <ILogger> .Create(Context.Logger), Assembly.GetExecutingAssembly(), null))
                        {
                            // call MDS
                            //AssertSomeQuotesMissing(curveDefinition);
                            Guid mdsRequestId = Guid.NewGuid();
                            MDSResult <QuotedAssetSet> mdsResponse = mdc.GetMarketQuotes(
                                MDSProviderId.Bloomberg, null, mdsRequestId, true, null,
                                curveDefinition);
                            if (mdsResponse.Error != null)
                            {
                                throw mdsResponse.Error;
                            }
                            marketData = mdsResponse.Result;
                            if ((marketData.assetQuote == null) || marketData.assetQuote.Length < 1)
                            {
                                throw new ApplicationException($"MDS response contains no quotes! ({mdsRequestId})");
                            }

                            // save transient market data for later offline use
                            if (request.SaveMarketData)
                            {
                                var marketDataProps = new NamedValueSet();
                                marketDataProps.Set(liveCurveProps.Get(EnvironmentProp.NameSpace));//TODO Added to filter on client namespace!
                                marketDataProps.Set(liveCurveProps.Get(CurveProp.Market));
                                marketDataProps.Set(liveCurveProps.Get(CurveProp.PricingStructureType));
                                marketDataProps.Set(liveCurveProps.Get(CurveProp.CurveName));
                                marketDataProps.Set(liveCurveProps.Get(CurveProp.Currency1));
                                Context.Cache.SaveObject(marketData, marketDataItemName, marketDataProps, true, TimeSpan.FromDays(7));
                            }
                        }
                    }
                    // check market data for undefined/invalid quotes
                    foreach (BasicAssetValuation asset in marketData.assetQuote)
                    {
                        if (asset.quote.Any(quote => quote.measureType.Value.Equals("undefined", StringComparison.OrdinalIgnoreCase)))
                        {
                            throw new ApplicationException(
                                      $"Market quote undefined/missing for asset '{asset.objectReference.href}'");
                        }
                    }
                    // merge MDS results with stored quotes in the curve definition
                    curveDefinition.Replace(marketData);//Merge(marketData, true, false, true);
                    // generate ordinary base curve
                    if (psv is YieldCurveValuation valuation)
                    {
                        valuation.inputs = curveDefinition;
                    }
                    else
                    {
                        ((FxCurveValuation)psv).spotRate = new FxRateSet
                        {
                            instrumentSet = curveDefinition.instrumentSet,
                            assetQuote    = curveDefinition.assetQuote
                        };
                    }
                    // hack - if rate basis curve then call new triplet fn, else call old pair fn.
                    IPricingStructure ips;
                    switch (curveType)
                    {
                    case PricingStructureTypeEnum.RateBasisCurve:
                    {
                        // rate basis curves require a reference curve
                        string refCurveUniqueId =
                            $"Market.{inputMarketName}.{curveDefProps.GetValue<string>(CurveProp.ReferenceCurveName, true)}";
                        // load the reference curve
                        ICoreItem refCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, refCurveUniqueId);
                        var       refCurve     = (Market)refCurveItem.Data;
                        //Format the ref curve data and call the pricing structure helper.
                        var refCurveFpMLTriplet = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(refCurve.Items[0],
                                                                                                                           refCurve.Items1[0], refCurveItem.AppProps);
                        liveCurveProps.Set(CurveProp.ReferenceCurveUniqueId, refCurveUniqueId);
                        var spreadCurveFpMLTriplet = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(ps, psv, liveCurveProps);
                        //create and set the pricingstructure
                        ips = CurveLoader.LoadInterestRateCurve(Context.Logger, Context.Cache, nameSpace, refCurveFpMLTriplet, spreadCurveFpMLTriplet);
                        //Creator.Create(refCurveFpMLTriplet, spreadCurveFpMLTriplet);
                    }
                    break;

                    case PricingStructureTypeEnum.RateXccyCurve:
                    {
                        // rate basis curves require a base curve
                        string baseCurveUniqueId = String.Format(nameSpace + ".Market.{0}.{1}",
                                                                 inputMarketName, curveDefProps.GetValue <string>(CurveProp.ReferenceCurveName, true));
                        // load the reference curve
                        ICoreItem baseCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, baseCurveUniqueId);
                        var       baseCurve     = (Market)baseCurveItem.Data;
                        // rate basis curves require an fx curve
                        string fxCurveUniqueId = String.Format(nameSpace + ".Market.{0}.{1}",
                                                               inputMarketName, curveDefProps.GetValue <string>(CurveProp.ReferenceFxCurveName, true));
                        // load the reference curve
                        ICoreItem fxCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, fxCurveUniqueId);
                        var       fxCurve     = (Market)fxCurveItem.Data;
                        // rate basis curves require a reference curve
                        string refCurveUniqueId = String.Format(nameSpace + ".Market.{0}.{1}",
                                                                inputMarketName, curveDefProps.GetValue <string>(CurveProp.ReferenceCurrency2CurveName, true));
                        // load the reference curve
                        ICoreItem refCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, refCurveUniqueId);
                        var       refCurve     = (Market)refCurveItem.Data;
                        //Format the ref curve data and call the pricing structure helper.
                        var baseCurveFpMLTriplet = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(baseCurve.Items[0],
                                                                                                                            baseCurve.Items1[0], baseCurveItem.AppProps);
                        var fxCurveFpMLTriplet = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(fxCurve.Items[0],
                                                                                                                          fxCurve.Items1[0], fxCurveItem.AppProps);
                        var refCurveFpMLTriplet = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(refCurve.Items[0],
                                                                                                                           refCurve.Items1[0], refCurveItem.AppProps);
                        liveCurveProps.Set(CurveProp.ReferenceCurveUniqueId, baseCurveUniqueId);
                        liveCurveProps.Set(CurveProp.ReferenceFxCurveUniqueId, fxCurveUniqueId);
                        liveCurveProps.Set(CurveProp.ReferenceCurrency2CurveId, refCurveUniqueId);
                        var spreadCurveFpMLTriplet = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(ps, psv, liveCurveProps);
                        //create and set the pricingstructure
                        ips = CurveLoader.LoadInterestRateCurve(Context.Logger, Context.Cache, nameSpace, baseCurveFpMLTriplet,
                                                                fxCurveFpMLTriplet, refCurveFpMLTriplet, spreadCurveFpMLTriplet);
                        //Creator.Create(baseCurveFpMLTriplet, fxCurveFpMLTriplet, refCurveFpMLTriplet, spreadCurveFpMLTriplet);
                    }
                    break;        //TODO Add Volatility types as well

                    default:
                    {
                        ips = CurveLoader.LoadCurve(Context.Logger, Context.Cache,
                                                    nameSpace, new Pair <PricingStructure, PricingStructureValuation>(ps, psv),
                                                    liveCurveProps);
                        //Creator.Create(new Pair<PricingStructure, PricingStructureValuation>(ps, psv), liveCurveProps);
                    }
                    break;
                    }
                    // retrieve curve
                    liveCurve = PricingStructureHelper.CreateMarketFromFpML(
                        ips.GetPricingStructureId().UniqueIdentifier,
                        ips.GetFpMLData());
                    // curve done
                    response.IncrementItemsPassed();
                }
                catch (Exception innerExcp)
                {
                    response.IncrementItemsFailed();
                    Context.Logger.Log(innerExcp);
                    liveCurveProps.Set(WFPropName.ExcpName, WFHelper.GetExcpName(innerExcp));
                    liveCurveProps.Set(WFPropName.ExcpText, WFHelper.GetExcpText(innerExcp));
                }

                // ================================================================================
                // calculate curve lifetimes
                //   SOD = 8am, EOD = 4:30pm
                // live curves
                // - publish anytime
                // - expires SOD next day
                // EOD (today) curves
                // - publish for 15 minutes prior to EOD today
                // - expires in 7 days
                // EOD (dated) - 7 days
                // - publish for 15 minutes prior to EOD today
                // - expires in 7 days
                DateTime dtNow             = DateTime.Now;
                DateTime dtToday           = dtNow.Date;
                DateTime dtEODPublishBegin = dtToday.AddHours(16.25);  // 4:15pm today
                DateTime dtEODPublishUntil = dtToday.AddHours(16.5);   // 4:30pm today
                DateTime dtSODTomorrow     = dtToday.AddHours(24 + 8); // 8am tomorrow
                //DateTime dtEODTomorrow = dtToday.AddHours(24 + 16); // 4pm tomorrow
                // publish live curve
                Context.Cache.SaveObject(liveCurve, nameSpace + "." + liveCurveItemName, liveCurveProps, true, dtSODTomorrow);
                // republish as latest EOD curve
                if (request.ForceGenerateEODCurves || ((dtNow >= dtEODPublishBegin) && (dtNow <= dtEODPublishUntil)))
                {
                    NamedValueSet itemProps = PricingStructureIdentifier.CreateMarketCurveIdentifier(liveCurveProps, CurveConst.QR_EOD, null, null, null, null).Properties;
                    var           itemName  = itemProps.GetValue <string>(CurveProp.UniqueIdentifier, true);
                    // persistent
                    Context.Cache.SaveObject(liveCurve, nameSpace + "." + itemName, itemProps, false, TimeSpan.FromDays(7));
                }
                // republish as dated EOD curve
                if (request.ForceGenerateEODCurves || ((dtNow >= dtEODPublishBegin) && (dtNow <= dtEODPublishUntil)))
                {
                    NamedValueSet itemProps = PricingStructureIdentifier.CreateMarketCurveIdentifier(liveCurveProps, CurveConst.QR_EOD, dtToday, null, null, null).Properties;
                    var           itemName  = itemProps.GetValue <string>(CurveProp.UniqueIdentifier, true);
                    // persistent
                    Context.Cache.SaveObject(liveCurve, nameSpace + "." + itemName, itemProps, false, TimeSpan.FromDays(7));
                }
            } // foreach curve
            // success
            response.Status = RequestStatusEnum.Completed;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 生成查看人员
        /// </summary>
        /// <param name="SurveyId"></param>
        /// <returns></returns>
        public bool CreateReadUser(string SurveyId)
        {
            SurveyReaderObj SrEnt = SurveyReaderObj.FindFirstByProperties(SurveyReaderObj.Prop_SurveyId, SurveyId);
            //组织下的人员
            string RdSQL = this.ReadSQL;

            if (string.IsNullOrEmpty(SrEnt.OrgIds) || string.IsNullOrEmpty(SrEnt.OrgNames))
            {
                RdSQL = RdSQL.Replace("##Query##", " and 1<>1 ");   //组织为空情况
                RdSQL = string.Format(RdSQL, SurveyId);
            }
            else
            {
                RdSQL = RdSQL.Replace("##Query##", " ");
                RdSQL = string.Format(RdSQL, SurveyId);
            }

            DataTable FilterUsrDt = DataHelper.QueryDataTable(RdSQL);

            // 添加的人员
            string SQL = @"with SurObjUsr As 
                             (
                                 select CA.* from
                                 FL_Culture..SurveyReaderObj As A 
                                 cross apply(
                                      select Filed As UsrID from FL_Culture..GetTblByJson(A.AllowUser,'Id')
                                 ) As CA
                                 where SurveyId='{0}'
                             ),
                             UserInfo As (
                               select T.UserID,T.Name, T.WorkNo from SurObjUsr As A 
                                 left join FL_PortalHR..Sysuser As T 
                                 on A.UsrID=T.UserID 

                            )
                          select distinct * from UserInfo ";

            SQL = "select '' where  1<>1  ";  //Change BY WGM 9-30

            SQL = SQL.Replace("FL_PortalHR", Global.AimPortalDB);
            SQL = string.Format(SQL, SurveyId);
            DataTable AddUsrDt = DataHelper.QueryDataTable(SQL);

            //排除的人员
            string ReMoveSQL = @" select CA.* from
                        FL_Culture..SurveyReaderObj As A 
                        cross apply(
                             select Filed As UserID from FL_Culture..GetTblByJson(A.NoAllowUser,'Id')
                        ) As CA
                        where SurveyId='{0}'";

            ReMoveSQL = string.Format(ReMoveSQL, SurveyId);

            ReMoveSQL = "select '' where  1<>1  ";  //Change BY WGM 9-30
            DataTable RemoveDt = DataHelper.QueryDataTable(ReMoveSQL);

            //排除人员
            if (RemoveDt.Rows.Count > 0)
            {
                for (int i = 0; i < FilterUsrDt.Rows.Count; i++)
                {
                    for (int j = 0; j < RemoveDt.Rows.Count; j++)
                    {
                        if (FilterUsrDt.Rows[i]["UserID"].ToString() == RemoveDt.Rows[j]["UserID"].ToString())
                        {
                            FilterUsrDt.Rows.Remove(FilterUsrDt.Rows[i]);
                        }
                    }
                }
            }

            // 合并

            DataTable  FinalDt     = new DataTable();
            DataColumn Dc_UserId   = new DataColumn("UserId"); FinalDt.Columns.Add(Dc_UserId);
            DataColumn Dc_UserName = new DataColumn("UserName"); FinalDt.Columns.Add(Dc_UserName);
            DataColumn Dc_DeptId   = new DataColumn("DeptId"); FinalDt.Columns.Add(Dc_DeptId);
            DataColumn Dc_DeptName = new DataColumn("DeptName"); FinalDt.Columns.Add(Dc_DeptName);
            DataColumn Dc_WorkNo   = new DataColumn("WorkNo"); FinalDt.Columns.Add(Dc_WorkNo);

            for (int i = 0; i < FilterUsrDt.Rows.Count; i++)
            {
                DataRow dr = FinalDt.NewRow();
                //dr["DeptId"] = FilterUsrDt.Rows[i]["GroupId"];
                //dr["DeptName"] = FilterUsrDt.Rows[i]["GroupName"];
                string FullDept = WFHelper.getZzjg(FilterUsrDt.Rows[i]["UserID"].ToString(), true);
                dr["DeptName"] = FullDept;
                dr["WorkNo"]   = FilterUsrDt.Rows[i]["WorkNo"];
                dr["UserId"]   = FilterUsrDt.Rows[i]["UserID"];   //*
                dr["UserName"] = FilterUsrDt.Rows[i]["UserName"]; //*

                FinalDt.Rows.Add(dr);
            }
            //Add
            for (int i = 0; i < AddUsrDt.Rows.Count; i++)
            {
                DataRow dr = FinalDt.NewRow();
                //dr["DeptId"] = AddUsrDt.Rows[i]["GroupID"];
                //dr["DeptName"] = AddUsrDt.Rows[i]["GroupName"];
                string FullDept = WFHelper.getZzjg(AddUsrDt.Rows[i]["UserID"].ToString(), true);
                dr["DeptName"] = FullDept;
                dr["WorkNo"]   = AddUsrDt.Rows[i]["WorkNo"];
                dr["UserId"]   = AddUsrDt.Rows[i]["UserID"]; //*
                dr["UserName"] = AddUsrDt.Rows[i]["Name"];   //*

                FinalDt.Rows.Add(dr);
            }

            SurveyQuestion Ent = SurveyQuestion.Find(SurveyId);

            if (Ent != null)
            {
                //添加问卷创建者
                DataRow CreateRow = FinalDt.NewRow();
                CreateRow["UserId"]   = Ent.CreateId;
                CreateRow["UserName"] = Ent.CreateName;
                FinalDt.Rows.Add(CreateRow);
            }
            //---------------------------------------------------------------
            //生成调查用户
            for (int i = 0; i < FinalDt.Rows.Count; i++)
            {
                SurveyCanReaderUsr UserEnt = new SurveyCanReaderUsr();
                UserEnt.CreateWay = "1";      //1 表示生成的用户而非创建
                UserEnt.SurveyId  = SurveyId;
                UserEnt.DeptName  = FinalDt.Rows[i]["DeptName"].ToString();
                //UserEnt.DeptId = FinalDt.Rows[i]["DeptId"].ToString();
                UserEnt.UserId   = FinalDt.Rows[i]["UserId"].ToString();
                UserEnt.UserName = FinalDt.Rows[i]["UserName"].ToString();
                UserEnt.WorkNo   = FinalDt.Rows[i]["WorkNo"].ToString();
                UserEnt.DoCreate();
            }

            return(true);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 生成被调查人员
        /// </summary>
        /// <param name="SurveyId"></param>
        /// <returns></returns>
        public bool CreateSurveyedUser(string SurveyId)
        {
            SurveyedObj Ent = SurveyedObj.FindFirstByProperties(SurveyedObj.Prop_SurveyId, SurveyId);

            // 根据条件筛选的人员
            string where = string.Empty;
            if (string.IsNullOrEmpty(Ent.OrgIds) || string.IsNullOrEmpty(Ent.OrgNames))
            {
                where = " and 1<>1 ";  //组织结构为空情况
            }
            else
            {
                where = AnalyzeSQL(Ent);
            }

            var FilterUsrDt = FilterUser(SurveyId, where);

            //筛选职位
            if (!string.IsNullOrEmpty(Ent.PostionNames))
            {
                string   split   = string.Empty;
                string[] tempArr = Ent.PostionNames.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                for (int j = 0; j < tempArr.Length; j++)
                {
                    if (j > 0)
                    {
                        split += " or ";
                    }
                    split += " JobName like  '%" + tempArr[j] + "%' ";
                }

                DataRow[]  rows       = FilterUsrDt.Select(split); //查询gw
                DataTable  tempDt     = new DataTable();
                DataColumn D_UserId   = new DataColumn("UserId"); tempDt.Columns.Add(D_UserId);
                DataColumn D_UserName = new DataColumn("UserName"); tempDt.Columns.Add(D_UserName);
                DataColumn D_WorkNo   = new DataColumn("WorkNo"); tempDt.Columns.Add(D_WorkNo);
                DataColumn D_JobName  = new DataColumn("JobName"); tempDt.Columns.Add(D_JobName);
                for (int i = 0; i < rows.Length; i++)
                {
                    DataRow dr = tempDt.NewRow();
                    dr["UserId"]   = rows[i]["UserId"];
                    dr["UserName"] = rows[i]["UserName"];
                    dr["WorkNo"]   = rows[i]["WorkNo"];
                    dr["JobName"]  = rows[i]["JobName"];
                    tempDt.Rows.Add(dr);
                }
                if (tempDt.Rows.Count > 0)
                {
                    FilterUsrDt = tempDt;
                }
            }


            //Modify By WGM 8/9
            string SQL = @"with SurObjUsr As 
                            (
                                select CA.* from
                                FL_Culture..SurveyedObj As A 
                                cross apply(
                                     select Filed As UsrID from FL_Culture..GetTblByJson(A.AddUserNames,'Id')
                                ) As CA
                                where SurveyId='{0}'
                            ),
                            UserInfo As (
                              select T.UserID,T.Name,T.WorkNo from SurObjUsr As A 
                                left join FL_PortalHR..Sysuser As T 
                                on A.UsrID=T.UserID 
                            )
                            select distinct * from UserInfo";

            SQL = SQL.Replace("FL_PortalHR", Global.AimPortalDB);
            SQL = string.Format(SQL, SurveyId);

            SQL = "select '' where  1<>1  ";  //Change BY WGM 9-30
            DataTable AddUsrDt = DataHelper.QueryDataTable(SQL);

            //排除的人员
            string ReMoveSQL = @" select CA.* from
                        FL_Culture..SurveyedObj As A 
                        cross apply(
                             select Filed As UserID from FL_Culture..GetTblByJson(A.AddUserNames,'Id')
                        ) As CA
                        where SurveyId='{0}'";

            ReMoveSQL = string.Format(ReMoveSQL, SurveyId);
            ReMoveSQL = "select '' where  1<>1  ";  //Change BY WGM 9-30

            DataTable RemoveDt = DataHelper.QueryDataTable(ReMoveSQL);

            if (RemoveDt.Rows.Count > 0)
            {
                for (int i = 0; i < FilterUsrDt.Rows.Count; i++)
                {
                    for (int j = 0; j < RemoveDt.Rows.Count; j++)
                    {
                        if (FilterUsrDt.Rows[i]["UserID"].ToString() == RemoveDt.Rows[j]["UserID"].ToString())
                        {
                            FilterUsrDt.Rows.Remove(FilterUsrDt.Rows[i]);
                        }
                    }
                }
            }

            //---------------------------生成DataTable-----------------------------

            DataTable  FinalDt     = new DataTable();
            DataColumn Dc_UserId   = new DataColumn("UserId"); FinalDt.Columns.Add(Dc_UserId);
            DataColumn Dc_UserName = new DataColumn("UserName"); FinalDt.Columns.Add(Dc_UserName);
            DataColumn Dc_DeptId   = new DataColumn("DeptId"); FinalDt.Columns.Add(Dc_DeptId);
            DataColumn Dc_DeptName = new DataColumn("DeptName"); FinalDt.Columns.Add(Dc_DeptName);
            DataColumn Dc_WorkNo   = new DataColumn("WorkNo"); FinalDt.Columns.Add(Dc_WorkNo);

            // string FindSQL = @"select FL_Culture.dbo.GetGroupIds('{0}') As DeptId,FL_Culture.dbo.GetGroupNames('{0}') As DeptName";
            for (int i = 0; i < FilterUsrDt.Rows.Count; i++)
            {
                //string tempSQL = string.Format(FindSQL, FilterUsrDt.Rows[i]["UserID"].ToString());
                //DataTable tempDt = DataHelper.QueryDataTable(tempSQL);
                DataRow dr = FinalDt.NewRow();
                //dr["DeptId"] = FilterUsrDt.Rows[i]["GroupIds"];
                //dr["DeptName"] = FilterUsrDt.Rows[i]["GroupNames"];

                string FullDept = WFHelper.getZzjg(FilterUsrDt.Rows[i]["UserID"].ToString(), true);
                dr["DeptName"] = FullDept;
                dr["UserId"]   = FilterUsrDt.Rows[i]["UserID"];   //*
                dr["UserName"] = FilterUsrDt.Rows[i]["UserName"]; //*
                dr["WorkNo"]   = FilterUsrDt.Rows[i]["WorkNo"];

                FinalDt.Rows.Add(dr);
            }

            for (int i = 0; i < AddUsrDt.Rows.Count; i++)
            {
                DataRow dr = FinalDt.NewRow();
                //dr["DeptId"] = AddUsrDt.Rows[i]["GroupID"];
                //dr["DeptName"] = AddUsrDt.Rows[i]["GroupName"];

                string FullDept = WFHelper.getZzjg(AddUsrDt.Rows[i]["UserID"].ToString(), true);
                dr["DeptName"] = FullDept;
                dr["UserId"]   = AddUsrDt.Rows[i]["UserID"]; //*
                dr["UserName"] = AddUsrDt.Rows[i]["Name"];   //*
                dr["WorkNo"]   = AddUsrDt.Rows[i]["WorkNo"];
                FinalDt.Rows.Add(dr);
            }
            //添加问卷发起者
            DataRow CreateRow = FinalDt.NewRow();

            CreateRow["UserId"]   = Ent.CreateId;
            CreateRow["UserName"] = Ent.CreateName;
            FinalDt.Rows.Add(CreateRow);

            //----------------------------------------------------------------------------

            //生成调查用户
            for (int i = 0; i < FinalDt.Rows.Count; i++)
            {
                SurveyFinallyUsr UserEnt = new SurveyFinallyUsr();
                UserEnt.CreateWay = "1";      //1 表示生成的用户而非创建
                UserEnt.SurveyId  = SurveyId;
                UserEnt.DeptName  = FinalDt.Rows[i]["DeptName"].ToString();
                //UserEnt.DeptId = FinalDt.Rows[i]["DeptId"].ToString();
                UserEnt.WorkNo   = FinalDt.Rows[i]["WorkNo"].ToString();
                UserEnt.UserId   = FinalDt.Rows[i]["UserId"].ToString();
                UserEnt.UserName = FinalDt.Rows[i]["UserName"].ToString();
                UserEnt.DoCreate();
            }

            return(true);
        }
Ejemplo n.º 9
0
        public void ProcessRequest(RequestBase baseRequest, HandlerResponse response)
        {
            if (baseRequest == null)
            {
                throw new ArgumentNullException(nameof(baseRequest));
            }
            var request = baseRequest as StressedCurveGenRequest;

            if (request == null)
            {
                throw new InvalidCastException(
                          $"{typeof(RequestBase).Name} is not a {typeof(StressedCurveGenRequest).Name}");
            }
            // check for workflow cancellation
            if (Cancelled)
            {
                throw new OperationCanceledException(CancelReason);
            }
            DateTime lastStatusPublishedAt = DateTime.Now;

            CurveSelection[] curveSelectors = request.CurveSelector ?? new List <CurveSelection>().ToArray();

            #region Load stress rules

            //find the uniques namespaces
            var uniquesNameSpaces = new List <string>();
            foreach (CurveSelection curveSelector in curveSelectors)
            {
                if (!uniquesNameSpaces.Contains(curveSelector.NameSpace))
                {
                    uniquesNameSpaces.Add(curveSelector.NameSpace);
                }
            }
            var cachedStressRules = new Dictionary <string, List <CachedStressRule> >();
            {
                IExpression       queryExpr         = Expr.IsEQU(EnvironmentProp.NameSpace, uniquesNameSpaces[0]);//TODO only does the first namespace....
                List <StressRule> storedStressRules = Context.Cache.LoadObjects <StressRule>(queryExpr);
                foreach (StressRule storedStressRule in storedStressRules)
                {
                    if ((storedStressRule.Disabled) || (storedStressRule.StressId == null))
                    {
                        continue;
                    }
                    string key = storedStressRule.StressId.ToLower();
                    List <CachedStressRule> rules;
                    if (!cachedStressRules.TryGetValue(key, out rules))
                    {
                        rules = new List <CachedStressRule>();
                        cachedStressRules[key] = rules;
                    }
                    rules.Add(new CachedStressRule(storedStressRule));
                    rules.Sort();
                }
            }
            #endregion

            response.ItemCount = curveSelectors.Length * cachedStressRules.Count;
            // iterate selected base curves
            foreach (CurveSelection curveSelector in curveSelectors)
            {
                // check for workflow cancellation
                if (Cancelled)
                {
                    throw new OperationCanceledException(CancelReason);
                }
                // publish 'intermediate' in-progress result (throttled)
                if ((DateTime.Now - lastStatusPublishedAt) > TimeSpan.FromSeconds(5))
                {
                    lastStatusPublishedAt = DateTime.Now;
                    response.Status       = RequestStatusEnum.InProgress;
                    Context.Cache.SaveObject(response);
                }
                string nameSpace       = curveSelector.NameSpace;
                string inputMarketName = curveSelector.MarketName;
                var    marketDate      = curveSelector.MarketDate;
                if (marketDate != null && marketDate != DateTime.MinValue)
                {
                    inputMarketName += "." + ((DateTime)marketDate).ToString(CurveProp.MarketDateFormat);
                }
                string inputCurveName = curveSelector.CurveName;
                string inputCurveType = curveSelector.CurveType;
                Context.Logger.LogDebug("Building stressed curve(s): {0}.{1}.{2}", inputMarketName, inputCurveType, inputCurveName);

                #region Load base curve

                var curveGenProps = new NamedValueSet();
                curveGenProps.Set(CurveProp.BaseDate, request.BaseDate);
                IPricingStructureIdentifier baseCurveId =
                    PricingStructureIdentifier.CreateMarketCurveIdentifier(curveGenProps, inputMarketName, null, inputCurveType, inputCurveName, null);
                var       baseCurveUniqueId = baseCurveId.Properties.GetValue <string>(CurveProp.UniqueIdentifier, true);
                ICoreItem baseCurveItem     = LoadAndCheckMarketItem(Context.Cache, nameSpace, baseCurveUniqueId);
                var       stressNameProp    = baseCurveItem.AppProps.GetValue <string>(CurveProp.StressName, null);
                if (stressNameProp != null)
                {
                    throw new ApplicationException("The Market with name '" + baseCurveUniqueId + "' is NOT a base curve! (Stress name is not null)");
                }
                var baseCurveFpml = (Market)baseCurveItem.Data;
                var baseCurveType = PropertyHelper.ExtractPricingStructureType(baseCurveItem.AppProps);

                #endregion

                #region Load the reference curves - if required

                string        fxCurveName = null, refCurveName = null, quoteCurveName = null;
                NamedValueSet fxProperties = null, refProperties = null, quoteProperties = null;
                Market        fxMarket = null, refMarket = null, quoteMarket = null;
                if (baseCurveType == PricingStructureTypeEnum.RateBasisCurve ||
                    baseCurveType == PricingStructureTypeEnum.RateXccyCurve)
                {
                    // rate basis curves require a reference curve
                    refCurveName = baseCurveItem.AppProps.GetValue <string>(CurveProp.ReferenceCurveUniqueId, true);
                    // load the reference curve
                    var refCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, refCurveName);
                    refMarket     = (Market)refCurveItem.Data;
                    refProperties = refCurveItem.AppProps;
                }
                if (baseCurveType == PricingStructureTypeEnum.RateXccyCurve)
                {
                    // rate basis curves require an fx curve
                    fxCurveName = baseCurveItem.AppProps.GetValue <string>(CurveProp.ReferenceFxCurveUniqueId, true);
                    // load the reference curve
                    var fxCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, fxCurveName);
                    fxMarket     = (Market)fxCurveItem.Data;
                    fxProperties = fxCurveItem.AppProps;
                    // rate basis curves require a reference curve
                    quoteCurveName = baseCurveItem.AppProps.GetValue <string>(CurveProp.ReferenceCurrency2CurveId, true);
                    // load the reference curve
                    var quoteCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, quoteCurveName);
                    quoteMarket     = (Market)quoteCurveItem.Data;
                    quoteProperties = quoteCurveItem.AppProps;
                }
                #endregion

                // process stress rules
                foreach (var kvp in cachedStressRules)
                {
                    CachedStressRule stressRule = kvp.Value.FirstOrDefault(item => (item.FilterExpr == null) || (Expr.CastTo(item.FilterExpr.Evaluate(baseCurveItem.AppProps), false)));
                    // find stress rule that applies
                    if (stressRule == null)
                    {
                        // this stress does not apply to this base curve
                        Context.Logger.LogWarning("Stress '{0}' does not apply to base curve '{1}'!", kvp.Key, baseCurveUniqueId);
                        response.IncrementItemsPassed();
                        continue;
                    }
                    // apply the stress rule
                    //_Context.Logger.LogDebug("Applying stress '{0}' (rule {1}) to base curve '{2}'", stressRule.StressId, stressRule.RuleId, baseCurveUniqueId);
                    var stressDefProps = new NamedValueSet(baseCurveItem.AppProps, curveGenProps);
                    stressDefProps.Set("Identifier", null);//THis is done for backward compatability eith the old ratecurves.
                    stressDefProps.Set(CurveProp.BaseCurveType, baseCurveType);
                    IPricingStructureIdentifier stressCurveId = PricingStructureIdentifier.CreateMarketCurveIdentifier(
                        stressDefProps, inputMarketName, null, baseCurveType.ToString(), inputCurveName, stressRule.StressId);
                    NamedValueSet stressCurveProps = stressCurveId.Properties;
                    var           stressCurveName  = stressCurveProps.GetValue <string>(CurveProp.UniqueIdentifier, true);
                    // from here on a curve will be published (with error details included)
                    var stressCurve = new Market(); // empty
                    try
                    {
                        // clone the base curve and adjust the market quotes
                        var ps = BinarySerializerHelper.Clone(baseCurveFpml.Items[0]);
                        PricingStructureValuation psv = ApplyStress(stressRule, baseCurveFpml.Items1[0]);
                        // hack - supply base date
                        psv.baseDate = new IdentifiedDate {
                            Value = request.BaseDate
                        };
                        Triplet <PricingStructure, PricingStructureValuation, NamedValueSet> refCurveFpmlTriplet = null;
                        if (baseCurveType == PricingStructureTypeEnum.RateBasisCurve ||
                            baseCurveType == PricingStructureTypeEnum.RateXccyCurve)
                        {
                            var psRef = BinarySerializerHelper.Clone(refMarket.Items[0]);
                            //var psvRef = BinarySerializerHelper.Clone<PricingStructureValuation>(refcurveFpml.Items1[0]);
                            var psvRef = ApplyStress(stressRule, refMarket.Items1[0]);
                            refCurveFpmlTriplet =
                                new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                    psRef, psvRef, refProperties);
                        }
                        IPricingStructure ips;
                        switch (baseCurveType)
                        {
                        case PricingStructureTypeEnum.RateBasisCurve:
                            stressCurveProps.Set(CurveProp.ReferenceCurveUniqueId, refCurveName);
                            var basisCurveFpmlTriplet =
                                new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                    ps, psv, stressCurveProps);
                            //create and set the pricingstructure
                            ips = CurveLoader.LoadInterestRateCurve(Context.Logger, Context.Cache, nameSpace, refCurveFpmlTriplet, basisCurveFpmlTriplet);
                            //Creator.Create(refCurveFpmlTriplet, basisCurveFpmlTriplet);
                            break;

                        case PricingStructureTypeEnum.RateXccyCurve:
                            stressCurveProps.Set(CurveProp.ReferenceCurveUniqueId, refCurveName);
                            stressCurveProps.Set(CurveProp.ReferenceFxCurveUniqueId, fxCurveName);
                            stressCurveProps.Set(CurveProp.ReferenceCurrency2CurveId, quoteCurveName);
                            var xccyCurveFpmlTriplet =
                                new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(ps, psv,
                                                                                                         stressCurveProps);
                            //Format the ref curve data and call the pricing structure helper.
                            var psvFx = ApplyStress(stressRule, fxMarket.Items1[0]);
                            var fxCurveFpmlTriplet
                                = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                      fxMarket.Items[0],
                                      psvFx, fxProperties);

                            var psvRef = ApplyStress(stressRule, quoteMarket.Items1[0]);
                            var quoteCurveFpmlTriplet
                                = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                      quoteMarket.Items[0],
                                      psvRef, quoteProperties);
                            //create and set the pricingstructure
                            ips = CurveLoader.LoadInterestRateCurve(Context.Logger, Context.Cache, nameSpace, refCurveFpmlTriplet, fxCurveFpmlTriplet, quoteCurveFpmlTriplet,
                                                                    xccyCurveFpmlTriplet);
                            //Creator.Create(refCurveFpmlTriplet, fxCurveFpmlTriplet, quoteCurveFpmlTriplet, xccyCurveFpmlTriplet);
                            break;

                        default:
                            ips = CurveLoader.LoadCurve(Context.Logger, Context.Cache,
                                                        nameSpace, new Pair <PricingStructure, PricingStructureValuation>(ps, psv),
                                                        stressCurveProps);
                            //Creator.Create( new Pair<PricingStructure, PricingStructureValuation>(ps, psv), stressCurveProps);
                            break;
                        }
                        var identifier = ips.GetPricingStructureId().UniqueIdentifier;
                        // retrieve curve
                        stressCurve = PricingStructureHelper.CreateMarketFromFpML(
                            identifier,
                            ips.GetFpMLData());
                        // curve done
                        response.IncrementItemsPassed();
                    }
                    catch (Exception innerExcp)
                    {
                        response.IncrementItemsFailed();
                        Context.Logger.Log(innerExcp);
                        stressCurveProps.Set(WFPropName.ExcpName, WFHelper.GetExcpName(innerExcp));
                        stressCurveProps.Set(WFPropName.ExcpText, WFHelper.GetExcpText(innerExcp));
                    }
                    // save stressed curve with same lifetime as base curve
                    stressCurveProps.Set(EnvironmentProp.NameSpace, nameSpace);
                    Context.Cache.SaveObject(stressCurve, nameSpace + "." + stressCurveName, stressCurveProps, true, baseCurveItem.Expires);
                } // foreach stress rule
            }     // foreach base curve

            // success
            response.Status = RequestStatusEnum.Completed;
        }