コード例 #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ServicePresenter objSerPre = new ServicePresenter();
        CommonUtil objCommonUtil = new CommonUtil();
        try
        {
            PropertyInfo propertyInfo = ucForeCast.GetType().GetProperty("Filter");
            propertyInfo.SetValue(ucForeCast, Convert.ChangeType(false, propertyInfo.PropertyType), null);
        }
        catch (Exception ex)
        {
            AgriCastException currEx = new AgriCastException(objSerPre.GetServiceDetails(), ex);
            AgriCastLogger.Publish(currEx, AgriCastLogger.LogType.Error);
            HttpContext.Current.Session["ErrorMessage"] = objCommonUtil.getTransText(Constants.MOB_LOAD_FAILURE) + " : " + ex.Message.ToString();

        }
    }
コード例 #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ServiceInfo objSvcInfo;
        CommonUtil objComUtil = new CommonUtil();
        if (Session == null || Session["serviceInfo"] == null)
        {

            objSvcInfo = new ServiceInfo();
        }
        else
        {
            objSvcInfo = (ServiceInfo)Session["serviceInfo"];
        }

        //set the master page controls translated text

        lnkTnC.InnerHtml = objComUtil.getTransText(lnkTnC.Attributes["name"]);
        lnkDisclaimer.InnerText = objComUtil.getTransText(lnkDisclaimer.Attributes["name"]);
        lnkFullSite.InnerText = objComUtil.getTransText(lnkFullSite.Attributes["name"]);
        btnBack.InnerHtml = objComUtil.getTransText("Back");
    }
コード例 #3
0
        /// <summary>
        /// 查询商品规格
        /// </summary>
        /// <param name="search">查询类</param>
        /// <returns>结果</returns>
        public List <Jinher.AMP.BTP.Deploy.SpecificationsDTO> GetSpecificationsListExt(Jinher.AMP.BTP.Deploy.SpecificationsDTO search)
        {
            List <Jinher.AMP.BTP.Deploy.SpecificationsDTO> objlist = new List <Jinher.AMP.BTP.Deploy.SpecificationsDTO>();
            var Specificationslist = Specifications.ObjectSet().Where(p => p.IsDel == false).AsQueryable();

            if (search.AppId != Guid.Empty)
            {
                Specificationslist = Specificationslist.Where(p => p.AppId == search.AppId);
            }
            if (search.Attribute != 0)
            {
                Specificationslist = Specificationslist.Where(p => p.Attribute == search.Attribute);
            }
            if (Specificationslist.Count() > 0)
            {
                foreach (var item in Specificationslist.OrderByDescending(p => p.SubTime).ToList())
                {
                    Jinher.AMP.BTP.Deploy.SpecificationsDTO entity = new Jinher.AMP.BTP.Deploy.SpecificationsDTO();
                    entity = CommonUtil.ReadObjectExchange(entity, item);
                    objlist.Add(entity);
                }
            }
            return(objlist);
        }
コード例 #4
0
        public void Init()
        {
            //Setting up references and initial values
            pointers           = CommonUtil.FindGameObjectsOfTag("Pointer");
            groups             = CommonUtil.FindGameObjectsOfTag("Group");
            scrollRect         = GetComponent <ScrollRect> ();
            rectTransform      = GetComponent <RectTransform> ();
            initialAspectRatio = Camera.main.aspect;
            CalculateGridLayoutsValues();
            isLerping = true;

            if (groups == null)
            {
                Debug.LogWarning("No groups found");
            }
            else if (groups.Length == 0)
            {
                Debug.LogWarning("No groups found");
            }

            SnapToGroup();
            GoToCurrentGroup();
            tempLerpSpeed = 256;
        }
コード例 #5
0
        public void HandlerReturnFalseWhenOthersFilterSucceedIsFailure()
        {
            ICollection <ILogFilter> filters = new List <ILogFilter>();

            ICollection <string> categories = new List <string>();

            categories.Add("cat1");
            categories.Add("cat2");
            categories.Add("cat3");
            categories.Add("cat4");
            filters.Add(new ExceptionThrowingLogFilter("exception1"));
            filters.Add(new CategoryFilter("category", categories, CategoryFilterMode.AllowAllExceptDenied));
            filters.Add(new PriorityFilter("priority", 100));

            filters.Add(new LogEnabledFilter("enable", true));

            MockLogFilterErrorHandler handler      = new MockLogFilterErrorHandler(false);
            LogFilterHelper           filterHelper = new LogFilterHelper(filters, handler);

            LogEntry log = CommonUtil.GetDefaultLogEntry();

            Assert.IsFalse(filterHelper.CheckFilters(log));
            Assert.AreEqual(1, handler.failingFilters.Count);
        }
コード例 #6
0
        public void SingleErrorForFiltersResultsInSingleNotification()
        {
            ICollection <ILogFilter> filters = new List <ILogFilter>();

            ICollection <string> categories = new List <string>();

            categories.Add("cat1");
            categories.Add("cat2");
            categories.Add("cat3");
            categories.Add("cat4");
            filters.Add(new CategoryFilter("category", categories, CategoryFilterMode.AllowAllExceptDenied));
            filters.Add(new ExceptionThrowingLogFilter("exception"));
            filters.Add(new PriorityFilter("priority", 100));

            filters.Add(new LogEnabledFilter("enable", true));

            MockLogFilterErrorHandler handler      = new MockLogFilterErrorHandler(true);
            LogFilterHelper           filterHelper = new LogFilterHelper(filters, handler);

            LogEntry log = CommonUtil.GetDefaultLogEntry();

            filterHelper.CheckFilters(log);
            Assert.AreEqual(1, handler.failingFilters.Count);
        }
コード例 #7
0
        /// <summary>
        /// Get detail of selected slip.
        /// </summary>
        /// <param name="SlipNo"></param>
        /// <returns></returns>
        public ActionResult GetSlipDetail(string SlipNo)
        {
            ObjectResultData res = new ObjectResultData();

            try
            {
                IInventoryHandler InvH = ServiceContainer.GetService <IInventoryHandler>() as IInventoryHandler;
                List <doInventorySlipDetailList> lst = InvH.GetInventorySlipDetailForSearch(SlipNo);
                res.ResultData = CommonUtil.ConvertToXml <doInventorySlipDetailList>(lst, "Inventory\\IVS011_SlipDetailList", CommonUtil.GRID_EMPTY_TYPE.SEARCH);

                IVS011_ScreenParameter param = GetScreenObject <IVS011_ScreenParameter>();

                if (param.lstInventory == null)
                {
                    param.lstInventory = new List <doInventorySlipDetailList>();
                }

                param.lstInventory = lst;
                UpdateScreenObject(param);

                return(Json(res));
            }
            catch (Exception ex) { res.AddErrorMessage(ex); return(Json(res)); }
        }
コード例 #8
0
        public object getitem(int id)
        {
            try
            {
                //      var booking = _context.Location.SingleOrDefault(x => x.id == id);
                var query = from a in _context.common_properties

                            where a.id == id
                            select new
                {
                    id        = a.id,
                    code      = a.code,
                    value     = a.value,
                    parent_id = a.parent_id,
                    order     = a.order,
                };
                var data = query.Where(x => x.id == id);

                return(Json(data));
            }
            catch (Exception ex)
            {
                return(Json(new JMessage()
                {
                    Error = true, Title = String.Format(CommonUtil.ResourceValue("MSG_LOAD_FAIL"), CommonUtil.ResourceValue("USER_USERNAME").ToLower()), Object = ex
                }));
            }
        }
コード例 #9
0
ファイル: BaseWindow.cs プロジェクト: atsushinee/Netx
        public async void GetIpv4AddrListHandler(Action <List <string> > action, bool showLocal = true)
        {
            var result = await CommonUtil.GetIpv4AddrListAsync(showLocal);

            action(result);
        }
コード例 #10
0
 public ActionResult IVS282_InitialDetailGrid()
 {
     return(Json(CommonUtil.ConvertToXml <object>(null, @"Inventory\IVS282_Detail", CommonUtil.GRID_EMPTY_TYPE.VIEW)));
 }
コード例 #11
0
        /// <summary>
        /// process the batch response
        /// </summary>
        /// <param name="batchReader">The batch reader to use for reading the batch response.</param>
        /// <returns>enumerable of QueryResponse or null</returns>
        /// <remarks>
        /// The batch message reader for the entire batch response is stored in this.batchMessageReader.
        /// Note that this method takes over the ownership of this reader and must Dispose it if it successfully returns.
        /// </remarks>
        private IEnumerable <OperationResponse> HandleBatchResponse(ODataBatchReader batchReader)
        {
            try
            {
                if (this.batchMessageReader == null)
                {
                    // The enumerable returned by this method can be enumerated multiple times.
                    // In that case it looks like if the method is called multiple times.
                    // This didn't fail in previous versions, it simply returned no results, so we need to do the same.
                    yield break;
                }

                Debug.Assert(batchReader != null, "batchReader != null");

                bool changesetFound  = false;
                bool insideChangeset = false;
                int  queryCount      = 0;
                int  operationCount  = 0;
                this.entryIndex = 0;
                while (batchReader.Read())
                {
                    switch (batchReader.State)
                    {
                        #region ChangesetStart
                    case ODataBatchReaderState.ChangesetStart:
                        if ((Util.IsBatchWithSingleChangeset(this.Options) && changesetFound) || (operationCount != 0))
                        {
                            // Throw if we encounter multiple changesets when running in batch with single changeset mode
                            // or if we encounter operations outside of a changeset.
                            Error.ThrowBatchUnexpectedContent(InternalError.UnexpectedBeginChangeSet);
                        }

                        insideChangeset = true;
                        break;
                        #endregion

                        #region ChangesetEnd
                    case ODataBatchReaderState.ChangesetEnd:
                        changesetFound  = true;
                        operationCount  = 0;
                        insideChangeset = false;
                        break;
                        #endregion

                        #region Operation
                    case ODataBatchReaderState.Operation:
                        Exception exception = this.ProcessCurrentOperationResponse(batchReader, insideChangeset);
                        if (!insideChangeset)
                        {
                            #region Get response
                            Debug.Assert(operationCount == 0, "missing an EndChangeSet 2");

                            QueryOperationResponse qresponse = null;
                            try
                            {
                                if (exception == null)
                                {
                                    DataServiceRequest query        = this.Queries[queryCount];
                                    ResponseInfo       responseInfo = this.RequestInfo.GetDeserializationInfo(null /*mergeOption*/);
                                    MaterializeAtom    materializer = DataServiceRequest.Materialize(
                                        responseInfo,
                                        query.QueryComponents(this.RequestInfo.Model),
                                        null,
                                        this.currentOperationResponse.Headers.GetHeader(XmlConstants.HttpContentType),
                                        this.currentOperationResponse.CreateResponseMessage(),
                                        query.PayloadKind);
                                    qresponse = QueryOperationResponse.GetInstance(query.ElementType, this.currentOperationResponse.Headers, query, materializer);
                                }
                            }
                            catch (ArgumentException e)
                            {
                                exception = e;
                            }
                            catch (FormatException e)
                            {
                                exception = e;
                            }
                            catch (InvalidOperationException e)
                            {
                                exception = e;
                            }

                            if (qresponse == null)
                            {
                                if (this.Queries != null)
                                {
                                    // this is the normal ExecuteBatch response
                                    DataServiceRequest query = this.Queries[queryCount];

                                    if (this.RequestInfo.IgnoreResourceNotFoundException && this.currentOperationResponse.StatusCode == HttpStatusCode.NotFound)
                                    {
                                        qresponse = QueryOperationResponse.GetInstance(query.ElementType, this.currentOperationResponse.Headers, query, MaterializeAtom.EmptyResults);
                                    }
                                    else
                                    {
                                        qresponse       = QueryOperationResponse.GetInstance(query.ElementType, this.currentOperationResponse.Headers, query, MaterializeAtom.EmptyResults);
                                        qresponse.Error = exception;
                                    }
                                }
                                else
                                {
                                    // This is top-level failure for SaveChanges(SaveChangesOptions.BatchWithSingleChangeset) or SaveChanges(SaveChangesOptions.BatchWithIndependentOperations) operations.
                                    // example: server doesn't support batching or number of batch objects exceeded an allowed limit.
                                    // ex could be null if the server responded to SaveChanges with an unexpected success with
                                    // response of batched GETS that did not correspond the original POST/PATCH/PUT/DELETE requests.
                                    // we expect non-null since server should have failed with a non-success code
                                    // and HandleResponse(status, ...) should generate the exception object
                                    throw exception;
                                }
                            }

                            qresponse.StatusCode = (int)this.currentOperationResponse.StatusCode;
                            queryCount++;
                            yield return(qresponse);

                            #endregion
                        }
                        else
                        {
                            #region Update response
                            try
                            {
                                Descriptor descriptor = this.ChangedEntries[this.entryIndex];
                                operationCount += this.SaveResultProcessed(descriptor);

                                if (exception != null)
                                {
                                    throw exception;
                                }

                                this.HandleOperationResponseHeaders(this.currentOperationResponse.StatusCode, this.currentOperationResponse.Headers);
#if DEBUG
                                this.HandleOperationResponse(descriptor, this.currentOperationResponse.Headers, this.currentOperationResponse.StatusCode);
#else
                                this.HandleOperationResponse(descriptor, this.currentOperationResponse.Headers);
#endif
                            }
                            catch (Exception e)
                            {
                                this.ChangedEntries[this.entryIndex].SaveError = e;
                                exception = e;

                                if (!CommonUtil.IsCatchableExceptionType(e))
                                {
                                    throw;
                                }
                            }

                            ChangeOperationResponse changeOperationResponse =
                                new ChangeOperationResponse(this.currentOperationResponse.Headers, this.ChangedEntries[this.entryIndex]);
                            changeOperationResponse.StatusCode = (int)this.currentOperationResponse.StatusCode;
                            if (exception != null)
                            {
                                changeOperationResponse.Error = exception;
                            }

                            operationCount++;
                            this.entryIndex++;
                            yield return(changeOperationResponse);

                            #endregion
                        }

                        break;
                        #endregion

                    default:
                        Error.ThrowBatchExpectedResponse(InternalError.UnexpectedBatchState);
                        break;
                    }
                }

                Debug.Assert(batchReader.State == ODataBatchReaderState.Completed, "unexpected batch state");

                // Check for a changeset without response (first line) or GET request without response (second line).
                // either all saved entries must be processed or it was a batch and one of the entries has the error
                if ((this.Queries == null &&
                     (!changesetFound ||
                      0 < queryCount ||
                      this.ChangedEntries.Any(o => o.ContentGeneratedForSave && o.SaveResultWasProcessed == 0) &&
                      (!this.IsBatchRequest || this.ChangedEntries.FirstOrDefault(o => o.SaveError != null) == null))) ||
                    (this.Queries != null && queryCount != this.Queries.Length))
                {
                    throw Error.InvalidOperation(Strings.Batch_IncompleteResponseCount);
                }
            }
            finally
            {
                // Note that this will be called only once the enumeration of all responses is finished and the Dispose
                // was called on the IEnumerator used for that enumeration. It is not called when the method returns,
                // since the compiler change this method to return the compiler-generated IEnumerable.
                Util.Dispose(ref this.batchMessageReader);
            }
        }
コード例 #12
0
        public ActionResult Login(string shopFlag, string code)
        {
            try
            {
                if (string.IsNullOrEmpty(code))
                {
                    throw new ArgumentNullException("code");
                }

                var authorizer = db.Query <ShopWechatOpenAuthorizer>()
                                 .Where(m => !m.IsDel)
                                 .Where(m => m.Shop.Flag == shopFlag)
                                 .Select(m => new
                {
                    AuthorizerAppId = m.WechatOpenAuthorizer.AuthorizerAppId
                })
                                 .FirstOrDefault();


                //return Content(authorizer.AuthorizerAppId + "," + code);

                var jsCode2Json = getJsCode2Json(authorizer.AuthorizerAppId, code);

                //_logger.LogInformation("Login时,jsCode2Json:{0}", jsCode2Json);

                //判定是否已经绑定手机号
                int?memberId      = null;
                var customerPhone = wechatCoreDb.Query <CustomerPhone>()
                                    .Where(m => !m.IsDel)
                                    .Where(m => m.Status == CustomerPhoneStatus.已绑定 && m.OpenId == jsCode2Json.openid)
                                    .FirstOrDefault();

                if (customerPhone != null)
                {
                    //var email = $"{customerPhone.Phone}@phone";
                    //memberId = base.memberDb.Query<Member>()
                    //    .Where(m => !m.IsDel)
                    //    .Where(m => m.Email == email)
                    //    .Select(m => m.Id)
                    //    .FirstOrDefault();

                    //获取memberId的过程,改为使用memberPhone
                    memberId = memberDb.GetMemberIdByMemberPhone(customerPhone.Phone);

                    if (memberId <= 0)
                    {
                        throw new Exception("有错误发生,没有找到Member,请重新绑定手机号");
                    }
                }


                var jwt = new MemberLogin()
                {
                    Flag      = CommonUtil.CreateNoncestr(18),
                    LoginType = "Wechat",
                    MemberId  = memberId
                };
                jwt.SetloginSettingValue("shopFlag", shopFlag);
                jwt.SetloginSettingValue("openId", jsCode2Json.openid);
                jwt.SetloginSettingValue("sessionKey", jsCode2Json.session_key);
                db.Add <MemberLogin>(jwt);

                var expiration = TimeSpan.FromDays(1000);
                var encodedJwt = MemberLogin.CreateJwtToken(jwt, expiration);
                db.SaveChanges();

                Member member = null;
                if (memberId.HasValue)
                {
                    member = memberDb.MemberDbSet().Find(memberId.Value);
                }
                bool hasUserInfo = member != null && !string.IsNullOrEmpty(member.Avatar);

                var response = new
                {
                    access_token = encodedJwt,
                    expires_in   = (int)expiration.TotalSeconds,
                    isBindPhone  = jwt.MemberId.HasValue,
                    hasUserInfo,
                    phone = customerPhone != null ? customerPhone.Phone : ""
                };

                return(Json(response));
            }
            catch (Exception ex)
            {
                _logger.LogInformation("登陆失败:{0}", ex.StackTrace);
                return(Json(new { error = ex.Message + ex.StackTrace }));
            }
        }
コード例 #13
0
        public APIResult LoginWx(string shopFlag, string code)
        {
            if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(shopFlag))
            {
                throw new ArgumentNullException("args is null");
            }

            var authorizer = db.Query <ShopWechatOpenAuthorizer>()
                             .Where(m => !m.IsDel)
                             .Where(m => m.Shop.Flag == shopFlag)
                             .Select(m => new
            {
                AuthorizerAppId = m.WechatOpenAuthorizer.AuthorizerAppId
            })
                             .FirstOrDefault();

            var jsCode2Json = getJsCode2Json(authorizer.AuthorizerAppId, code);

            if (string.IsNullOrEmpty(jsCode2Json.openid))
            {
                throw new Exception("未能获取openId");
            }
            var jwt = db.MemberLogins.FirstOrDefault(p => !p.IsDel && p.OpenId == jsCode2Json.openid && p.ShopFlag == shopFlag);

            if (jwt == null)
            {
                jwt = new MemberLogin()
                {
                    SessionKey = jsCode2Json.session_key,
                    ShopFlag   = shopFlag,
                    OpenId     = jsCode2Json.openid,
                    Flag       = CommonUtil.CreateNoncestr(18),
                    LoginType  = "Wechat"
                };
                db.Add(jwt);
            }
            jwt.SessionKey = jsCode2Json.session_key;

            jwt.SetloginSettingValue("shopFlag", shopFlag);
            jwt.SetloginSettingValue("openId", jsCode2Json.openid);
            jwt.SetloginSettingValue("sessionKey", jsCode2Json.session_key);

            db.SaveChanges();
            if (string.IsNullOrEmpty(jsCode2Json.openid))
            {
                return(Error("获取openId失败"));
            }
            string token = null;

            //若有memberId则返回token
            if (jwt.MemberId.HasValue)
            {
                var expiration = TimeSpan.FromDays(365 * 10);
                token = MemberLogin.CreateJwtToken(jwt, expiration);
            }
            var response = new
            {
                jsCode2Json.openid,
                token
            };

            return(Success(response));
        }
コード例 #14
0
        private void GetCityXiaoquDetailPageUrls(IListSheet listSheet)
        {
            String exportDir     = this.RunPage.GetExportDir();
            string pageSourceDir = this.RunPage.GetDetailSourceFileDir();

            Dictionary <string, int> resultColumnDic = new Dictionary <string, int>();

            resultColumnDic.Add("detailPageUrl", 0);
            resultColumnDic.Add("detailPageName", 1);
            resultColumnDic.Add("cookie", 2);
            resultColumnDic.Add("grabStatus", 3);
            resultColumnDic.Add("giveUpGrab", 4);
            resultColumnDic.Add("cityCode", 5);
            resultColumnDic.Add("cityName", 6);
            resultColumnDic.Add("level1AreaCode", 7);
            resultColumnDic.Add("level1AreaName", 8);
            resultColumnDic.Add("level2AreaCode", 9);
            resultColumnDic.Add("level2AreaName", 10);
            resultColumnDic.Add("name", 11);
            resultColumnDic.Add("address", 12);
            resultColumnDic.Add("sale_num", 13);
            resultColumnDic.Add("build_year", 14);
            resultColumnDic.Add("mid_price", 15);

            string      resultFilePath         = Path.Combine(exportDir, "安居客小区详情页.xlsx");
            ExcelWriter resultEW               = new ExcelWriter(resultFilePath, "List", resultColumnDic);
            Dictionary <string, string> urlDic = new Dictionary <string, string>();

            for (int i = 0; i < listSheet.RowCount; i++)
            {
                if (i % 100 == 0)
                {
                    this.RunPage.InvokeAppendLogText("正在输出Excel文件... " + ((double)(i * 100) / (double)listSheet.RowCount).ToString("0.00") + "%", LogLevelType.System, true);
                }
                Dictionary <string, string> row = listSheet.GetRow(i);
                string detailUrl      = row["detailPageUrl"];
                string cityName       = row["cityName"];
                string cityCode       = row["cityCode"];
                string level1AreaName = row["level1AreaName"];
                string level1AreaCode = row["level1AreaCode"];
                string level2AreaCode = row["level2AreaCode"];
                string level2AreaName = row["level2AreaName"];
                bool   giveUp         = "Y".Equals(row[SysConfig.GiveUpGrabFieldName]);
                if (!giveUp)
                {
                    string localFilePath    = this.RunPage.GetFilePath(detailUrl, pageSourceDir);
                    string fileText         = FileHelper.GetTextFromFile(localFilePath);
                    int    requestPageCount = int.Parse(fileText);
                    for (int j = 0; j < requestPageCount; j++)
                    {
                        string pageLocalFilePath = this.RunPage.GetFilePath(detailUrl + "?p=" + (j + 1).ToString(), pageSourceDir);
                        string pageFileText      = FileHelper.GetTextFromFile(pageLocalFilePath);
                        try
                        {
                            JObject rootJo          = JObject.Parse(pageFileText);
                            JArray  xiaoquJsonArray = rootJo["data"] as JArray;
                            for (int k = 0; k < xiaoquJsonArray.Count; k++)
                            {
                                JObject xiaoquJson = xiaoquJsonArray[k] as JObject;
                                string  name       = CommonUtil.HtmlDecode(xiaoquJson["name"].ToString());
                                string  area       = CommonUtil.HtmlDecode(xiaoquJson["area"].ToString());
                                string  address    = CommonUtil.HtmlDecode(xiaoquJson["address"].ToString());
                                string  sale_num   = xiaoquJson["sale_num"].ToString();
                                string  build_year = CommonUtil.HtmlDecode(xiaoquJson["build_year"].ToString());
                                string  mid_price  = xiaoquJson["mid_price"].ToString();
                                string  url        = CommonUtil.HtmlDecode(xiaoquJson["url"].ToString());
                                if (!urlDic.ContainsKey(url))
                                {
                                    urlDic.Add(url, null);
                                    Dictionary <string, string> f2vs = new Dictionary <string, string>();
                                    f2vs.Add("detailPageUrl", url);
                                    f2vs.Add("detailPageName", url);
                                    f2vs.Add("cityCode", cityCode);
                                    f2vs.Add("cityName", cityName);
                                    f2vs.Add("level1AreaCode", level1AreaCode);
                                    f2vs.Add("level1AreaName", level1AreaName);
                                    f2vs.Add("level2AreaCode", level2AreaCode);
                                    f2vs.Add("level2AreaName", level2AreaName);
                                    f2vs.Add("name", name);
                                    f2vs.Add("address", address);
                                    f2vs.Add("sale_num", sale_num);
                                    f2vs.Add("build_year", build_year);
                                    f2vs.Add("mid_price", mid_price);
                                    resultEW.AddRow(f2vs);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
            }
            resultEW.SaveToDisk();
            this.RunPage.InvokeAppendLogText("完成输出Excel文件... 100%", LogLevelType.System, true);
        }
コード例 #15
0
 public MobilePresenter()
 {
     objComm = new CommonUtil();
     objServiceHandler = new ServiceHandler();
     objTblSvc = new TableService();
     objSvcPre = new ServicePresenter();
     svcInfo = ServiceInfo.ServiceConfig;
 }
コード例 #16
0
 protected void Page_Init(object sender, EventArgs e)
 {
     //Initialize the objects
     objComm = new CommonUtil();
     objServiceHandler = new ServiceHandler();
     objMobPresenter = new MobilePresenter();
     svcInfo = new ServiceInfo();
     svcInfo = ServiceInfo.ServiceConfig;
 }
コード例 #17
0
    protected void btnPubMedSearch_OnClick(object sender, EventArgs e)
    {
        string value = "";

        if (rdoPubMedKeyword.Checked)
        {
            string andString = "";
            value = "(";
            if (txtSearchAuthor.Text.Length > 0)
            {
                string inputString = txtSearchAuthor.Text.Trim();

                inputString = inputString.Replace("\r\n", "|");
                // Added line to handle multiple authors for Firefox
                inputString = inputString.Replace("\n", "|");

                string[] split = inputString.Split('|');

                for (int i = 0; i < split.Length; i++)
                {
                    value = value + andString + "(" + split[i] + "[Author])";
                    andString = " AND ";
                }
            }
            if (txtSearchAffiliation.Text.Length > 0)
            {
                value = value + andString + "(" + txtSearchAffiliation.Text + "[Affiliation])";
                andString = " AND ";
            }
            if (txtSearchKeyword.Text.Length > 0)
            {
                value = value + andString + "((" + txtSearchKeyword.Text + "[Title/Abstract]) OR (" + txtSearchKeyword.Text + "[MeSH Terms]))";
            }
            value = value + ")";
        }
        else if (rdoPubMedQuery.Checked)
        {
            value = txtPubMedQuery.Text;
        }

        string orString = "";
        string idValues = "";
        //if (chkPubMedExclude.Checked)
        //{
        //    if (grdEditPublications.Rows.Count > 0)
        //    {
        //        value = value + " not (";
        //        foreach (GridViewRow gvr in grdEditPublications.Rows)
        //        {
        //            value = value + orString + (string)grdEditPublications.DataKeys[gvr.RowIndex]["PubID"]) + "[uid]";
        //            orString = " OR ";
        //        }
        //        value = value + ")";
        //    }
        //}

        if (chkPubMedExclude.Checked)
        {
            foreach (GridViewRow gvr in grdEditPublications.Rows)
            {
                HiddenField hdn = (HiddenField)gvr.FindControl("hdnPMID");
                idValues = idValues + orString + hdn.Value;
                orString = ",";
            }
        }

        CommonUtil commonUtil = new CommonUtil();
        Hashtable MyParameters = new Hashtable();

        string uri = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&usehistory=y&retmax=100&retmode=xml&term=" + value;
        System.Xml.XmlDocument myXml = new System.Xml.XmlDocument();
        myXml.LoadXml(commonUtil.HttpPost(uri, "Catalyst", "text/plain"));

        XmlNodeList xnList;
        string queryKey = "";
        string webEnv = "";

        xnList = myXml.SelectNodes("/eSearchResult");

        foreach (XmlNode xn in xnList)
        {
            queryKey = xn["QueryKey"].InnerText;
            webEnv = xn["WebEnv"].InnerText;
        }

        //string queryKey = MyGetXmlNodeValue(myXml, "QueryKey", "");
        //string webEnv = MyGetXmlNodeValue(myXml, "WebEnv", "");

        uri = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?retmin=0&retmax=100&retmode=xml&db=Pubmed&query_key=" + queryKey + "&webenv=" + webEnv;
        myXml.LoadXml(commonUtil.HttpPost(uri, "Catalyst", "text/plain"));

        string pubMedAuthors = "";
        string pubMedTitle = "";
        string pubMedSO = "";
        string pubMedID = "";
        string seperator = "";

        PubMedResults.Tables.Clear();
        PubMedResults.Tables.Add("Results");
        PubMedResults.Tables["Results"].Columns.Add(new System.Data.DataColumn("pmid"));
        PubMedResults.Tables["Results"].Columns.Add(new System.Data.DataColumn("citation"));
        PubMedResults.Tables["Results"].Columns.Add(new System.Data.DataColumn("checked"));

        XmlNodeList docSums = myXml.SelectNodes("eSummaryResult/DocSum");
        foreach (XmlNode docSum in docSums)
        {
            pubMedAuthors = "";
            pubMedTitle = "";
            pubMedSO = "";
            pubMedID = "";
            seperator = "";
            XmlNodeList authors = docSum.SelectNodes("Item[@Name='AuthorList']/Item[@Name='Author']");
            foreach (XmlNode author in authors)
            {
                pubMedAuthors = pubMedAuthors + seperator + author.InnerText;
                seperator = ", ";
            }
            pubMedTitle = docSum.SelectSingleNode("Item[@Name='Title']").InnerText;
            pubMedSO = docSum.SelectSingleNode("Item[@Name='SO']").InnerText;
            pubMedID = docSum.SelectSingleNode("Id").InnerText;

            if (!idValues.Contains(pubMedID))
            {
                DataRow myDataRow = PubMedResults.Tables["Results"].NewRow();
                myDataRow["pmid"] = pubMedID;
                myDataRow["checked"] = "0";
                myDataRow["citation"] = pubMedAuthors + "; " + pubMedTitle + "; " + pubMedSO;
                PubMedResults.Tables["Results"].Rows.Add(myDataRow);
                PubMedResults.AcceptChanges();
            }
        }

        grdPubMedSearchResults.DataSource = PubMedResults;
        grdPubMedSearchResults.DataBind();

        lblPubMedResultsHeader.Text = "PubMed Results (" + PubMedResults.Tables["Results"].Rows.Count.ToString() + ")";

        pnlAddPubMedResults.Visible = true;
        upnlEditSection.Update();
    }
コード例 #18
0
    //Inserts comma seperated string of PubMed Ids into the db
    private void InsertPubMedIds(string value)
    {
        CommonUtil commonUtil = new CommonUtil();
        string uri = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?retmax=1000&db=pubmed&retmode=xml&id=" + value;

        System.Xml.XmlDocument myXml = new System.Xml.XmlDocument();
        myXml.LoadXml(commonUtil.HttpPost(uri, "Catalyst", "text/plain"));
        XmlNodeList nodes = myXml.SelectNodes("PubmedArticleSet/PubmedArticle");
        foreach (XmlNode node in nodes)
        {
            string pmid = node.SelectSingleNode("MedlineCitation/PMID").InnerText;

            if (!_pubBL.CheckPublicationExists(pmid))
                // Insert or update the publication
                _pubBL.InsertPublication(pmid, node.OuterXml);

            // Assign the user to the publication
            _pubBL.AddUserPublication(_personId, Convert.ToInt32(pmid));
            // Profiles OpenSocial Extension by UCSF
            if (lblVisiblePublication.Visible)
            {
                OpenSocialHelper.PostActivity(_personId, "added a publication", "added PubMed publication PMID=" + pmid + " to their profile", "PMID", pmid);
            }
        }
    }
コード例 #19
0
 /// <summary>
 /// Get data for initialize search payment result grid.
 /// </summary>
 /// <returns>Return ActionResult of JSON data data for initialize search payment result grid.</returns>
 public ActionResult ICS110_InitialSearchPaymentResultGrid()
 {
     return(Json(CommonUtil.ConvertToXml <object>(null, "Income\\ICS110_SearchPaymentResult", CommonUtil.GRID_EMPTY_TYPE.SEARCH)));
 }
コード例 #20
0
        private void GenerateRelatedItemFile(string fromItemId, string fromItemName, string fromItemTitle, string fromItemUrl, HtmlNodeCollection aNodes)
        {
            String exportDir      = this.RunPage.GetExportDir();
            string partDir        = CommonUtil.MD5Crypto(fromItemTitle + "_" + fromItemId).Substring(0, 4);
            string resultFilePath = Path.Combine(exportDir, partDir + "/易贸商务_百度百科_词条关联_" + CommonUtil.ProcessFileName(fromItemTitle, "_") + "_" + fromItemId + ".xlsx");

            if (!File.Exists(resultFilePath))
            {
                Dictionary <string, int> resultColumnDic = new Dictionary <string, int>();
                resultColumnDic.Add("fromItemUrl", 0);
                resultColumnDic.Add("fromItemId", 1);
                resultColumnDic.Add("fromItemName", 2);
                resultColumnDic.Add("fromItemTitle", 3);
                resultColumnDic.Add("toItemUrl", 4);
                resultColumnDic.Add("toItemId", 5);
                resultColumnDic.Add("toItemName", 6);
                ExcelWriter resultEW = new ExcelWriter(resultFilePath, "List", resultColumnDic, null);
                Dictionary <string, bool> itemMaps = new Dictionary <string, bool>();

                for (int j = 0; j < aNodes.Count; j++)
                {
                    HtmlNode aNode      = aNodes[j];
                    string   toItemUrl  = aNode.GetAttributeValue("href", "");
                    string   toItemId   = aNode.GetAttributeValue("data-lemmaid", "");
                    string   toItemName = CommonUtil.HtmlDecode(aNode.InnerText).Trim();
                    if (toItemUrl.StartsWith("/item/") && !itemMaps.ContainsKey(toItemUrl) && this.IsInMainContent(aNode))
                    {
                        itemMaps.Add(toItemUrl, true);

                        string toItemFullUrl = "https://baike.baidu.com" + toItemUrl;
                        Dictionary <string, string> relatedItemRow = new Dictionary <string, string>();
                        relatedItemRow.Add("fromItemUrl", fromItemUrl);
                        relatedItemRow.Add("fromItemId", fromItemId);
                        relatedItemRow.Add("fromItemName", fromItemName);
                        relatedItemRow.Add("fromItemTitle", fromItemTitle);
                        relatedItemRow.Add("toItemUrl", toItemFullUrl);
                        relatedItemRow.Add("toItemId", toItemId);
                        relatedItemRow.Add("toItemName", toItemName);

                        resultEW.AddRow(relatedItemRow);
                    }
                }
                resultEW.SaveToDisk();
            }
        }
コード例 #21
0
        public string GetTextByRequest(string pageUrl, Dictionary <string, string> listRow, bool needProxy, decimal intervalAfterLoaded, int timeout, Encoding encoding, string cookie, string xRequestedWith, bool autoAbandonDisableProxy, Proj_DataAccessType dataAccessType, Proj_CompleteCheckList completeChecks, int intervalProxyRequest)
        {
            NDAWebClient client = null;

            try
            {
                DateTime dt1 = DateTime.Now;
                client    = new NDAWebClient();
                client.Id = pageUrl;
                client.ResponseEncoding = encoding;
                System.Net.ServicePointManager.DefaultConnectionLimit = 512;
                client.Timeout = timeout;
                if (needProxy)
                {
                    client.ProxyServer = this.RunPage.CurrentProxyServers.BeginUse(intervalProxyRequest);
                }
                //client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

                string userAgent = this.RunPage.CurrentUserAgents.GetOneUserAgent();
                client.Headers.Add("user-agent", userAgent);
                if (!CommonUtil.IsNullOrBlank(cookie))
                {
                    client.Headers.Add("cookie", cookie);
                    //client.Headers.Add("connection", "keep-alive");
                }
                client.Headers.Add("x-requested-with", "XMLHttpRequest");

                client.OpenReadCompleted += client_OpenReadCompleted;
                client.OpenReadAsync(new Uri(pageUrl));

                int    waitingTime = 0;
                object data        = null;
                while (data == null && waitingTime < timeout)
                {
                    data = GetResponseString(client.Id);
                    if (data == null)
                    {
                        waitingTime = waitingTime + 3000;
                        Thread.Sleep(3000);
                    }
                }

                if (data != null)
                {
                    RemoveResponseData(client.Id);
                    if (data is Exception)
                    {
                        throw (Exception)data;
                    }
                    else
                    {
                        string s = null;
                        if (data is string)
                        {
                            s = (string)data;
                        }
                        if (data is byte[])
                        {
                            s = encoding.GetString((byte[])data);
                        }

                        this.CheckRequestCompleteFile(s, listRow);

                        if (needProxy)
                        {
                            this.RunPage.CurrentProxyServers.Success(client.ProxyServer);
                        }

                        //再增加个等待,等待异步加载的数据
                        Thread.Sleep((int)intervalAfterLoaded);

                        DateTime dt2 = DateTime.Now;
                        double   ts  = (dt2 - dt1).TotalSeconds;
                        return(s);
                    }
                }
                else
                {
                    throw new Exception("访问超时.");
                }
            }
            catch (NoneProxyException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                string errorInfo = "";
                if (needProxy)
                {
                    if (autoAbandonDisableProxy)
                    {
                        this.RunPage.CurrentProxyServers.Error(client.ProxyServer);
                        if (client.ProxyServer.IsAbandon)
                        {
                            errorInfo = "放弃代理服务器:" + client.ProxyServer.IP + ":" + client.ProxyServer.Port.ToString() + ". ";
                        }
                        else
                        {
                            errorInfo = "代理服务器:" + client.ProxyServer.IP + ":" + client.ProxyServer.Port.ToString() + ". ";
                        }
                    }
                    else
                    {
                        errorInfo = "代理服务器:" + client.ProxyServer.IP + ":" + client.ProxyServer.Port.ToString() + ". ";
                    }
                }

                errorInfo = "获取网页失败.\r\n" + errorInfo + " " + pageUrl;
                throw new GrabRequestException(errorInfo, ex);
            }
            finally
            {
                if (needProxy)
                {
                    this.RunPage.CurrentProxyServers.EndUse(client.ProxyServer);
                }
            }
        }
コード例 #22
0
        private void GetRelatedItemPageUrls(IListSheet listSheet)
        {
            string sourceDir = this.RunPage.GetDetailSourceFileDir();

            ExcelWriter moreItemEW = null;
            int         rowCount   = 0;

            Dictionary <string, bool> itemMaps = new Dictionary <string, bool>();
            int pageIndex = 0;

            for (int i = 0; i < listSheet.RowCount; i++)
            {
                Dictionary <string, string> listRow = listSheet.GetRow(i);
                string fromItemUrl = listRow[SysConfig.DetailPageUrlFieldName];

                itemMaps.Add(fromItemUrl, true);

                Dictionary <string, string> moreItemRow = new Dictionary <string, string>();
                moreItemRow.Add("detailPageUrl", fromItemUrl);
                moreItemRow.Add("detailPageName", fromItemUrl);
                moreItemRow.Add("itemId", listRow["itemId"]);
                moreItemRow.Add("itemName", listRow["itemName"]);
                this.AddToMoreExcelWriter(ref pageIndex, ref moreItemEW, moreItemRow, ref rowCount);
            }

            for (int i = 0; i < listSheet.RowCount; i++)
            {
                Dictionary <string, string> listRow = listSheet.GetRow(i);
                bool   giveUp      = "Y".Equals(listRow[SysConfig.GiveUpGrabFieldName]);
                string fromItemUrl = listRow[SysConfig.DetailPageUrlFieldName];
                if (!giveUp)
                {
                    try
                    {
                        string localFilePath = this.RunPage.GetFilePath(fromItemUrl, sourceDir);
                        string html          = FileHelper.GetTextFromFile(localFilePath, Encoding.UTF8);
                        if (!html.Contains("您所访问的页面不存在"))
                        {
                            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                            htmlDoc.LoadHtml(html);

                            HtmlNode titleNode = htmlDoc.DocumentNode.SelectSingleNode("//dd[@class=\"lemmaWgt-lemmaTitle-title\"]/h1");
                            if (titleNode == null)
                            {
                                this.RunPage.InvokeAppendLogText("此词条不存在,百度没有收录, pageUrl = " + fromItemUrl, LogLevelType.Error, true);
                            }
                            else
                            {
                                string fromItemName = CommonUtil.HtmlDecode(titleNode.InnerText).Trim();

                                HtmlNode itemBaseInfoNode = htmlDoc.DocumentNode.SelectSingleNode("//div[@class=\"lemmaWgt-promotion-rightPreciseAd\"]");
                                string   fromItemId       = itemBaseInfoNode.GetAttributeValue("data-lemmaid", "");
                                string   fromItemTitle    = itemBaseInfoNode.GetAttributeValue("data-lemmatitle", "");

                                HtmlNodeCollection aNodes = htmlDoc.DocumentNode.SelectNodes("//a");
                                for (int j = 0; j < aNodes.Count; j++)
                                {
                                    HtmlNode aNode         = aNodes[j];
                                    string   toItemUrl     = aNode.GetAttributeValue("href", "");
                                    string   toItemId      = aNode.GetAttributeValue("data-lemmaid", "");
                                    string   toItemName    = CommonUtil.HtmlDecode(aNode.InnerText).Trim();
                                    string   toItemFullUrl = "https://baike.baidu.com" + toItemUrl;
                                    if (toItemUrl.StartsWith("/item/") && !itemMaps.ContainsKey(toItemFullUrl) && this.IsInMainContent(aNode))
                                    {
                                        itemMaps.Add(toItemFullUrl, true);

                                        Dictionary <string, string> moreItemRow = new Dictionary <string, string>();
                                        moreItemRow.Add("detailPageUrl", toItemFullUrl);
                                        moreItemRow.Add("detailPageName", toItemFullUrl);
                                        moreItemRow.Add("itemId", toItemId);
                                        moreItemRow.Add("itemName", toItemName);

                                        this.AddToMoreExcelWriter(ref pageIndex, ref moreItemEW, moreItemRow, ref rowCount);
                                    }
                                }

                                this.GenerateRelatedItemFile(fromItemId, fromItemName, fromItemTitle, fromItemUrl, aNodes);
                            }
                        }
                        else
                        {
                            this.RunPage.InvokeAppendLogText("放弃解析此页, 所访问的页面不存在, pageUrl = " + fromItemUrl, LogLevelType.Error, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        this.RunPage.InvokeAppendLogText(ex.Message + ". 解析出错, pageUrl = " + fromItemUrl, LogLevelType.Error, true);
                        throw ex;
                    }
                }
            }

            moreItemEW.SaveToDisk();
        }
コード例 #23
0
        private void GetXiaoquErshoufangListPageUrls(IListSheet listSheet)
        {
            string pageSourceDir = this.RunPage.GetDetailSourceFileDir();
            Dictionary <string, ExcelWriter> cityToEW        = new Dictionary <string, ExcelWriter>();
            Dictionary <string, int>         cityToFileIndex = new Dictionary <string, int>();
            Dictionary <string, string>      urlDic          = new Dictionary <string, string>();

            for (int i = 0; i < listSheet.RowCount; i++)
            {
                Dictionary <string, string> row = listSheet.GetRow(i);
                string      detailUrl           = row["detailPageUrl"];
                string      cityName            = row["cityName"];
                ExcelWriter resultEW            = cityToEW.ContainsKey(cityName) ? cityToEW[cityName] : null;

                if (resultEW == null || resultEW.RowCount > 500000)
                {
                    if (resultEW != null)
                    {
                        resultEW.SaveToDisk();
                    }
                    int fileIndex = cityToFileIndex.ContainsKey(cityName) ? cityToFileIndex[cityName] : 1;
                    resultEW = this.GetErshoufangExcelWriter(fileIndex, cityName);
                    fileIndex++;
                    cityToEW[cityName]        = resultEW;
                    cityToFileIndex[cityName] = fileIndex;
                }

                if (i % 100 == 0)
                {
                    this.RunPage.InvokeAppendLogText("正在输出二手房列表页Excel文件... " + ((double)(i * 100) / (double)listSheet.RowCount).ToString("0.00") + "%", LogLevelType.System, true);
                }

                bool giveUp = "Y".Equals(row[SysConfig.GiveUpGrabFieldName]);
                if (!giveUp)
                {
                    string localFilePath    = this.RunPage.GetFilePath(detailUrl, pageSourceDir);
                    string fileText         = FileHelper.GetTextFromFile(localFilePath);
                    int    requestPageCount = int.Parse(fileText);
                    for (int j = 0; j < requestPageCount; j++)
                    {
                        string pageLocalFilePath = this.RunPage.GetFilePath(detailUrl + "?p=" + (j + 1).ToString(), pageSourceDir);
                        string pageFileText      = FileHelper.GetTextFromFile(pageLocalFilePath);
                        try
                        {
                            JObject rootJo          = JObject.Parse(pageFileText);
                            JArray  xiaoquJsonArray = rootJo["data"] as JArray;
                            for (int k = 0; k < xiaoquJsonArray.Count; k++)
                            {
                                JObject xiaoquJson  = xiaoquJsonArray[k] as JObject;
                                string  xiaoquName  = CommonUtil.HtmlDecode(xiaoquJson["name"].ToString());
                                string  sale_numStr = xiaoquJson["sale_num"].ToString().Trim();
                                int     saleNum     = sale_numStr.Length == 0 ? 0 : int.Parse(sale_numStr);
                                string  xiaoquUrl   = CommonUtil.HtmlDecode(xiaoquJson["url"].ToString());
                                if (!urlDic.ContainsKey(xiaoquUrl) && saleNum > 0)
                                {
                                    urlDic.Add(xiaoquUrl, null);
                                    int pageIndex = 0;
                                    while (pageIndex * 60 < saleNum)
                                    {
                                        Dictionary <string, string> f2vs = new Dictionary <string, string>();
                                        string ershoufangPageUrl         = xiaoquUrl + "esf/?page=" + (pageIndex + 1).ToString();
                                        f2vs.Add("detailPageUrl", ershoufangPageUrl);
                                        f2vs.Add("detailPageName", ershoufangPageUrl);
                                        f2vs.Add("saleNum", sale_numStr);
                                        f2vs.Add("xiaoquName", xiaoquName);
                                        f2vs.Add("xiaoquUrl", xiaoquUrl);
                                        f2vs.Add("cityName", row["cityName"]);
                                        f2vs.Add("cityCode", row["cityCode"]);
                                        f2vs.Add("level1AreaName", row["level1AreaName"]);
                                        f2vs.Add("level1AreaCode", row["level1AreaCode"]);
                                        f2vs.Add("level2AreaCode", row["level2AreaCode"]);
                                        f2vs.Add("level2AreaName", row["level2AreaName"]);
                                        resultEW.AddRow(f2vs);
                                        pageIndex++;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
            }
            foreach (string cityName in cityToEW.Keys)
            {
                ExcelWriter resultEW = cityToEW[cityName];
                resultEW.SaveToDisk();
            }
        }
コード例 #24
0
ファイル: ClientEdmModel.cs プロジェクト: zdzislaw/odata.net
        private EdmTypeCacheValue GetOrCreateEdmTypeInternal(IEdmStructuredType edmBaseType, Type type, PropertyInfo[] keyProperties, bool isEntity, bool?hasProperties)
        {
            Debug.Assert(type != null, "type != null");
            Debug.Assert(keyProperties != null, "keyProperties != null");

            EdmTypeCacheValue cachedEdmType;

            lock (this.clrToEdmTypeCache)
            {
                this.clrToEdmTypeCache.TryGetValue(type, out cachedEdmType);
            }

            if (cachedEdmType == null)
            {
                Type collectionType;
                if (PrimitiveType.IsKnownNullableType(type))
                {
                    PrimitiveType primitiveType;
                    PrimitiveType.TryGetPrimitiveType(type, out primitiveType);
                    Debug.Assert(primitiveType != null, "primitiveType != null");
                    cachedEdmType = new EdmTypeCacheValue(primitiveType.CreateEdmPrimitiveType(), hasProperties);
                }
                else if ((collectionType = ClientTypeUtil.GetImplementationType(type, typeof(ICollection <>))) != null && ClientTypeUtil.GetImplementationType(type, typeof(IDictionary <,>)) == null)
                {
                    // Collection Type
                    Type     elementType = collectionType.GetGenericArguments()[0];
                    IEdmType itemType    = this.GetOrCreateEdmType(elementType);

                    // Note that
                    // 1. throw here because collection of a collection is not allowed
                    // 2. will also throw during SaveChanges(), validated by unit test case 'SerializationOfCollection'in CollectionTests.cs.
                    if ((itemType.TypeKind == EdmTypeKind.Collection))
                    {
                        throw new ODataException(Strings.ClientType_CollectionOfCollectionNotSupported);
                    }

                    cachedEdmType = new EdmTypeCacheValue(new EdmCollectionType(itemType.ToEdmTypeReference(ClientTypeUtil.CanAssignNull(elementType))), hasProperties);
                }
                else
                {
                    Type enumTypeTmp = null;
                    if (isEntity)
                    {
                        Action <EdmEntityTypeWithDelayLoadedProperties> delayLoadEntityProperties = (entityType) =>
                        {
                            // Create properties without modifying the entityType.
                            // This will leave entityType intact in case of an exception during loading.
                            List <IEdmProperty>           loadedProperties    = new List <IEdmProperty>();
                            List <IEdmStructuralProperty> loadedKeyProperties = new List <IEdmStructuralProperty>();
                            foreach (PropertyInfo property in ClientTypeUtil.GetPropertiesOnType(type, /*declaredOnly*/ edmBaseType != null).OrderBy(p => p.Name))
                            {
                                IEdmProperty edmProperty = this.CreateEdmProperty((EdmStructuredType)entityType, property);
                                loadedProperties.Add(edmProperty);

                                if (edmBaseType == null && keyProperties.Any(k => k.DeclaringType == type && k.Name == property.Name))
                                {
                                    Debug.Assert(edmProperty.PropertyKind == EdmPropertyKind.Structural, "edmProperty.PropertyKind == EdmPropertyKind.Structural");
                                    Debug.Assert(edmProperty.Type.TypeKind() == EdmTypeKind.Primitive, "edmProperty.Type.TypeKind() == EdmTypeKind.Primitive");
                                    loadedKeyProperties.Add((IEdmStructuralProperty)edmProperty);
                                }
                            }

                            // Now add properties to the entityType.
                            foreach (IEdmProperty property in loadedProperties)
                            {
                                entityType.AddProperty(property);
                            }

                            entityType.AddKeys(loadedKeyProperties);
                        };

                        // Creating an entity type
                        Debug.Assert(edmBaseType == null || edmBaseType.TypeKind == EdmTypeKind.Entity, "baseType == null || baseType.TypeKind == EdmTypeKind.Entity");
                        bool hasStream = GetHasStreamValue((IEdmEntityType)edmBaseType, type);
                        cachedEdmType = new EdmTypeCacheValue(
                            new EdmEntityTypeWithDelayLoadedProperties(CommonUtil.GetModelTypeNamespace(type), CommonUtil.GetModelTypeName(type), (IEdmEntityType)edmBaseType, c.PlatformHelper.IsAbstract(type), /*isOpen*/ false, hasStream, delayLoadEntityProperties),
                            hasProperties);
                    }
                    else if ((enumTypeTmp = Nullable.GetUnderlyingType(type) ?? type) != null &&
                             enumTypeTmp.IsEnum())
                    {
                        Action <EdmEnumTypeWithDelayLoadedMembers> delayLoadEnumMembers = (enumType) =>
                        {
#if WINRT
                            foreach (FieldInfo tmp in enumTypeTmp.GetFields().Where(fieldInfo => fieldInfo.IsStatic))
#else
                            foreach (FieldInfo tmp in enumTypeTmp.GetFields(BindingFlags.Static | BindingFlags.Public))
#endif
                            {
                                object memberValue = Enum.Parse(enumTypeTmp, tmp.Name, false);
                                enumType.AddMember(new EdmEnumMember(enumType, tmp.Name, new EdmIntegerConstant((long)Convert.ChangeType(memberValue, typeof(long), CultureInfo.InvariantCulture.NumberFormat))));
                            }
                        };

                        // underlying type may be Edm.Byte, Edm.SByte, Edm.Int16, Edm.Int32, or Edm.Int64.
                        Type underlyingType = Enum.GetUnderlyingType(enumTypeTmp);
                        IEdmPrimitiveType underlyingEdmType = (IEdmPrimitiveType)EdmCoreModel.Instance.FindDeclaredType("Edm." + underlyingType.Name);
                        Debug.Assert(underlyingEdmType != null, "underlyingEdmType != null");
                        bool isFlags = enumTypeTmp.GetCustomAttributes(false).Any(s => s is FlagsAttribute);
                        cachedEdmType = new EdmTypeCacheValue(
                            new EdmEnumTypeWithDelayLoadedMembers(CommonUtil.GetModelTypeNamespace(enumTypeTmp), CommonUtil.GetModelTypeName(enumTypeTmp), underlyingEdmType, isFlags, delayLoadEnumMembers),
                            null);
                    }
                    else
                    {
                        Action <EdmComplexTypeWithDelayLoadedProperties> delayLoadComplexProperties = (complexType) =>
                        {
                            // Create properties without modifying the complexType.
                            // This will leave complexType intact in case of an exception during loading.
                            List <IEdmProperty> loadedProperties = new List <IEdmProperty>();
                            foreach (PropertyInfo property in ClientTypeUtil.GetPropertiesOnType(type, /*declaredOnly*/ edmBaseType != null).OrderBy(p => p.Name))
                            {
                                IEdmProperty edmProperty = this.CreateEdmProperty(complexType, property);
                                loadedProperties.Add(edmProperty);
                            }

                            // Now add properties to the complexType.
                            foreach (IEdmProperty property in loadedProperties)
                            {
                                complexType.AddProperty(property);
                            }
                        };

                        // Creating a complex type
                        Debug.Assert(edmBaseType == null || edmBaseType.TypeKind == EdmTypeKind.Complex, "baseType == null || baseType.TypeKind == EdmTypeKind.Complex");
                        cachedEdmType = new EdmTypeCacheValue(
                            new EdmComplexTypeWithDelayLoadedProperties(CommonUtil.GetModelTypeNamespace(type), CommonUtil.GetModelTypeName(type), (IEdmComplexType)edmBaseType, c.PlatformHelper.IsAbstract(type), /*isOpen*/ false, delayLoadComplexProperties),
                            hasProperties);
                    }
                }

                Debug.Assert(cachedEdmType != null, "cachedEdmType != null");

                IEdmType             edmType = cachedEdmType.EdmType;
                ClientTypeAnnotation clientTypeAnnotation = this.GetOrCreateClientTypeAnnotation(edmType, type);
                this.SetClientTypeAnnotation(edmType, clientTypeAnnotation);

                if (edmType.TypeKind == EdmTypeKind.Entity || edmType.TypeKind == EdmTypeKind.Complex)
                {
                    IEdmStructuredType edmStructuredType = edmType as IEdmStructuredType;
                    Debug.Assert(edmStructuredType != null, "edmStructuredType != null");
                    this.SetMimeTypeForProperties(edmStructuredType);
                }

                // Need to cache the type before loading the properties so we don't stack overflow because
                // loading the property can trigger calls to GetOrCreateEdmType on the same type.
                lock (this.clrToEdmTypeCache)
                {
                    EdmTypeCacheValue existing;
                    if (this.clrToEdmTypeCache.TryGetValue(type, out existing))
                    {
                        cachedEdmType = existing;
                    }
                    else
                    {
                        this.clrToEdmTypeCache.Add(type, cachedEdmType);
                    }
                }
            }

            return(cachedEdmType);
        }
コード例 #25
0
        public APIResult LoginByWxAuth([FromBody] LoginByWxAuthApiModel apiArgs)
        {
            if (string.IsNullOrWhiteSpace(apiArgs.code) || string.IsNullOrWhiteSpace(apiArgs.shopFlag))
            {
                throw new ArgumentNullException("args is null");
            }

            var authorizer = db.Query <ShopWechatOpenAuthorizer>()
                             .Where(m => !m.IsDel)
                             .Where(m => m.Shop.Flag == apiArgs.shopFlag)
                             .Select(m => new
            {
                m.WechatOpenAuthorizer.AuthorizerAppId
            })
                             .FirstOrDefault();

            var jsCode2Json = getJsCode2Json(authorizer.AuthorizerAppId, apiArgs.code);

            ///根据sessionkey 解密userinfo
            var json = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedData(jsCode2Json.session_key, apiArgs.encryptedData, apiArgs.iv);
            var args = Newtonsoft.Json.JsonConvert.DeserializeObject <Senparc.Weixin.WxOpen.Entities.DecodedUserInfo>(json);

            //查询数据库是否存在此member,没有则创建Member
            var member = memberDb.Query <Member>().FirstOrDefault(p => p.UnionId == args.unionId);

            if (member == null)
            {
                member = new Member()
                {
                    Truename = "WechatUser",
                    Avatar   = args.avatarUrl,
                    NickName = args.nickName,
                    RegTime  = DateTime.Now,
                    Status   = MemberStatus.正常,
                    UnionId  = args.unionId
                };
                memberDb.Add(member);
                memberDb.SaveChanges();
            }
            var jwt = db.MemberLogins.FirstOrDefault(p => !p.IsDel && p.OpenId == jsCode2Json.openid && p.ShopFlag == apiArgs.shopFlag);

            if (jwt == null)
            {
                jwt = new MemberLogin()
                {
                    ShopFlag  = apiArgs.shopFlag,
                    OpenId    = jsCode2Json.openid,
                    Flag      = CommonUtil.CreateNoncestr(18),
                    LoginType = "Wechat",
                    MemberId  = member.Id
                };
                db.Add(jwt);
            }
            jwt.SessionKey = jsCode2Json.session_key;
            jwt.SetloginSettingValue("shopFlag", apiArgs.shopFlag);
            jwt.SetloginSettingValue("openId", jsCode2Json.openid);
            jwt.SetloginSettingValue("sessionKey", jsCode2Json.session_key);
            db.SaveChanges();

            var expiration = TimeSpan.FromDays(3650);
            var encodedJwt = MemberLogin.CreateJwtToken(jwt, expiration);
            var response   = new
            {
                access_token = encodedJwt
            };

            return(Success(response));
        }
コード例 #26
0
    void initEquip()
    {
        // 战力
        {
            PlayerData.ZhanLi = 100 + PlayerData.UserInfoData.EquipList.Count * 1000;
            ZhanLi.text       = PlayerData.ZhanLi.ToString();
        }

        EquipItems.transform.Find("Equip_wuqi/Button").transform.localScale      = new Vector3(0, 0, 0);
        EquipItems.transform.Find("Equip_yifu/Button").transform.localScale      = new Vector3(0, 0, 0);
        EquipItems.transform.Find("Equip_xiezi/Button").transform.localScale     = new Vector3(0, 0, 0);
        EquipItems.transform.Find("Equip_maozi/Button").transform.localScale     = new Vector3(0, 0, 0);
        EquipItems.transform.Find("Equip_xianglian/Button").transform.localScale = new Vector3(0, 0, 0);
        EquipItems.transform.Find("Equip_huwan/Button").transform.localScale     = new Vector3(0, 0, 0);

        for (int i = 0; i < PlayerData.UserInfoData.EquipList.Count; i++)
        {
            int id = PlayerData.UserInfoData.EquipList[i];
            switch (id)
            {
            // 武器
            case 101:
            {
                EquipItems.transform.Find("Equip_wuqi/Button").transform.localScale = new Vector3(1, 1, 1);
                CommonUtil.setImageSprite(EquipItems.transform.Find("Equip_wuqi/Button").GetComponent <Image>(), "Sprites/PlayerInfo/icon_" + id);
            }
            break;

            // 衣服
            case 102:
            {
                EquipItems.transform.Find("Equip_yifu/Button").transform.localScale = new Vector3(1, 1, 1);
                CommonUtil.setImageSprite(EquipItems.transform.Find("Equip_yifu/Button").GetComponent <Image>(), "Sprites/PlayerInfo/icon_" + id);
            }
            break;

            // 鞋子
            case 103:
            {
                EquipItems.transform.Find("Equip_xiezi/Button").transform.localScale = new Vector3(1, 1, 1);
                CommonUtil.setImageSprite(EquipItems.transform.Find("Equip_xiezi/Button").GetComponent <Image>(), "Sprites/PlayerInfo/icon_" + id);
            }
            break;

            // 帽子
            case 104:
            {
                EquipItems.transform.Find("Equip_maozi/Button").transform.localScale = new Vector3(1, 1, 1);
                CommonUtil.setImageSprite(EquipItems.transform.Find("Equip_maozi/Button").GetComponent <Image>(), "Sprites/PlayerInfo/icon_" + id);
            }
            break;

            // 项链
            case 105:
            {
                EquipItems.transform.Find("Equip_xianglian/Button").transform.localScale = new Vector3(1, 1, 1);
                CommonUtil.setImageSprite(EquipItems.transform.Find("Equip_xianglian/Button").GetComponent <Image>(), "Sprites/PlayerInfo/icon_" + id);
            }
            break;

            // 护腕
            case 106:
            {
                EquipItems.transform.Find("Equip_huwan/Button").transform.localScale = new Vector3(1, 1, 1);
                CommonUtil.setImageSprite(EquipItems.transform.Find("Equip_huwan/Button").GetComponent <Image>(), "Sprites/PlayerInfo/icon_" + id);
            }
            break;
            }
        }
    }
コード例 #27
0
        public void SetRecordProperties(JObject recordJSON, ZCRMRecord record)
        {
            foreach (KeyValuePair <string, JToken> token in recordJSON)
            {
                string fieldAPIName = token.Key;
                if (fieldAPIName.Equals("id"))
                {
                    record.EntityId = Convert.ToInt64(token.Value);
                }
                else if (fieldAPIName.Equals("Product_Details"))
                {
                    SetInventoryLineItems(token.Value);
                }
                else if (fieldAPIName.Equals("Participants"))
                {
                    SetParticipants(token.Value);
                }
                else if (fieldAPIName.Equals("Pricing_Details"))
                {
                    SetPriceDetails((JArray)token.Value);
                }
                else if (fieldAPIName.Equals("Created_By") && token.Value.Type != JTokenType.Null)
                {
                    JObject  createdObject = (JObject)token.Value;
                    ZCRMUser createdUser   = ZCRMUser.GetInstance(Convert.ToInt64(createdObject["id"]), (string)createdObject["name"]);
                    record.CreatedBy = createdUser;
                }
                else if (fieldAPIName.Equals("Modified_By") && token.Value.Type != JTokenType.Null)
                {
                    JObject  modifiedObject = (JObject)token.Value;
                    ZCRMUser modifiedBy     = ZCRMUser.GetInstance(Convert.ToInt64(modifiedObject["id"]), (string)modifiedObject["name"]);
                    record.ModifiedBy = modifiedBy;
                }
                else if (fieldAPIName.Equals("Created_Time"))
                {
                    record.CreatedTime = CommonUtil.removeEscaping((string)JsonConvert.SerializeObject(token.Value));
                }
                else if (fieldAPIName.Equals("Modified_Time"))
                {
                    record.ModifiedTime = CommonUtil.removeEscaping((string)JsonConvert.SerializeObject(token.Value));
                }
                else if (fieldAPIName.Equals("Owner") && token.Value.Type != JTokenType.Null)
                {
                    JObject  ownerObject = (JObject)token.Value;
                    ZCRMUser ownerUser   = ZCRMUser.GetInstance(Convert.ToInt64(ownerObject["id"]), (string)ownerObject["name"]);
                    record.Owner = ownerUser;
                }
                else if (fieldAPIName.Equals("Layout") && token.Value.Type != JTokenType.Null)
                {
                    JObject    layoutObject = (JObject)token.Value;
                    ZCRMLayout layout       = ZCRMLayout.GetInstance(Convert.ToInt64(layoutObject["id"]));
                    layout.Name = (string)layoutObject["name"];
                }
                else if (fieldAPIName.Equals("Handler") && token.Value.Type != JTokenType.Null)
                {
                    JObject  handlerObject = (JObject)token.Value;
                    ZCRMUser handler       = ZCRMUser.GetInstance(Convert.ToInt64(handlerObject["id"]), (string)handlerObject["name"]);
                    record.SetFieldValue(fieldAPIName, handler);
                }

                else if (fieldAPIName.Equals("Remind_At") && token.Value.Type != JTokenType.Null)
                {
                    if (token.Value is JObject)
                    {
                        JObject remindObject = (JObject)token.Value;
                        record.SetFieldValue(fieldAPIName, remindObject["ALARM"]);
                    }
                    else
                    {
                        record.SetFieldValue(fieldAPIName, token.Value);
                    }
                }
                else if (fieldAPIName.Equals("Recurring_Activity") && token.Value.Type != JTokenType.Null)
                {
                    JObject recurringActivityObject = (JObject)token.Value;
                    record.SetFieldValue(fieldAPIName, recurringActivityObject["RRULE"]);
                }
                else if (fieldAPIName.Equals("$line_tax") && token.Value.Type != JTokenType.Null)
                {
                    JArray taxDetails = (JArray)token.Value;
                    foreach (JObject taxDetail in taxDetails)
                    {
                        ZCRMTax tax = ZCRMTax.GetInstance((string)taxDetail["name"]);
                        tax.Percentage = Convert.ToDouble(taxDetail["percentage"]);
                        tax.Value      = Convert.ToDouble(taxDetail["value"]);
                        record.AddTax(tax);
                    }
                }
                else if (fieldAPIName.Equals("Tax") && token.Value.Type != JTokenType.Null)
                {
                    var taxNames = token.Value;
                    foreach (string data in taxNames)
                    {
                        ZCRMTax tax = ZCRMTax.GetInstance(data);
                        record.AddTax(tax);
                    }
                }
                else if (fieldAPIName.Equals("tags") && token.Value.Type != JTokenType.Null)
                {
                    JArray        jsonArray = (JArray)token.Value;
                    List <string> tags      = new List <string>();
                    foreach (string tag in jsonArray)
                    {
                        tags.Add(tag);
                    }
                    record.TagNames = tags;
                }
                else if (fieldAPIName.Equals("Tag") && token.Value.Type != JTokenType.Null)
                {
                    JArray jsonArray = (JArray)token.Value;
                    foreach (JObject tag in jsonArray)
                    {
                        ZCRMTag tagIns = ZCRMTag.GetInstance(Convert.ToInt64(tag.GetValue("id")));
                        tagIns.Name = tag.GetValue("name").ToString();
                        record.Tags.Add(tagIns);
                    }
                }
                else if (fieldAPIName.StartsWith("$", StringComparison.CurrentCulture))
                {
                    fieldAPIName = fieldAPIName.TrimStart('\\', '$');
                    if (APIConstants.PROPERTIES_AS_FILEDS.Contains(fieldAPIName))
                    {
                        record.SetFieldValue(fieldAPIName, token.Value);
                    }
                    else
                    {
                        record.SetProperty(fieldAPIName, token.Value);
                    }
                }
                else if (token.Value is JObject)
                {
                    JObject    lookupDetails = (JObject)token.Value;
                    ZCRMRecord lookupRecord  = ZCRMRecord.GetInstance(fieldAPIName, Convert.ToInt64(lookupDetails["id"]));
                    lookupRecord.LookupLabel = (string)lookupDetails["name"];
                    record.SetFieldValue(fieldAPIName, lookupRecord);
                }
                else if (token.Value is JArray)
                {
                    JArray        jsonArray = (JArray)token.Value;
                    List <object> values    = new List <object>();

                    foreach (Object obj in jsonArray)
                    {
                        if (obj is JObject)
                        {
                            values.Add((JObject)obj);
                        }
                        else
                        {
                            values.Add(obj);
                        }
                    }
                    record.SetFieldValue(fieldAPIName, values);
                }
                else
                {
                    if (token.Value.Type.ToString().Equals("Date"))
                    {
                        record.SetFieldValue(fieldAPIName, CommonUtil.removeEscaping((string)JsonConvert.SerializeObject(token.Value)));
                    }
                    else
                    {
                        record.SetFieldValue(fieldAPIName, token.Value);
                    }
                }
            }
        }
コード例 #28
0
        /// <summary>Materializes the specified <paramref name="entry"/> as dynamic property.</summary>
        /// <param name="entry">Entry with object to materialize.</param>
        /// <param name="link">Nested resource link as parsed.</param>
        private void MaterializeDynamicProperty(MaterializerEntry entry, ODataNestedResourceInfo link)
        {
            Debug.Assert(entry != null, "entry != null");
            Debug.Assert(entry.ResolvedObject != null, "entry.ResolvedObject != null -- otherwise not resolved/created!");
            Debug.Assert(link != null, "link != null");

            ClientEdmModel model = this.MaterializerContext.Model;

            IDictionary <string, object> containerProperty;

            // Stop if owning type is not an open type
            // Or container property is not found
            // Or key with matching name already exists in the dictionary
            if (!ClientTypeUtil.IsInstanceOfOpenType(entry.ResolvedObject, model) ||
                !ClientTypeUtil.TryGetContainerProperty(entry.ResolvedObject, out containerProperty) ||
                containerProperty.ContainsKey(link.Name))
            {
                return;
            }

            MaterializerNavigationLink linkState = MaterializerNavigationLink.GetLink(link);

            if (linkState == null || (linkState.Entry == null && linkState.Feed == null))
            {
                return;
            }

            // NOTE: ODL (and OData WebApi) support navigational property on complex types
            // That support has not yet been implemented in OData client

            // An entity or entity collection as a dynamic property currently doesn't work as expected
            // due to the absence of a navigational property definition in the metadata
            // to express the relationship between that entity and the parent entity - unless they're the same type!
            // Only materialize a nested resource if its a complex or complex collection

            if (linkState.Feed != null)
            {
                string collectionTypeName     = linkState.Feed.TypeName; // TypeName represents a collection e.g. Collection(NS.Type)
                string collectionItemTypeName = CommonUtil.GetCollectionItemTypeName(collectionTypeName, false);

                // Highly unlikely, but the method return null if the typeName argument does not meet certain expectations
                if (collectionItemTypeName == null)
                {
                    return;
                }

                Type collectionItemType = ResolveClientTypeForDynamicProperty(collectionItemTypeName, entry.ResolvedObject);

                if (collectionItemType != null && ClientTypeUtil.TypeIsComplex(collectionItemType, model))
                {
                    Type  collectionType = typeof(System.Collections.ObjectModel.Collection <>).MakeGenericType(new Type[] { collectionItemType });
                    IList collection     = (IList)Util.ActivatorCreateInstance(collectionType);

                    IEnumerable <ODataResource> feedEntries = MaterializerFeed.GetFeed(linkState.Feed).Entries;
                    foreach (ODataResource feedEntry in feedEntries)
                    {
                        MaterializerEntry linkEntry = MaterializerEntry.GetEntry(feedEntry);
                        this.Materialize(linkEntry, collectionItemType, false /*includeLinks*/);
                        collection.Add(linkEntry.ResolvedObject);
                    }

                    containerProperty.Add(link.Name, collection);
                }
            }
            else
            {
                MaterializerEntry linkEntry = linkState.Entry;
                Type itemType = ResolveClientTypeForDynamicProperty(linkEntry.Entry.TypeName, entry.ResolvedObject);

                if (itemType != null && ClientTypeUtil.TypeIsComplex(itemType, model))
                {
                    this.Materialize(linkEntry, itemType, false /*includeLinks*/);
                    containerProperty.Add(link.Name, linkEntry.ResolvedObject);
                }
            }
        }
コード例 #29
0
 public ActionResult IVS282_InitialSearchResultGrid()
 {
     return(Json(CommonUtil.ConvertToXml <object>(null, @"Inventory\IVS282_SearchResult", CommonUtil.GRID_EMPTY_TYPE.SEARCH)));
 }
コード例 #30
0
        private bool GetRanges(string parameters, IListSheet listSheet)
        {
            string[] allParameters = parameters.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            string  rightStr      = allParameters[0];
            string  topStr        = allParameters[1];
            string  leftStr       = allParameters[2];
            string  bottomStr     = allParameters[3];
            string  blockWidthStr = allParameters[4];
            decimal top           = decimal.Parse(topStr);
            decimal bottom        = decimal.Parse(bottomStr);
            decimal left          = decimal.Parse(leftStr);
            decimal right         = decimal.Parse(rightStr);
            decimal blockWidth    = decimal.Parse(blockWidthStr);
            string  exportDir     = allParameters[5];

            int     vBlockCount = (int)Math.Ceiling((top - bottom) / blockWidth);
            int     hBlockCount = (int)Math.Ceiling((right - left) / blockWidth);
            decimal lastY       = bottom;

            //已经下载下来的列表页html保存到的目录(文件夹)
            string pageSourceDir = this.RunPage.GetDetailSourceFileDir();

            //输出excel表格包含的列
            Dictionary <string, int> resultColumnDic = CommonUtil.InitStringIndexDic(new string[] {
                "detailPageUrl",
                "detailPageName",
                "cookie",
                "grabStatus",
                "giveUpGrab",
                "name",
                "left",
                "right",
                "bottom",
                "top",
                "itemIndex",
                "requestString"
            });

            string resultFilePath = Path.Combine(exportDir, "宜出行获取POI信息.xlsx");

            //输出对象
            ExcelWriter resultEW  = new ExcelWriter(resultFilePath, "List", resultColumnDic);
            int         itemIndex = 0;

            for (int i = 1; i <= vBlockCount; i++)
            {
                decimal nextY = i == vBlockCount ? top : (lastY + blockWidth);
                decimal lastX = left;
                for (int j = 1; j <= hBlockCount; j++)
                {
                    itemIndex++;
                    decimal nextX = j == hBlockCount ? right : (lastX + blockWidth);

                    string code          = lastX.ToString() + "," + nextX.ToString() + "," + lastY.ToString() + "," + nextY.ToString();
                    string requestString = "lat=" + nextX.ToString() + "&lng=" + nextY.ToString() + "&_token=";

                    Dictionary <string, string> f2vsLocation = new Dictionary <string, string>();
                    f2vsLocation.Add("detailPageUrl", "http://c.easygo.qq.com/api/egc/location?" + itemIndex.ToString());
                    f2vsLocation.Add("detailPageName", "location_" + code);
                    f2vsLocation.Add("name", "location_" + code);
                    f2vsLocation.Add("left", lastX.ToString());
                    f2vsLocation.Add("right", nextX.ToString());
                    f2vsLocation.Add("bottom", lastY.ToString());
                    f2vsLocation.Add("top", nextY.ToString());
                    f2vsLocation.Add("itemIndex", itemIndex.ToString());
                    f2vsLocation.Add("requestString", requestString);
                    resultEW.AddRow(f2vsLocation);

                    Dictionary <string, string> f2vsLineData = new Dictionary <string, string>();
                    f2vsLineData.Add("detailPageUrl", "http://c.easygo.qq.com/api/egc/linedata?" + itemIndex.ToString());
                    f2vsLineData.Add("detailPageName", "lineData" + code);
                    f2vsLineData.Add("name", "lineData" + code);
                    f2vsLineData.Add("left", lastX.ToString());
                    f2vsLineData.Add("right", nextX.ToString());
                    f2vsLineData.Add("bottom", lastY.ToString());
                    f2vsLineData.Add("top", nextY.ToString());
                    f2vsLineData.Add("itemIndex", itemIndex.ToString());
                    f2vsLineData.Add("requestString", requestString);
                    resultEW.AddRow(f2vsLineData);
                    lastX = nextX;
                }
                lastY = nextY;
            }

            //保存到硬盘
            resultEW.SaveToDisk();

            return(true);
        }
コード例 #31
0
        public BulkAPIResponse <ZCRMRecord> GetRecords(long?cvId, string sortByField, CommonUtil.SortOrder?sortOrder, int page, int perPage, string modifiedSince, string isConverted, string isApproved, List <string> fields)
        {
            try
            {
                requestMethod = APIConstants.RequestMethod.GET;

                urlPath = module.ApiName;

                if (cvId != null)
                {
                    requestQueryParams.Add("cvid", cvId.ToString());
                }

                if (sortByField != null)
                {
                    requestQueryParams.Add("sort_by", sortByField);
                }

                if (sortOrder != null)
                {
                    requestQueryParams.Add("sort_order", sortOrder.ToString());
                }

                requestQueryParams.Add(APIConstants.PAGE, page.ToString());

                requestQueryParams.Add(APIConstants.PER_PAGE, perPage.ToString());

                if (isApproved != null && isApproved != "")
                {
                    requestQueryParams.Add("approved", isApproved);
                }

                if (isConverted != null && isConverted != "")
                {
                    requestQueryParams.Add("converted", isConverted);
                }

                if (fields != null)
                {
                    requestQueryParams.Add("fields", CommonUtil.CollectionToCommaDelimitedString(fields));
                }

                if (modifiedSince != null && modifiedSince != "")
                {
                    requestHeaders.Add("If-Modified-Since", modifiedSince);
                }

                BulkAPIResponse <ZCRMRecord> response = APIRequest.GetInstance(this).GetBulkAPIResponse <ZCRMRecord>();

                List <ZCRMRecord> records = new List <ZCRMRecord>();

                JObject responseJSON = response.ResponseJSON;

                if (responseJSON.ContainsKey(APIConstants.DATA))
                {
                    JArray recordsArray = (JArray)responseJSON[APIConstants.DATA];

                    foreach (JObject recordDetails in recordsArray)
                    {
                        ZCRMRecord record = ZCRMRecord.GetInstance(module.ApiName, Convert.ToInt64(recordDetails["id"]));

                        EntityAPIHandler.GetInstance(record).SetRecordProperties(recordDetails);

                        records.Add(record);
                    }
                }

                response.BulkData = records;

                return(response);
            }
            catch (Exception e) when(!(e is ZCRMException))
            {
                ZCRMLogger.LogError(e);

                throw new ZCRMException(APIConstants.SDK_ERROR, e);
            }
        }
コード例 #32
0
        private static void CheckFiles()
        {
            var gameFilePaths = Directory.GetFiles(CommonUtil.CombinePaths(Client.KspPath, "GameData"), "*",
                                                   SearchOption.AllDirectories);
            var gameFileRelativePaths =
                gameFilePaths.Select(
                    filePath =>
                    filePath.Substring(filePath.ToLowerInvariant().IndexOf("gamedata", StringComparison.Ordinal) + 9)
                    .Replace('\\', '/')).ToList();

            //Check Required
            foreach (var requiredEntry in ParseRequired)
            {
                if (!requiredEntry.Key.EndsWith("dll"))
                {
                    CheckNonDllFile(gameFileRelativePaths, requiredEntry, true);
                }
                else
                {
                    CheckDllFile(requiredEntry, true);
                }
            }

            //Check Optional
            foreach (var optionalEntry in ParseOptional)
            {
                if (!optionalEntry.Key.EndsWith("dll"))
                {
                    CheckNonDllFile(gameFileRelativePaths, optionalEntry, false);
                }
                else
                {
                    CheckDllFile(optionalEntry, false);
                }
            }

            if (WhiteList.Any() && !BlackList.Any()) //Check Resource whitelist
            {
                var autoAllowed = new List <string>
                {
                    "lunamultiplayer/plugins/lunaclient.dll",
                    "lunamultiplayer/plugins/lunacommon.dll",
                    "lunamultiplayer/plugins/fastmember.dll",
                    "lunamultiplayer/plugins/lidgren.network.dll",
                    "lunamultiplayer/plugins/mono.data.tds.dll",
                    "lunamultiplayer/plugins/system.data.dll",
                    "lunamultiplayer/plugins/system.threading.dll",
                    "lunamultiplayer/plugins/system.transactions.dll"
                };

                //Allow LMP files, Ignore squad plugins, Check required (Required implies whitelist), Check optional (Optional implies whitelist)
                //Check whitelist

                foreach (var dllResource in
                         SystemsContainer.Get <ModSystem>().DllList.Where(
                             dllResource =>
                             !autoAllowed.Contains(dllResource.Key) && !dllResource.Key.StartsWith("squad/plugins") &&
                             !ParseRequired.ContainsKey(dllResource.Key) && !ParseOptional.ContainsKey(dllResource.Key) &&
                             !WhiteList.ContainsKey(dllResource.Key)))
                {
                    ModCheckOk = false;
                    LunaLog.Log($"[LMP]: Non-whitelisted resource {dllResource.Key} exists on client!");
                    StringBuilder.AppendLine($"Non-whitelisted resource {dllResource.Key} exists on client!");
                }
            }

            if (!WhiteList.Any() && BlackList.Any()) //Check Resource blacklist
            {
                foreach (var blacklistEntry in
                         BlackList.Keys.Where(blacklistEntry => SystemsContainer.Get <ModSystem>().DllList.ContainsKey(blacklistEntry)))
                {
                    ModCheckOk = false;
                    LunaLog.Log($"[LMP]: Banned resource {blacklistEntry} exists on client!");
                    StringBuilder.AppendLine($"Banned resource {blacklistEntry} exists on client!");
                }
            }
        }
 public void ExceptionHandlingSettingsNodeHasReadonlyName()
 {
     Assert.IsTrue(CommonUtil.IsPropertyReadOnly(typeof(ExceptionHandlingSettingsNode), "Name"));
 }
コード例 #34
0
        public ActionResult ICS110_ConfirmWHT()
        {
            ObjectResultData res = new ObjectResultData();

            try
            {
                ICS110_ScreenParameter sParam = GetScreenObject <ICS110_ScreenParameter>();
                if (sParam.RegisterParam == null)
                {
                    throw new ApplicationException("RegisterParam is null");
                }

                var param = CommonUtil.CloneObject <doPaymentForWHTRegister, doPaymentForWHTRegister>(sParam.RegisterParam);
                var hand  = ServiceContainer.GetService <IIncomeHandler>() as IIncomeHandler;

                tbt_IncomeWHT wht = null;
                using (TransactionScope scope = new TransactionScope())
                {
                    if (param.WHTNo == null)
                    {
                        wht = new tbt_IncomeWHT()
                        {
                            WHTNo              = hand.GenerateWHTNo(param.WHTMatchingDate),
                            Amount             = param.AmountCurrencyType == CurrencyUtil.C_CURRENCY_LOCAL ? param.Amount : 0,
                            AmountUsd          = param.AmountCurrencyType == CurrencyUtil.C_CURRENCY_US ? param.Amount.Value : 0,
                            AmountCurrencyType = param.AmountCurrencyType,
                            DocumentDate       = param.DocumentDate ?? DateTime.MinValue,
                            WHTMatchingDate    = param.WHTMatchingDate ?? DateTime.MinValue,
                            CreateBy           = CommonUtil.dsTransData.dtUserData.EmpNo,
                            CreateDate         = CommonUtil.dsTransData.dtOperationData.ProcessDateTime
                        };
                        hand.InsertTbt_IncomeWHT(new List <tbt_IncomeWHT>()
                        {
                            wht
                        });
                    }
                    else
                    {
                        var tmpWht = hand.GetTbt_IncomeWHT(param.WHTNo);
                        if (tmpWht == null || tmpWht.Count <= 0)
                        {
                            throw new ApplicationException("Missing data tbt_IncomeWHT of WHTNo. " + param.WHTNo);
                        }
                        wht                    = tmpWht.FirstOrDefault();
                        wht.Amount             = param.AmountCurrencyType == CurrencyUtil.C_CURRENCY_LOCAL ? param.Amount : 0;
                        wht.AmountUsd          = param.AmountCurrencyType == CurrencyUtil.C_CURRENCY_US ? param.Amount.Value : 0;
                        wht.AmountCurrencyType = param.AmountCurrencyType;
                        wht.DocumentDate       = param.DocumentDate ?? DateTime.MinValue;
                        //WHTMatchingDate is not allowed to changed after created.
                        //wht.WHTMatchingDate = param.WHTMatchingDate ?? DateTime.MinValue;
                        wht.UpdateBy   = CommonUtil.dsTransData.dtUserData.EmpNo;
                        wht.UpdateDate = CommonUtil.dsTransData.dtOperationData.ProcessDateTime;
                        hand.UpdateTbt_IncomeWHT(new List <tbt_IncomeWHT>()
                        {
                            wht
                        });
                    }

                    hand.UpdateWHTNoToPayment(
                        wht.WHTNo,
                        param.PaymentTransNoList,
                        CommonUtil.dsTransData.dtUserData.EmpNo,
                        CommonUtil.dsTransData.dtOperationData.ProcessDateTime
                        );

                    scope.Complete();
                }

                res.ResultData = new
                {
                    IsSuccess = true,
                    WHTNo     = wht.WHTNo
                };
            }
            catch (Exception ex)
            {
                res.AddErrorMessage(ex);
            }

            return(Json(res));
        }
コード例 #35
0
    public static IObservable <T> PostWithSign <T>(string url, Dictionary <string, object> param,
                                                   string fileName = null, string filePath = null, bool showToast = true)
    {
        StringBuilder strParam  = new StringBuilder();
        var           formParam = new WWWForm();

        if (token.IsNullOrEmpty())
        {
            token = PlayerPrefsUtil.GetToken();
        }

        if (!token.IsNullOrEmpty())
        {
            param.Add("token", token);
        }

        if (param.Count > 0)
        {
            param.ForEach(pair =>
            {
                strParam.Append(pair.Key);
                strParam.Append(":");
                strParam.Append(pair.Value.ToString());
                strParam.Append("&");
                formParam.AddField(pair.Key, pair.Value.ToString());
            });
            string sign = SignUtil.getSign(param);
            formParam.AddField("sign", sign);
            formParam.AddField("appid", AppConst.APPID);
            strParam.Append("sign");
            strParam.Append(":");
            strParam.Append(sign);
            strParam.Append("&");
            strParam.Append("appid");
            strParam.Append(":");
            strParam.Append(AppConst.APPID);
        }

        if (filePath.IsNotNullAndEmpty())
        {
            formParam.AddBinaryData("file", File.ReadAllBytes(filePath), fileName);
            strParam.Append("&");
            strParam.Append("file");
            strParam.Append(":");
            strParam.Append(File.ReadAllBytes(filePath));
        }

        return(ObservableWWW.Post(url, formParam).Select <string, T>(s =>
        {
            Log.I("url==" + url);
            Log.I("formParam==" + strParam);
            Log.I("返回信息是" + s);
            if (s.IsNullOrEmpty())
            {
                throw new HttpException("104", "网络连接失败", 104);
            }

            BaseEntity <T> deserializeObject = JsonConvert.DeserializeObject <BaseEntity <T> >(s);
            if (deserializeObject.status != 1)
            {
                CommonUtil.error(deserializeObject.errCode, deserializeObject.message, deserializeObject.status);
                throw new HttpException(deserializeObject.errCode, deserializeObject.message, deserializeObject.status);
            }

            return deserializeObject.data;
        }).DoOnError(e =>
        {
            LoadingManager.GetInstance().DismissLoading();
            if (showToast)
            {
                if (e is HttpException)
                {
                    CommonUtil.toast(((HttpException)e).ErrMessage);
                }
                else if (e is WWWErrorException)
                {
                    ToastManager.GetInstance().CreatToast("网络连接失败,请检查网络连接");
                }
                else
                {
                    ToastManager.GetInstance().CreatToast(e.Message);
                }
            }
        }));
    }
コード例 #36
0
 /// <summary>
 /// Get data for initialize match payment detail grid.
 /// </summary>
 /// <returns>Return ActionResult of JSON data data for initialize match payment detail grid.</returns>
 public ActionResult ICS110_InitialMatchWHTDetail()
 {
     return(Json(CommonUtil.ConvertToXml <object>(null, "Income\\ICS110_MatchWHTDetail", CommonUtil.GRID_EMPTY_TYPE.INSERT)));
 }