コード例 #1
0
ファイル: ItemDb.cs プロジェクト: mexaniksay/GamePro02
		public async void AddGameItemToSQL()
		{
		
			string url = "https://api.steampowered.com/IEconDOTA2_570/GetGameItems/v1/?key=6A9C411A88D047DA4C9E843EDF0B02F5&format=json&" +
				"language=en_us";
			var ApiReq = new APIRequest ();
			var comm = new DBComm ();
			var temp = (JToken)await ApiReq.FetchJsonAsync (url);
			var jItems = (JToken)temp.SelectToken ("result.items");

				foreach (JToken jItem in jItems) {
					var item = new Item ();
					string cdnUrl = "http://cdn.dota2.com/apps/dota2/images/items/";
					item.ItemId = (int)jItem.SelectToken ("id");
					item.Name = (string)jItem.SelectToken ("name");
					item.LocalName = (string)jItem.SelectToken ("localized_name");
					string itemName = item.Name;
					itemName=itemName.Substring(itemName.IndexOf("_")+1);
					item.ImageUrl = cdnUrl+itemName+"_lg.png";
					try {
						comm.Connect.Insert(item);
						Console.Out.WriteLine (item.LocalName);
					} catch (SQLiteException e) {
						Console.Out.WriteLine (e.Message);
					}
			}
			comm.Connect.Dispose ();
		}
コード例 #2
0
ファイル: APIHelper.cs プロジェクト: minhdu/mmo-client
 static public void CallAPI(APIRequest request, Action<APIResponse> onResponse)
 {
     GameObject apiCarrier = new GameObject();
     apiCarrier.name = request.GetType().ToString();
     APIHelper api = apiCarrier.AddComponent<APIHelper>();
     api.Request(request, response => { onResponse(response); });
 }
コード例 #3
0
ファイル: APIHelper.cs プロジェクト: minhdu/mmo-client
 public void Request (APIRequest request, Action<APIResponse> onResponse)
 {
     StartCoroutine(WWWRequest(request.RequestURL, request.SubmitData, response =>
     {
         onResponse(response);
     }));
 }
コード例 #4
0
		public async Task OnRefresh()
		{
			try {
				if (!SettingsApp.refreshFlag) 
				{
					SettingsApp.refreshFlag = true;
					cts = new CancellationTokenSource ();
					cts.Token.ThrowIfCancellationRequested ();
					APIRequest ApiReq = new APIRequest ();
					var jListMatch = await ApiReq.GetJsonAsync (SettingsApp.ServerAPIAddress+SettingsApp.GameName+"/GetUpcomingMatches");
					var listMatch = JsonConvert.DeserializeObject<List<SimpleMatchInfo>> (jListMatch.ToString());
					SimpleMatchInfo_2 s2 = new SimpleMatchInfo_2 ();
					listTeams = await s2.ConvertToSimple2 (listMatch,cts.Token);
					if(this.Activity!=null)
						this.ListAdapter = new SimpleMatchAdapter(this.Activity,listTeams,3,cts.Token);
					cts = null;
					SettingsApp.refreshFlag = false;
					Toast.MakeText (context, context.Resources.GetString(Resource.String.updated), ToastLength.Long).Show ();
				}
			}
			catch {
				cts = null;
				SettingsApp.refreshFlag = false;
				Toast.MakeText (context, context.Resources.GetString(Resource.String.error), ToastLength.Long).Show ();
			}
		}
コード例 #5
0
		public override async void OnListItemClick(ListView l, View v, int index, long id)
		{
			APIRequest apiReq = new APIRequest ();
			if (cts != null) {
				cts.Cancel ();
			}
			Intent intent = new Intent ();

			switch (SettingsApp.GameName) {
			case "DOTA2":
				intent = new Intent (this.Activity, typeof(DotaMatchActivity));
				break;
			case "Hearthstone":
				intent = new Intent (this.Activity, typeof(HSMatchActivity));
				break;
			case "CSGO":
				intent = new Intent (this.Activity, typeof(CSMatchActivity));
				break;
			default:
				return;
				break;
			}
			int match_id = listTeams [index].MatchId;

			intent.PutExtra ("iconIdGame", "0");
			//intent.PutExtra ("matchDetail", jMatchResponce.ToString());
			intent.PutExtra ("match_id", match_id.ToString());
			intent.PutExtra ("title", Resources.GetString(Resource.String.tabRecent));
			intent.PutExtra ("liveFlag", "1");
			//intent.PutExtra ("gameInfo", jMatchInfo);
			StartActivity (intent);

		}
コード例 #6
0
ファイル: HeroDb.cs プロジェクト: mexaniksay/GamePro02
		public async void AddGameHeroToSQl ()
		{

			string url = "https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v1/?key=6A9C411A88D047DA4C9E843EDF0B02F5&format=json&" +
				"language=en_us&itemizedonly=0";
			var ApiReq = new APIRequest ();
			var comm = new DBComm ();
			var temp = (JToken)await ApiReq.FetchJsonAsync (url);
			var jHeroes = (JToken)temp.SelectToken ("result.heroes");
			foreach (JToken jHero in jHeroes) {
				var hero = new Hero ();
				string cdnUrl = "http://cdn.dota2.com/apps/dota2/images/heroes/";
				hero.HeroId =(int) jHero.SelectToken ("id");
				hero.Name = (string)jHero.SelectToken ("name");
				hero.LocalName = (string)jHero.SelectToken ("localized_name");
				string heroName = hero.Name;
				heroName = heroName.Substring (14);
				hero.SHorImgUrl = cdnUrl+heroName+"_sb.png";
				hero.LHorImgUrl = cdnUrl+heroName+"_lg.png";
				hero.FHorImgUrl = cdnUrl+heroName+"_full.png";
				hero.FVerImgUrl = cdnUrl+heroName+"_vert.jpg";
				try {
						comm.Connect.Insert(hero);
						Console.Out.WriteLine (hero.LocalName);

				} catch (SQLiteException e) {
					Console.Out.WriteLine (e.Message);
				}
			}

		}
コード例 #7
0
 		protected  override async void OnCreate (Bundle bundle)
		{
			try{
				base.OnCreate (bundle);
				SetContentView (Resource.Layout.LayoutMatchInfo);

				title=Intent.GetStringExtra("title");
				ActionBarTitle.SetTitle (this,Resource.Layout.ActionBarLayout,title,Resources.GetString (Resource.String.nameDota2));
				buttonRefresh=FindViewById<Button>(Resource.Id.buttonRefreshActionBar);
				buttonRefresh.Click+=ButtonRefreshClick;
				buttonRefresh.Visibility=ViewStates.Invisible;
				var buttonBack=FindViewById<Button>(Resource.Id.buttonBackActionBar);
				buttonBack.Click+=ButtonBackClick;
				//var rl=FindViewById<RelativeLayout>(Resource.Id.rlayout_match_info);
				//var buttonPickBan = rl.FindViewById<Button> (Resource.Id.button_picks_bans);
				//var rlTowersViews=FindViewById<RelativeLayout>(Resource.Id.towersState);
				Button buttonPickBan =FindViewById<Button> (Resource.Id.buttonBattle);
				buttonPickBan.Click += buttonPickBansClick;
				Button buttonGameStats = FindViewById<Button> (Resource.Id.buttonGameStats);
				buttonGameStats.Click += buttomGameStatsClick;
				pb=FindViewById<ProgressBar> (Resource.Id.progressBar3);
				pb.Visibility= ViewStates.Visible;
				APIRequest apiReq = new APIRequest ();
				int match_id=Convert.ToInt32( Intent.GetStringExtra("match_id"));
				var url =SettingsApp.ServerAPIAddress+SettingsApp.GameName+"/GetDetailInfo?match_id=" + match_id;
				var jMatchResponce = await apiReq.GetJsonAsync (url);
				gameInfo=jMatchResponce.ToString();
				var jDetailMatchInfo= JsonConvert.DeserializeObject<JDetailMatchInfo>(gameInfo);
				var jMatchDetails=JToken.Parse(jDetailMatchInfo.JMatchDetails);
				matchDetail=JsonConvert.DeserializeObject<MatchInfo>(jMatchDetails.ToString());
				dotaMatchInfo=JsonConvert.DeserializeObject<List<DotaMatchInfo>>(jMatchDetails.SelectToken("DetailsMatch").ToString());
				List<DetailInfo> listDetail=new List<DetailInfo>();
				listDetail.AddRange(dotaMatchInfo);
				matchDetail.DetailsMatch=listDetail;
				liveFlag=Intent.GetStringExtra("liveFlag");
				cts= new CancellationTokenSource();
				cts.Token.ThrowIfCancellationRequested ();
				dotaMatchInfo_2=new DotaMatchInfo_2();
				refreshFlag = true;

				dotaMatchInfo_2 = await dotaMatchInfo_2.ParseMatchTitle (matchDetail);
				//Title match
				await RefreshData(cts.Token);

			}catch(Exception e) {
				Console.WriteLine (e.Data);
				Console.WriteLine (e.Message);
			}
			cts = null;
			pb.Visibility= ViewStates.Gone;
			buttonRefresh.Visibility = ViewStates.Visible;
		}
コード例 #8
0
ファイル: LeagueDb.cs プロジェクト: mexaniksay/GamePro02
		public async Task<League> AddLeague(int id,string gameName)
		{
			string url = SettingsDB.ServerAPIAddress+gameName+"/GetLeague?league_id="+id;
			var ApiReq = new APIRequest ();
			var comm = new DBComm ();
			JToken temp = await ApiReq.GetJsonAsync (url);
			var league = JsonConvert.DeserializeObject<League> (temp.ToString ());
			if (temp.ToString () != "") {
				comm.Connect.Insert (league);
				comm.Connect.Dispose ();
			}
			return league;
		}
コード例 #9
0
ファイル: CSMapDb.cs プロジェクト: mexaniksay/GamePro02
		public async Task<CSMap> AddMap(int id)
		{
			string url = SettingsDB.ServerAPIAddress+"CSGO/GetMap?map_id="+id;
			var ApiReq = new APIRequest ();
			DBComm command = new DBComm ("CSGO");
			JToken temp = await ApiReq.GetJsonAsync (url);
			var map = JsonConvert.DeserializeObject<CSMap> (temp.ToString ());
			if (temp.ToString () != "") {
				command.Connect.Insert (map);
				command.Connect.Dispose ();
			}
			return map;
		}
コード例 #10
0
        /// <summary>
        /// deployVirtualMachine API call
        /// </summary>
        /// <param name="session">Client connection to CloudStack API</param>
        /// <param name="templateid">Cloud resource identifier for vm template</param>
        /// <param name="serviceofferingid">CPU / memory architecture for VM.</param>
        /// <param name="securityGroups">Optional list of security groups to apply to the VM, used in basic networking scenarios.</param>
        /// <param name="zoneid">Zone on which to place the VM</param>
        /// <param name="displayname">Optional display name to provide to the new instance.</param>
        /// <param name="network">Optional identifier for network to put VM on.</param>
        /// <param name="userdata">Optional data to pass to newly created VM</param>
        /// <param name="createStopped">Created VM should be initiallty stopped</param>
        /// <returns>Cloud resource identifier for the new VM.</returns>
        public static string DeployVirtualMachine(Client session, string templateid, string serviceofferingid, IList<string> securityGroups, string zoneid, string displayname, string network, string userdata, bool createStopped)
        {
            APIRequest req = new APIRequest("deployVirtualMachine");
            req.Parameters["serviceOfferingid"] = serviceofferingid;
            req.Parameters["templateid"] = templateid;
            req.Parameters["zoneid"] = zoneid;

            if (createStopped)
            {
                req.Parameters.Add("startvm", "false");
            }

            if (displayname != null)
            {
                req.Parameters.Add("displayname", displayname);
            }

            if (securityGroups != null && securityGroups.Count > 0)
            {
                StringBuilder securityGroupList = new StringBuilder();
                foreach (string grp in securityGroups)
                {
                    if (!string.IsNullOrEmpty(grp))
                    {
                        securityGroupList.Append(grp + ",");
                    }
                }
                if (securityGroupList.Length > 0)
                {
                    if (securityGroupList[securityGroupList.Length - 1] == ',')
                    {
                        securityGroupList.Remove(securityGroupList.Length - 1, 1);
                    }
                    req.Parameters.Add("securitygroupids", securityGroupList.ToString());
                }
            }

            if (network != null)
            {
                req.Parameters.Add("networkids", network);
            }

            if (userdata != null)
            {
                string base64String = EncodeUserData(userdata);
                req.Parameters.Add("userdata", base64String);
            }
            return AsyncSupport.WaitForNewResourceIdFromAsyncCmd(session, req);
        }
コード例 #11
0
        public static async Task<String> PostAsync(HttpClient client, String apiUrl, APIRequest requestBody)
        {
            var responseBody = String.Empty;

            var jsonRequest = JsonConvert.SerializeObject(requestBody);

            var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
            using (HttpResponseMessage response = await client.PostAsync(apiUrl, content))
            {
                response.EnsureSuccessStatusCode();
                responseBody = await response.Content.ReadAsStringAsync();
            }

            return responseBody;
        }
コード例 #12
0
		protected async override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
			SetContentView (Resource.Layout.CSMatchInfoLayout);
			title=Intent.GetStringExtra("title");
			pb = FindViewById<ProgressBar> (Resource.Id.progressBar3);
			ActionBarTitle.SetTitle (this,Resource.Layout.ActionBarLayout,title,Resources.GetString(Resource.String.nameCSGO));
			var buttonBack=FindViewById<Button>(Resource.Id.buttonBackActionBar);
			buttonBack.Click+=ButtonBackClick;
			buttonRefresh=FindViewById<Button>(Resource.Id.buttonRefreshActionBar);
			buttonRefresh.Click+=ButtonRefreshClick;
			buttonRefresh.Visibility=ViewStates.Invisible;
			pb=FindViewById<ProgressBar> (Resource.Id.progressBar3);
			pb.Visibility= ViewStates.Visible;
			APIRequest apiReq = new APIRequest ();
			int match_id=Convert.ToInt32( Intent.GetStringExtra("match_id"));
			var url =SettingsApp.ServerAPIAddress+SettingsApp.GameName+"/GetDetailInfo?match_id=" + match_id;
			var jMatchResponce = await apiReq.GetJsonAsync (url);

			gameInfo=jMatchResponce.ToString ();
			liveFlag=Intent.GetStringExtra("liveFlag");
			var jDetailMatchInfo= JsonConvert.DeserializeObject<JDetailMatchInfo>(gameInfo);
			var jMatchDetails=JToken.Parse(jDetailMatchInfo.JMatchDetails);
			matchInfo=JsonConvert.DeserializeObject<MatchInfo>(jMatchDetails.ToString());
			csMatchInfo=JsonConvert.DeserializeObject<List<CSMatchInfo>>(jMatchDetails.SelectToken("DetailsMatch").ToString());
			List<DetailInfo> listDetail=new List<DetailInfo>();
			listDetail.AddRange(csMatchInfo);
			matchInfo.DetailsMatch=listDetail;

			cts = new CancellationTokenSource ();
			matchInfo_2 = new CSMatchInfo_2 ();
			listMatchInfo = await matchInfo_2.ParseMatchTitle (matchInfo);
			if (listMatchInfo.Count > 0) {
				matchInfo_2 = listMatchInfo [0];
			}
			FillTitleMatch ();

			CreateFragment (Resource.Id.cs_llayout_match_draft, new FragmentCSMatchDraft (listMatchInfo));
			cts = null;
			pb.Visibility= ViewStates.Gone;
			buttonRefresh.Visibility = ViewStates.Visible;
			// Create your application here
		}
コード例 #13
0
ファイル: TeamDb.cs プロジェクト: mexaniksay/GamePro02
		public async Task<Player> GetPlayerAPI(long steamId)
		{
			long id64 = ConvertSteamId32To64 (steamId);
			string url = 
				"https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key=6A9C411A88D047DA4C9E843EDF0B02F5&format=json&" +
				"language=en_us&"+"steamids="+id64;
			APIRequest ApiReq = new APIRequest ();
			JToken temp = await ApiReq.FetchJsonAsync (url);
			JToken playerJS = (JToken)temp.SelectToken("response.players[0]");
			var newPlayer = new Player ();
			newPlayer.SteamId32 = steamId;
			newPlayer.SteamId64 = id64;
			newPlayer.Name = (string)playerJS.SelectToken("personaname");
			newPlayer.ProfileUrl = (string)playerJS.SelectToken("profileurl");
			newPlayer.Avatar = (string) playerJS.SelectToken("avatarmedium");
			//newPlayer.TeamID = teamID;

			System.Console.Out.WriteLine (newPlayer.SteamId64);
			return newPlayer;
		}
コード例 #14
0
ファイル: TeamDb.cs プロジェクト: mexaniksay/GamePro02
		public async Task<byte[]> GetTeamLogoAPI (string LogoUGCId)
		{

			byte[] byteArray = null;
			var ApiReq = new APIRequest ();
			string url = 
				"https://api.steampowered.com/ISteamRemoteStorage/GetUGCFileDetails/v1/?key=6A9C411A88D047DA4C9E843EDF0B02F5&format=json&" +
				"language=en_us&"+
				"ugcid="+LogoUGCId+"&appid=570";
			try 
			{
				JToken temp = await ApiReq.FetchJsonAsync (url);
				string logoUrl = (string)temp.SelectToken ("data.url");
				byte[] imgByte = await ApiReq.FetchByteArrAsync (logoUrl);
				Bitmap b = BitmapFactory.DecodeByteArray(imgByte, 0, imgByte.Length);
				Bitmap b1=Bitmap.CreateScaledBitmap(b, 150, 90, false);
				MemoryStream  stream = new MemoryStream ();
				b1.Compress(Bitmap.CompressFormat.Png, 0, stream);
				byteArray = stream.ToArray();
			}
			catch {
			}
			return byteArray;
		}
コード例 #15
0
 /// <summary>
 /// 验证公共参数
 /// </summary>
 /// <param name="pRequest"></param>
 protected virtual void ValidateCommonParameters(APIRequest <TRequestPara> pRequest)
 {
 }
コード例 #16
0
ファイル: APIAccess.cs プロジェクト: yheno/osu
        /// <summary>
        /// Handle a single API request.
        /// </summary>
        /// <param name="req">The request.</param>
        /// <returns>true if we should remove this request from the queue.</returns>
        private bool handleRequest(APIRequest req)
        {
            try
            {
                Logger.Log($@"Performing request {req}", LoggingTarget.Network);
                req.Perform(this);

                State = APIState.Online;
                failureCount = 0;
                return true;
            }
            catch (WebException we)
            {
                HttpStatusCode statusCode = (we.Response as HttpWebResponse)?.StatusCode ?? HttpStatusCode.RequestTimeout;

                switch (statusCode)
                {
                    case HttpStatusCode.Unauthorized:
                        State = APIState.Offline;
                        return true;
                    case HttpStatusCode.RequestTimeout:
                        failureCount++;
                        log.Add($@"API failure count is now {failureCount}");

                        if (failureCount < 3)
                            //we might try again at an api level.
                            return false;

                        State = APIState.Failing;
                        return true;
                }

                req.Fail(we);
                return true;
            }
            catch (Exception e)
            {
                if (e is TimeoutException)
                    log.Add(@"API level timeout exception was hit");

                req.Fail(e);
                return true;
            }
        }
コード例 #17
0
        protected override UnitMonthReportRD ProcessRequest(APIRequest <UnitMonthReportRP> pRequest)
        {
            //
            var rd = new UnitMonthReportRD();
            var rp = pRequest.Parameters;

            //
            var aggUnitMonthlyBLL            = new Agg_UnitMonthlyBLL(CurrentUserInfo);
            var rUnitProductMonthSalesTopBLL = new R_UnitProductMonthSalesTopBLL(CurrentUserInfo);
            var aggUnitMonthlyEmplBLL        = new Agg_UnitMonthly_EmplBLL(CurrentUserInfo);
            var aggUnitNowEmplBLL            = new Agg_UnitNow_EmplBLL(CurrentUserInfo);
            var t_UserBLL = new T_UserBLL(CurrentUserInfo);

            //
            var aggUnitMonthlyEntity              = default(Agg_UnitMonthlyEntity);              // 本月
            var lastMonthAggUnitMonthlyEntity     = default(Agg_UnitMonthlyEntity);              //  上月
            var lastYearAggUnitMonthlyEntity      = default(Agg_UnitMonthlyEntity);              //  去年同月
            var rUnitProductMonthSalesTopEntities = default(R_UnitProductMonthSalesTopEntity[]); //  销量榜
            var aggUnitMonthlyEmplEntities        = default(Agg_UnitMonthly_EmplEntity[]);       // 业绩榜
            //var setoffAggUnitMonthlyEmplEntities = default(Agg_UnitMonthly_EmplEntity[]);  // 集客榜
            var aggUnitNowEmplEntities = default(Agg_UnitNow_EmplEntity[]);                      //  员工总数据
            var t_UserEntities         = default(T_UserEntity[]);                                //门店员工

            //
            var tasks = new List <Task>();
            var date  = Convert.ToDateTime(rp.Date);

            tasks.Add(Task.Factory.StartNew(() =>
            {
                aggUnitMonthlyEntity = aggUnitMonthlyBLL.QueryByEntity(new Agg_UnitMonthlyEntity
                {
                    CustomerId = rp.CustomerID,
                    UnitId     = rp.UnitID,
                    DateCode   = Convert.ToDateTime(date.Year + "-" + date.Month + "-01")
                }, null).FirstOrDefault();
            }));
            tasks.Add(Task.Factory.StartNew(() =>
            {
                var dateNew = date.AddMonths(-1);
                lastMonthAggUnitMonthlyEntity = aggUnitMonthlyBLL.QueryByEntity(new Agg_UnitMonthlyEntity
                {
                    CustomerId = rp.CustomerID,
                    UnitId     = rp.UnitID,
                    DateCode   = Convert.ToDateTime(dateNew.Year + "-" + dateNew.Month + "-01")
                }, null).FirstOrDefault();
            }));
            tasks.Add(Task.Factory.StartNew(() =>
            {
                var dateNew = date.AddYears(-1);
                lastYearAggUnitMonthlyEntity = aggUnitMonthlyBLL.QueryByEntity(new Agg_UnitMonthlyEntity
                {
                    CustomerId = rp.CustomerID,
                    UnitId     = rp.UnitID,
                    DateCode   = Convert.ToDateTime(dateNew.Year + "-" + dateNew.Month + "-01")
                }, null).FirstOrDefault();
            }));
            tasks.Add(Task.Factory.StartNew(() =>
            {
                rUnitProductMonthSalesTopEntities = rUnitProductMonthSalesTopBLL.PagedQueryByEntity(new R_UnitProductMonthSalesTopEntity
                {
                    CustomerId = rp.CustomerID,
                    UnitId     = rp.UnitID,
                    DateCode   = Convert.ToDateTime(date.Year + "-" + date.Month + "-01")
                }, new OrderBy[]
                {
                    new OrderBy
                    {
                        FieldName = "SalesQty",
                        Direction = OrderByDirections.Desc
                    }
                }, 10, 1).Entities;
            }));
            tasks.Add(Task.Factory.StartNew(() =>
            {
                aggUnitMonthlyEmplEntities = aggUnitMonthlyEmplBLL.QueryByEntity(new Agg_UnitMonthly_EmplEntity
                {
                    CustomerId = rp.CustomerID,
                    UnitId     = rp.UnitID,
                    DateCode   = Convert.ToDateTime(date.Year + "-" + date.Month + "-01")
                }, null);
            }));
            //tasks.Add(Task.Factory.StartNew(() =>
            //{
            //    setoffAggUnitMonthlyEmplEntities = aggUnitMonthlyEmplBLL.PagedQueryByEntity(new Agg_UnitMonthly_EmplEntity
            //    {
            //        CustomerId = rp.CustomerID,
            //        UnitId = rp.UnitID,
            //        DateCode = Convert.ToDateTime(date.Year + "-" + date.Month + "-01")
            //    }, new OrderBy[]
            //    {
            //        new OrderBy
            //        {
            //            FieldName="setoffCount",
            //            Direction= OrderByDirections.Desc
            //        },
            //        new OrderBy
            //        {
            //            FieldName="EmplName",
            //            Direction=OrderByDirections.Asc
            //        }

            //    }, 10, 1).Entities;
            //}));
            tasks.Add(Task.Factory.StartNew(() =>
            {
                aggUnitNowEmplEntities = aggUnitNowEmplBLL.QueryByEntity(new Agg_UnitNow_EmplEntity
                {
                    CustomerId = rp.CustomerID,
                    UnitId     = rp.UnitID,
                    DateCode   = Convert.ToDateTime(rp.Date)
                }, null);
            }));
            tasks.Add(Task.Factory.StartNew(() =>
            {
                t_UserEntities = t_UserBLL.GetEntitiesByCustomerIdUnitId(rp.CustomerID, rp.UnitID);
            }));
            Task.WaitAll(tasks.ToArray());

            // 本月
            if (aggUnitMonthlyEntity != null)
            {
                rd.UnitCurrentMonthSalesAmount     = aggUnitMonthlyEntity.SalesAmount;
                rd.UnitCurrentMonthNewVipCount     = aggUnitMonthlyEntity.NewVipCount;
                rd.UnitCurrentMonthOldVipBackCount = aggUnitMonthlyEntity.OldVipBackCount;
                rd.UnitCurrentMonthUseCouponCount  = aggUnitMonthlyEntity.UseCouponCount;
            }

            // 上月
            if (lastMonthAggUnitMonthlyEntity != null)
            {
                rd.UnitLastMonthSalesAmount     = lastMonthAggUnitMonthlyEntity.SalesAmount;
                rd.UnitLastMonthNewVipCount     = lastMonthAggUnitMonthlyEntity.NewVipCount;
                rd.UnitLastMonthOldVipBackCount = lastMonthAggUnitMonthlyEntity.OldVipBackCount;
                rd.UnitLastMonthUseCouponCount  = lastMonthAggUnitMonthlyEntity.UseCouponCount;
            }

            // 环比
            rd.UnitCurrentMonthSalesAmountMoM     = ReportCommonBLL.Instance.CalcuDoD(lastMonthAggUnitMonthlyEntity == null ? null : lastMonthAggUnitMonthlyEntity.SalesAmount, aggUnitMonthlyEntity == null ? null : aggUnitMonthlyEntity.SalesAmount);
            rd.UnitCurrentMonthNewVipCountMoM     = ReportCommonBLL.Instance.CalcuDoD(lastMonthAggUnitMonthlyEntity == null ? null : lastMonthAggUnitMonthlyEntity.NewVipCount, aggUnitMonthlyEntity == null ? null : aggUnitMonthlyEntity.NewVipCount);
            rd.UnitCurrentMonthOldVipBackCountMoM = ReportCommonBLL.Instance.CalcuDoD(lastMonthAggUnitMonthlyEntity == null ? null : lastMonthAggUnitMonthlyEntity.OldVipBackCount, aggUnitMonthlyEntity == null ? null : aggUnitMonthlyEntity.OldVipBackCount);
            rd.UnitCurrentMonthUseCouponCountMoM  = ReportCommonBLL.Instance.CalcuDoD(lastMonthAggUnitMonthlyEntity == null ? null : lastMonthAggUnitMonthlyEntity.UseCouponCount, aggUnitMonthlyEntity == null ? null : aggUnitMonthlyEntity.UseCouponCount);

            // 同比
            rd.UnitCurrentMonthSalesAmountYoY     = ReportCommonBLL.Instance.CalcuDoD(lastYearAggUnitMonthlyEntity == null ? null : lastYearAggUnitMonthlyEntity.SalesAmount, aggUnitMonthlyEntity == null ? null : aggUnitMonthlyEntity.SalesAmount);
            rd.UnitCurrentMonthNewVipCountYoY     = ReportCommonBLL.Instance.CalcuDoD(lastYearAggUnitMonthlyEntity == null ? null : lastYearAggUnitMonthlyEntity.NewVipCount, aggUnitMonthlyEntity == null ? null : aggUnitMonthlyEntity.NewVipCount);
            rd.UnitCurrentMonthOldVipBackCountYoY = ReportCommonBLL.Instance.CalcuDoD(lastYearAggUnitMonthlyEntity == null ? null : lastYearAggUnitMonthlyEntity.OldVipBackCount, aggUnitMonthlyEntity == null ? null : aggUnitMonthlyEntity.OldVipBackCount);
            rd.UnitCurrentMonthUseCouponCountYoY  = ReportCommonBLL.Instance.CalcuDoD(lastYearAggUnitMonthlyEntity == null ? null : lastYearAggUnitMonthlyEntity.UseCouponCount, aggUnitMonthlyEntity == null ? null : aggUnitMonthlyEntity.UseCouponCount);

            // 销量榜
            rd.UnitCurrentMonthProductSalesTopList = new List <UnitProductSalesTop>();
            if (rUnitProductMonthSalesTopEntities != null && rUnitProductMonthSalesTopEntities.Length > 0)
            {
                var list = rUnitProductMonthSalesTopEntities.ToList();
                foreach (var item in list)
                {
                    rd.UnitCurrentMonthProductSalesTopList.Add(new UnitProductSalesTop
                    {
                        TopIndex    = item.TopIndex,
                        ProductName = item.item_name,
                        ProductSKU  = item.SkuName,
                        SalesAmount = item.SalesQty
                    });
                }
            }

            // 业绩榜
            rd.UnitCurrentMonthSalesAmountEmplTopList = new List <UnitSalesAmountEmplTop>();
            if (aggUnitMonthlyEmplEntities != null && aggUnitMonthlyEmplEntities.Length > 0)
            {
                var list = aggUnitMonthlyEmplEntities.OrderByDescending(p => p.SalesAmount).ThenBy(p => p.EmplName).ToList();
                var i    = 1;
                foreach (var item in list)
                {
                    var user = t_UserEntities.Where(p => p.user_id == item.EmplID).FirstOrDefault();
                    if (user == null)
                    {
                        continue;
                    }

                    rd.UnitCurrentMonthSalesAmountEmplTopList.Add(new UnitSalesAmountEmplTop
                    {
                        TopIndex    = i,
                        EmplName    = item.EmplName,
                        SalesAmount = item.SalesAmount
                    });
                    i++;
                    if (i > 10)
                    {
                        break;
                    }
                }
            }

            // 集客榜
            rd.UnitCurrentMonthSetoffEmplTopList = new List <UnitMonthSetoffEmplTop>();
            if (aggUnitMonthlyEmplEntities != null && aggUnitMonthlyEmplEntities.Length > 0)
            {
                var list = aggUnitMonthlyEmplEntities.OrderByDescending(p => p.SetoffCount).ThenBy(p => p.EmplName).ToList();
                var i    = 1;
                foreach (var item in list)
                {
                    var user = t_UserEntities.Where(p => p.user_id == item.EmplID).FirstOrDefault();
                    if (user == null)
                    {
                        continue;
                    }

                    var empSum = aggUnitNowEmplEntities.FirstOrDefault(it => it.EmplID == item.EmplID);
                    rd.UnitCurrentMonthSetoffEmplTopList.Add(new UnitMonthSetoffEmplTop
                    {
                        TopIndex         = i,
                        EmplName         = item.EmplName,
                        MonthSetoffCount = item.SetoffCount,
                        AllSetoffCount   = empSum != null ? empSum.SetoffCount : 0
                    });
                    i++;
                    if (i > 10)
                    {
                        break;
                    }
                }
            }

            //
            return(rd);
        }
コード例 #18
0
 /// <summary>
 /// 处理接口请求
 /// </summary>
 /// <param name="pVersion">接口版本号</param>
 /// <param name="pRequest">接口请求</param>
 /// <returns>处理结果</returns>
 protected abstract TResponseData ProcessRequest(APIRequest <TRequestPara> pRequest);
コード例 #19
0
ファイル: Payment.cs プロジェクト: venugec/codekit-csharp
                /// <summary>
                /// This function makes API call to Get Transaction Status
                /// </summary>
                /// <param name="idType">idType</param>
                /// <param name="id">id</param>
                public TransactionStatusResponseObj.RootObject getTransactionStatus(string idType, string id)
                {
                    APIRequest apiRequest = new APIRequest("Transactions/" + idType + "/" + id);

                    if (apiService.get(apiRequest))
                    {
                        TransactionStatusResponseObj responseObj = new TransactionStatusResponseObj();
                        return responseObj.deserializeTransactionStatusResponse(apiService.apiResponse.getResponseData());
                    }

                    throw new Exception(apiService.errorResponse);
                }
コード例 #20
0
 private void triggerSuccess <T>(APIRequest <T> req, T result)
     where T : class
 {
     requestComplete = true;
     req.TriggerSuccess(result);
 }
コード例 #21
0
 public APIResponse DeleteAttachment(long attachmentId)
 {
     requestMethod = APIConstants.RequestMethod.DELETE;
     urlPath       = parentRecord.ModuleAPIName + "/" + parentRecord.EntityId + "/" + relatedList.ApiName + "/" + attachmentId;
     return(APIRequest.GetInstance(this).GetAPIResponse());
 }
コード例 #22
0
        protected override ProcessActionRD ProcessRequest(APIRequest <ProcessActionRP> pRequest)
        {
            #region 错误码
            const int ERROR_ORDER_NOTEXISTS = 301;
            const int ERROR_ORDER_PROCESSED = 302;
            #endregion
            ProcessActionRD rd               = new ProcessActionRD();
            T_InoutBLL      _TInoutbll       = new T_InoutBLL(this.CurrentUserInfo);      //订单表
            TInoutStatusBLL _TInoutStatusBLL = new TInoutStatusBLL(this.CurrentUserInfo); //日志表
            VipIntegralBLL  vipIntegralBLL   = new VipIntegralBLL(this.CurrentUserInfo);  //会员业务对象实例化
            var             UserBLL          = new T_UserBLL(this.CurrentUserInfo);       //员工实例

            string OrderID         = pRequest.Parameters.OrderID;                         //订单ID
            string ActionCode      = pRequest.Parameters.ActionCode;                      //订单操作码(当前订单状态码作为操作码)
            string ActionParameter = pRequest.Parameters.ActionParameter;                 //订单操作参数,可为空
            string DeliverCompany  = pRequest.Parameters.DeliverCompany;                  //快递公司
            string DeliverOrder    = pRequest.Parameters.DeliverOrder;                    //快递单号

            string VipID = pRequest.UserID;
            if (pRequest.ChannelId != "2")
            {
                VipID = pRequest.Parameters.VipID;
            }

            var tran = _TInoutbll.GetTran();
            using (tran.Connection)//事物
            {
                try
                {
                    #region 1.根据订单ID,订单操作码更新订单表中订单状态和状态描述

                    var entity = _TInoutbll.GetInoutInfo(OrderID, this.CurrentUserInfo); //根据标识获取新的实例

                    if (entity.status == ActionCode)                                     //判断是否重复操作
                    {
                        throw new APIException("操作已处理")
                              {
                                  ErrorCode = ERROR_ORDER_PROCESSED
                              }
                    }
                    ;

                    #region 当状态为完成时,返现,返积分
                    if (ActionCode == "700" && entity.status != "700")
                    {
                        //确认收货时处理积分、返现、佣金[完成订单]
                        // vipIntegralBLL.OrderReward(entity, tran);
                        new SendOrderRewardMsgBLL().OrderReward(entity, this.CurrentUserInfo, tran);//存入到缓存
                    }

                    #endregion
                    if (entity == null)
                    {
                        throw new APIException(string.Format("未找到OrderID:{0}订单", pRequest.Parameters.OrderID))
                              {
                                  ErrorCode = ERROR_ORDER_NOTEXISTS
                              }
                    }
                    ;

                    if (entity.status == ActionCode) //如果状态以及国内是要提交的状态了,就不要再提交了
                    {
                        return(rd);
                    }

                    string Updatebeforestatus = entity.status_desc;                       //更新之前的订单状态描述
                    entity.status         = ActionCode;                                   //输入的状态码
                    entity.Field7         = ActionCode;
                    entity.status_desc    = GetStatusDesc(ActionCode);                    //输入的状态码对应的状态描述
                    entity.Field10        = GetStatusDesc(ActionCode);                    //Field10=status_desc状态描述
                    entity.modify_time    = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //修改时间
                    entity.modify_user_id = pRequest.UserID;                              //修改人

                    if (ActionCode == "600" || !string.IsNullOrEmpty(DeliverOrder) || !string.IsNullOrEmpty(DeliverCompany))
                    {
                        entity.Field9     = DateTime.Now.ToSQLFormatString();
                        entity.Field2     = DeliverOrder;   //快递单号
                        entity.carrier_id = DeliverCompany; //快递单号
                        //更新订单配送商及配送单号
                    }

                    if (ActionCode == "700" && pRequest.ChannelId != "2")
                    {
                        if (string.IsNullOrEmpty(entity.sales_user))
                        {
                            entity.sales_user = pRequest.UserID;//把当前用户作为服务人员。****!!
                        }
                        //更新订单支付状态
                        entity.Field1       = "1";
                        entity.accpect_time = DateTime.Now.ToString();

                        #region 提货,订单明细修改

                        T_Inout_DetailBLL  inoutDetailBll     = new T_Inout_DetailBLL(CurrentUserInfo);
                        VipAmountDetailBLL vipAmountDetailBll = new VipAmountDetailBLL(CurrentUserInfo);
                        if (pRequest.Parameters.OrderItemInfoList != null)
                        {
                            foreach (var item in pRequest.Parameters.OrderItemInfoList)
                            {
                                T_Inout_DetailEntity inoutDetailEntity = inoutDetailBll.QueryByEntity(new T_Inout_DetailEntity()
                                {
                                    order_id = OrderID, sku_id = item.SkuId
                                }, null).FirstOrDefault();
                                var vipAmountDetailEntity = vipAmountDetailBll.QueryByEntity(new VipAmountDetailEntity()
                                {
                                    ObjectId = OrderID, AmountSourceId = "1"
                                }, null).FirstOrDefault();
                                //将提货金额 + 余额 = SumPrice
                                if (vipAmountDetailEntity != null)
                                {
                                    item.SumPrice += Math.Abs(Convert.ToDecimal(vipAmountDetailEntity.Amount));
                                }
                                inoutDetailEntity.enter_qty    = item.EnterQty;
                                inoutDetailEntity.Field9       = "kg";
                                inoutDetailEntity.enter_amount = item.SumPrice;
                                inoutDetailEntity.enter_price  = Convert.ToDecimal(Math.Round(item.SumPrice / item.EnterQty, 2));
                                entity.total_amount            = entity.total_amount + Math.Round(Convert.ToDecimal(item.SumPrice / (entity.discount_rate / 100)), 2) - inoutDetailEntity.retail_amount;
                                entity.total_retail            = entity.total_amount;
                                entity.actual_amount           = entity.actual_amount + Math.Round(Convert.ToDecimal(item.SumPrice / (entity.discount_rate / 100)), 2) - inoutDetailEntity.retail_amount;
                                inoutDetailBll.Update(inoutDetailEntity, tran);
                            }
                        }
                        #endregion
                    }
                    entity.accpect_time = DateTime.Now.ToString();
                    _TInoutbll.Update(entity, tran); //用事物更新订单表(T_Inout)
                    #endregion



                    #region 2.根据订单ID更新订单日志表中数据

                    string CreateName = "";
                    if (pRequest.ChannelId != "2")
                    {
                        var UserData = UserBLL.GetByID(this.CurrentUserInfo.CurrentUser.User_Id);
                        CreateName = string.Format("[操作人:{0}]", (UserData == null ? "" : UserData.user_name));
                    }
                    else
                    {
                        CreateName = "[操作人:客户]";
                    }



                    var _TInoutStatusEntity = new TInoutStatusEntity()
                    {
                        InoutStatusID = Guid.NewGuid(),
                        OrderID       = OrderID,                                                                     //订单ID
                        OrderStatus   = Convert.ToInt32(ActionCode),                                                 //状态码
                        //StatusRemark = "订单状态从" + Updatebeforestatus + "变为" + GetStatusDesc(ActionCode) + "[操作人:" + CurrentUserInfo.CurrentUser.User_Name + "]",               //状态更新描述
                        StatusRemark = "订单状态从" + Updatebeforestatus + "变为" + GetStatusDesc(ActionCode) + CreateName, //状态更新描述
                        CustomerID   = CurrentUserInfo.ClientID                                                      //客户ID
                    };
                    _TInoutStatusBLL.Create(_TInoutStatusEntity, tran);                                              //用事物更新,向日志表(TInoutStatus)中插入一条数据
                    #endregion

                    tran.Commit();

                    if (ActionCode == "600")
                    {
                        #region 处理订单发货发送微信模板消息
                        //获取会员信息
                        var vipBll       = new VipBLL(CurrentUserInfo);
                        var vipInfo      = vipBll.GetByID(entity.vip_no);
                        var inoutService = new Inout3Service(CurrentUserInfo);
                        //物流公司
                        string LogisticsName = inoutService.GetCompanyName(entity.carrier_id);

                        var InoutInfo = new InoutInfo()
                        {
                            order_no     = entity.order_no,
                            carrier_name = LogisticsName,
                            vipId        = entity.vip_no,
                            Field2       = entity.Field2
                        };

                        //  var CommonBLL = new CommonBLL();
                        //   CommonBLL.SentShipMessage(InoutInfo, vipInfo.WeiXinUserId, InoutInfo.vip_no, CurrentUserInfo);
                        new SendOrderSendMsgBLL().SentShipMessage(InoutInfo, vipInfo.WeiXinUserId, InoutInfo.vip_no, CurrentUserInfo);
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw new APIException(ex.Message)
                          {
                              ErrorCode = ERROR_ORDER_NOTEXISTS
                          };
                }
            }
            return(rd);
        }
コード例 #23
0
        protected override HomePageConfigV2RD ProcessRequest(APIRequest <HomePageConfigV2RP> pRequest)
        {
            //创建连接用户对象
            var logginUserInfo    = base.CurrentUserInfo;
            HomePageConfigV2RD RD = new HomePageConfigV2RD();
            var adBll             = new MHAdAreaBLL(logginUserInfo); //广告部分

            #region 1.获取首页layout模块
            List <layoutList> ArrlayoutList = new List <layoutList> {
            };                                                                            //用于填充layoutList数据集合
            MHCategoryAreaGroupBLL mhBLL    = new MHCategoryAreaGroupBLL(logginUserInfo); //Layout部分
            DataSet layout = mhBLL.GetLayoutList(logginUserInfo.ClientID);
            if (layout != null && layout.Tables[0].Rows.Count > 0)
            {
                layoutList layoutinfo = new layoutList();
                layoutinfo.layoutid = "001";
                layoutinfo.x        = 0;
                layoutinfo.y        = 0;
                layoutinfo.width    = 320;
                layoutinfo.height   = 101;
                layoutinfo.type     = "ad_1"; //广告
                ArrlayoutList.Add(layoutinfo);
                int strhight = layoutinfo.height;
                int bY       = 0;
                for (int i = 0; i < layout.Tables[0].Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        layoutinfo          = new layoutList();
                        layoutinfo.layoutid = layout.Tables[0].Rows[i]["GroupValue"].ToString();
                        layoutinfo.x        = 0;
                        layoutinfo.y        = strhight;
                        layoutinfo.width    = 320;
                        layoutinfo.height   = Convert.ToInt32(layout.Tables[0].Rows[i]["Height"].ToString());
                        layoutinfo.type     = layout.Tables[0].Rows[i]["ModelType"].ToString();
                        bY = layoutinfo.y;
                    }
                    else
                    {
                        int bHeight      = Convert.ToInt32(layout.Tables[0].Rows[i - 1]["height"]);
                        int bTopDistance = Convert.ToInt32(layout.Tables[0].Rows[i - 1]["TopDistance"]);
                        layoutinfo          = new layoutList();
                        layoutinfo.layoutid = layout.Tables[0].Rows[i]["GroupValue"].ToString();
                        layoutinfo.x        = 0;
                        layoutinfo.y        = bY + bHeight + bTopDistance;
                        layoutinfo.width    = 320;
                        layoutinfo.height   = Convert.ToInt32(layout.Tables[0].Rows[i]["height"].ToString());
                        layoutinfo.type     = layout.Tables[0].Rows[i]["modeltype"].ToString();
                        bY = layoutinfo.y;
                    }
                    ArrlayoutList.Add(layoutinfo);
                }
            }
            #endregion

            #region 2.获取homedata模块
            var ArrhomedataList = new List <homedataList> {
            };                                               //用于填充homedata数据集合

            var homeBll = new MobileHomeBLL(this.CurrentUserInfo);
            //根据客户ID获取homeList集合
            var homeList = homeBll.QueryByEntity(new MobileHomeEntity {
                CustomerId = this.CurrentUserInfo.ClientID
            }, null);
            if (homeList != null)
            {
                var homeEntity        = homeList.FirstOrDefault();
                var dsGroup           = adBll.GetCategoryGroupId(homeEntity.HomeId.ToString());
                var ArriteminfoList   = new List <itemsList> {
                };
                homedataList homeinfo = new homedataList();
                itemsList    tempAd   = new itemsList();

                #region  获取广告部分
                var tempAdArealist = adBll.GetByCustomerID().OrderBy(t => t.DisplayIndex);//获取客户下图片广告集合
                if (tempAdArealist != null)
                {
                    homeinfo.layoutid = "001";
                    homeinfo.title    = "Title";
                    foreach (var item in tempAdArealist)
                    {
                        tempAd           = new itemsList();
                        tempAd.imgUrl    = item.ImageUrl;
                        tempAd.tagartUrl = GettagartUrl("MHAdArea", Convert.ToInt32(item.ObjectTypeId), CurrentUserInfo.ClientID.ToString(), item.ObjectId, item.Url, "");
                        tempAd.biztype   = "";
                        tempAd.trackid   = "";
                        ArriteminfoList.Add(tempAd); //广告
                    }
                    homeinfo.items = ArriteminfoList.ToArray();
                    ArrhomedataList.Add(homeinfo);
                }
                #endregion

                #region 获取分类部分
                if (dsGroup != null && dsGroup.Tables.Count > 0 && dsGroup.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in dsGroup.Tables[0].Rows)
                    {
                        ArriteminfoList   = new List <itemsList> {
                        };
                        homeinfo          = new homedataList();
                        homeinfo.layoutid = dr["GroupId"].ToString();
                        homeinfo.title    = "Title";
                        var dsItem = adBll.GetItemList(homeinfo.layoutid, homeEntity.HomeId.ToString());
                        if (dsItem != null && dsItem.Tables.Count > 0 && dsItem.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow itemrow in dsItem.Tables[0].Rows)
                            {
                                tempAd           = new itemsList();
                                tempAd.imgUrl    = itemrow["imageUrl"].ToString();
                                tempAd.tagartUrl = GettagartUrl("MHCategoryArea", Convert.ToInt32(itemrow["typeId"]), CurrentUserInfo.ClientID.ToString(), itemrow["objectId"].ToString(), itemrow["imageUrl"].ToString(), itemrow["categoryAreaId"].ToString());
                                tempAd.biztype   = "";
                                tempAd.trackid   = "1314";
                                ArriteminfoList.Add(tempAd);
                            }
                            homeinfo.items = ArriteminfoList.ToArray(); //分类部分
                            ArrhomedataList.Add(homeinfo);
                        }
                    }
                }
                #endregion
            }
            #endregion

            RD.timespan = "";
            RD.version  = "";
            RD.layout   = ArrlayoutList.ToArray();
            RD.homedata = ArrhomedataList.ToArray();
            return(RD);
        }
コード例 #24
0
        protected override SetMaterialTextRD ProcessRequest(APIRequest <SetMaterialTextRP> pRequest)
        {
            SetMaterialTextRD rd = new SetMaterialTextRD();
            var para             = pRequest.Parameters;

            #region 获取Page信息
            var pageBll = new SysPageBLL(CurrentUserInfo);
            var textBll = new WMaterialTextBLL(CurrentUserInfo);

            //组织图文实体
            var entity = new WMaterialTextEntity()
            {
                ApplicationId = para.MaterialText.ApplicationId,
                CoverImageUrl = para.MaterialText.ImageUrl,
                PageId        = para.MaterialText.PageID,

                PageParamJson    = para.MaterialText.PageParamJson,
                Text             = para.MaterialText.Text,
                TextId           = para.MaterialText.TextId,
                Title            = para.MaterialText.Title,
                TypeId           = para.MaterialText.TypeId,
                Author           = para.MaterialText.Abstract,//摘要使用原来的字段
                IsTitlePageImage = para.MaterialText.IsTitlePageImage
            };
            #endregion

            #region 生成URL
            var Domain = ConfigurationManager.AppSettings["interfacehost"].Replace("http://", "");

            var    Domain1 = ConfigurationManager.AppSettings["interfacehost1"].Replace("http://", "");
            string URL     = string.Empty;
            switch (para.MaterialText.UnionTypeId)
            {
            case "1":    //链接
                #region 链接
                URL = para.MaterialText.OriginalUrl;
                #endregion
                break;

            case "2":    //详情
                #region 详情
                URL = string.Format("http://{0}/Module/WeiXin/MaterialTextDetail.aspx?news_id=#TextId#&customerId=#cutomerId#&interfacehost={1}", Domain1.Trim('/'), ConfigurationManager.AppSettings["interfacehost1"]);
                #endregion
                break;

            case "3":                                                      //系统模块
                #region 系统模块
                var pages = pageBll.GetPageByID(para.MaterialText.PageID); //通过pageid查找syspage信息
                if (pages.Length == 0)
                {
                    throw new APIException("未找到Page:" + para.MaterialText.PageID)
                          {
                              ErrorCode = 341
                          }
                }
                ;
                SysPageEntity CurrentPage;
                string        path               = string.Empty;                                                                           //要替换的路径
                string        urlTemplate        = pages[0].URLTemplate;                                                                   //模板URL
                string        json               = pages[0].JsonValue;                                                                     // JSON体
                var           jsonDic            = json.DeserializeJSONTo <Dictionary <string, object> >();                                //转换后的字典
                var           htmls              = jsonDic["htmls"].ToJSON().DeserializeJSONTo <Dictionary <string, object>[]>().ToList(); //所有的Html模板
                Dictionary <string, object> html = null;                                                                                   //选择的html信息
                var defaultHtmlId = jsonDic["defaultHtml"].ToString();
                html = htmls.Find(t => t["id"].ToString() == defaultHtmlId);                                                               //默认的htmlid*****
                if (html != null)
                {
                    path = html["path"].ToString();
                }
                //判断高级oauth认证
                var scope = "snsapi_base";
                if (jsonDic.ContainsKey("scope"))
                {
                    scope = (jsonDic["scope"] == null || jsonDic["scope"] == "") ? "snsapi_base" : "snsapi_userinfo";
                }


                //判断是否有定制,没有则取JSON体中的默认
                //找出订制内容
                var customerPages = pages.ToList().FindAll(t => t.CustomerID == CurrentUserInfo.ClientID);
                if (customerPages.Count > 0)
                {
                    //看是否有htmls的定制(Node值=2)
                    CurrentPage = customerPages.Find(t => t.Node == "2");
                    if (CurrentPage != null)
                    {
                        var nodeValue = CurrentPage.NodeValue;
                        //在Json解析后的集合中找到path
                        html = htmls.Find(t => t["id"].ToString() == nodeValue);
                        if (html != null)
                        {
                            path = html["path"].ToString();
                        }
                    }
                    else
                    {
                        CurrentPage = pages[0];
                    }
                }
                else
                {
                    CurrentPage = pages[0];
                }
                //读取配置信息域名,检查不用http://开头,如果有则去除
                var IsAuth = false;
                //TODO:判断页面是否需要Auth认证,如果页面需要证则再判断这个客户有没有Auth认证,Type=3
                if (CurrentPage.IsAuth == 1)
                {
                    //判断这个客户是否是认证客户,type=3
                    var applicationBll = new WApplicationInterfaceBLL(CurrentUserInfo);
                    var application    = applicationBll.GetByID(para.MaterialText.ApplicationId);
                    if (application.WeiXinTypeId == "3")
                    {
                        IsAuth = true;
                    }
                }

                //替换URL模板
                #region 替换URL模板
                urlTemplate = urlTemplate.Replace("_pageName_", path);
                var paraDic = para.MaterialText.PageParamJson.DeserializeJSONTo <Dictionary <string, object>[]>();
                foreach (var item in paraDic)       //这里key和value对于活动来说,其实就是活动的eventId,和eventId的值
                {
                    if (item.ContainsKey("key") && item.ContainsKey("value"))
                    {
                        urlTemplate = urlTemplate.Replace("{" + item["key"] + "}", item["value"].ToString());
                    }
                }
                #endregion

                //根据规则组织URL
                #region 组织URL
                //读取配置文件中的域名

                if (string.IsNullOrEmpty(Domain))
                {
                    throw new APIException("微信管理:未配置域名,请在web.config中添加<add key='host' value=''/>")
                          {
                              ErrorCode = 342
                          }
                }
                ;
                if (IsAuth)
                {
                    //需要认证,并加上scope类型
                    URL = string.Format("http://{0}/WXOAuth/AuthUniversal.aspx?customerId={1}&applicationId={2}&goUrl={3}&scope={4}", Domain.Trim('/'), CurrentUserInfo.ClientID, para.MaterialText.ApplicationId, HttpUtility.UrlEncode(string.Format("{0}{1}", Domain.Trim('/'), urlTemplate)), scope);
                }
                else
                {
                    //不需要认证
                    URL = string.Format("http://{0}/WXOAuth/NoAuthGoto.aspx?customerId={1}&goUrl={2}", Domain.Trim('/'), CurrentUserInfo.ClientID, HttpUtility.UrlEncode(string.Format("{0}{1}", Domain.Trim('/'), urlTemplate.Trim('/'))));
                }
                entity.IsAuth        = Convert.ToInt32(IsAuth);
                entity.PageParamJson = para.MaterialText.PageParamJson;
                #endregion
                #endregion
                break;

            default:
                break;
            }

            entity.OriginalUrl = URL;//图文素材
            #endregion

            #region 保存
            var unionMappingBll = new WModelTextMappingBLL(CurrentUserInfo);
            //检查图文素材是否重复
            if (textBll.CheckName(entity.ApplicationId, entity.Title, entity.TextId))
            {
                throw new APIException("标题重复,请重新输入.")
                      {
                          ErrorCode = ERROR_CODES.INVALID_REQUEST
                      };
            }
            if (string.IsNullOrEmpty(entity.TextId))
            {
                entity.TextId = Guid.NewGuid().ToString("N");
                #region 图文详情要对占位符#TextId#和#customerId#进行替换
                entity.OriginalUrl = entity.OriginalUrl.Replace("#TextId#", entity.TextId).Replace("#cutomerId#", CurrentUserInfo.ClientID);
                #endregion
                textBll.Create(entity);
                var mapping = new WModelTextMappingEntity()
                {
                    MappingId = Guid.NewGuid().ToString("N"),
                    ModelId   = entity.TypeId,
                    TextId    = entity.TextId,
                };
                unionMappingBll.Create(mapping);
            }
            else
            {
                #region 图文详情要对占位符#textId和#customerId进行替换
                entity.OriginalUrl = entity.OriginalUrl.Replace("#TextId#", entity.TextId).Replace("#cutomerId#", CurrentUserInfo.ClientID);
                #endregion
                textBll.Update(entity);
            }

            #region 图文分类和图文Mapping关系,先删除再增加
            var modelMappingBll = new WModelTextMappingBLL(CurrentUserInfo);
            modelMappingBll.DeleteByTextId(entity.TextId);
            var modelMapping = new WModelTextMappingEntity()
            {
                MappingId = Guid.NewGuid().ToString("N"),
                ModelId   = entity.TypeId, //模板的标识竟然是和图文类型的标识
                TextId    = entity.TextId
            };
            modelMappingBll.Create(modelMapping);
            #endregion

            #endregion

            rd.MaterialTextId = entity.TextId;
            return(rd);
        }
コード例 #25
0
        protected override Get_R_Withdraw_HomeRD ProcessRequest(APIRequest <EmptyRequestParameter> pRequest)
        {
            var loggingSessionInfo = new SessionManager().CurrentUserLoginInfo;

            if (loggingSessionInfo == null)
            {
                throw new APIException("用户未登录")
                      {
                          ErrorCode = ERROR_CODES.INVALID_REQUEST
                      }
            }
            ;
            R_Withdraw_HomeBLL    bll    = new R_Withdraw_HomeBLL(loggingSessionInfo);
            Get_R_Withdraw_HomeRD result = new Get_R_Withdraw_HomeRD();

            //1=提现金额 2=可提现金额 3=当年已完成提现金额 4=超级分销商 5=待批准提现笔数
            var vipEntity  = bll.GetTopListByCustomer(loggingSessionInfo.ClientID, 1);
            var userEntity = bll.GetTopListByCustomer(loggingSessionInfo.ClientID, 2);
            var srtEntity  = bll.GetTopListByCustomer(loggingSessionInfo.ClientID, 4);

            result.List.Add(new WithdrawInfo()
            {
                Type = 1, Vip = vipEntity.BalanceTotal, User = userEntity.BalanceTotal, SRT = srtEntity.BalanceTotal, Count = vipEntity.BalanceTotal + userEntity.BalanceTotal + srtEntity.BalanceTotal
            });
            result.List.Add(new WithdrawInfo()
            {
                Type = 2, Vip = vipEntity.CanWithdrawTotal, User = userEntity.CanWithdrawTotal, SRT = srtEntity.CanWithdrawTotal, Count = vipEntity.CanWithdrawTotal + userEntity.CanWithdrawTotal + srtEntity.CanWithdrawTotal
            });
            result.List.Add(new WithdrawInfo()
            {
                Type = 4, Vip = vipEntity.CurrYearFinishWithdrawTotal, User = userEntity.CurrYearFinishWithdrawTotal, SRT = srtEntity.CurrYearFinishWithdrawTotal, Count = vipEntity.CurrYearFinishWithdrawTotal + userEntity.CurrYearFinishWithdrawTotal + srtEntity.CurrYearFinishWithdrawTotal
            });
            result.List.Add(new WithdrawInfo()
            {
                Type = 5, Vip = vipEntity.PreAuditWithdrawNumber, User = userEntity.PreAuditWithdrawNumber, SRT = srtEntity.PreAuditWithdrawNumber, Count = vipEntity.PreAuditWithdrawNumber + userEntity.PreAuditWithdrawNumber + srtEntity.PreAuditWithdrawNumber
            });

            if (srtEntity == null)
            {
                srtEntity = new R_Withdraw_HomeEntity();
            }

            #region 余额非空判断
            if (vipEntity.BalanceTotal == null)
            {
                vipEntity.BalanceTotal = 0;
            }
            if (userEntity.BalanceTotal == null)
            {
                userEntity.BalanceTotal = 0;
            }
            if (srtEntity.BalanceTotal == null)
            {
                srtEntity.BalanceTotal = 0;
            }
            #endregion

            #region 可提现金额总计 非空判断
            if (vipEntity.CanWithdrawTotal == null)
            {
                vipEntity.CanWithdrawTotal = 0;
            }

            if (userEntity.CanWithdrawTotal == null)
            {
                userEntity.CanWithdrawTotal = 0;
            }

            if (srtEntity.CanWithdrawTotal == null)
            {
                srtEntity.CanWithdrawTotal = 0;
            }
            #endregion

            #region 待批准提现金额总计 非空判断
            if (vipEntity.PreAuditWithdrawNumber == null)
            {
                vipEntity.PreAuditWithdrawNumber = 0;
            }

            if (userEntity.PreAuditWithdrawNumber == null)
            {
                userEntity.PreAuditWithdrawNumber = 0;
            }

            if (srtEntity.PreAuditWithdrawNumber == null)
            {
                srtEntity.PreAuditWithdrawNumber = 0;
            }
            #endregion

            #region 待批准提现笔数总计 非空判断
            if (vipEntity.PreAuditWithdrawTotal == null)
            {
                vipEntity.PreAuditWithdrawTotal = 0;
            }

            if (userEntity.PreAuditWithdrawTotal == null)
            {
                userEntity.PreAuditWithdrawTotal = 0;
            }

            if (srtEntity.PreAuditWithdrawTotal == null)
            {
                srtEntity.PreAuditWithdrawTotal = 0;
            }
            #endregion

            #region 当年已完成提现笔数总计 非空判断
            if (vipEntity.CurrYearFinishWithdrawNumber == null)
            {
                vipEntity.CurrYearFinishWithdrawNumber = 0;
            }

            if (userEntity.CurrYearFinishWithdrawNumber == null)
            {
                userEntity.CurrYearFinishWithdrawNumber = 0;
            }

            if (srtEntity.CurrYearFinishWithdrawNumber == null)
            {
                srtEntity.CurrYearFinishWithdrawNumber = 0;
            }
            #endregion

            #region 当年已完成提现笔数总计 非空判断

            if (vipEntity.CurrYearFinishWithdrawTotal == null)
            {
                vipEntity.CurrYearFinishWithdrawTotal = 0;
            }

            if (userEntity.CurrYearFinishWithdrawTotal == null)
            {
                userEntity.CurrYearFinishWithdrawTotal = 0;
            }

            if (srtEntity.CurrYearFinishWithdrawTotal == null)
            {
                srtEntity.CurrYearFinishWithdrawTotal = 0;
            }
            #endregion

            result.List.Add(new WithdrawInfo()
            {
                Type = 1, Vip = vipEntity.BalanceTotal, User = userEntity.BalanceTotal, SRT = srtEntity.BalanceTotal, Count = vipEntity.BalanceTotal + userEntity.BalanceTotal + srtEntity.BalanceTotal
            });
            result.List.Add(new WithdrawInfo()
            {
                Type = 2, Vip = vipEntity.CanWithdrawTotal, User = userEntity.CanWithdrawTotal, SRT = srtEntity.CanWithdrawTotal, Count = vipEntity.CanWithdrawTotal + userEntity.CanWithdrawTotal + srtEntity.CanWithdrawTotal
            });
            result.List.Add(new WithdrawInfo()
            {
                Type = 4, Vip = vipEntity.CurrYearFinishWithdrawTotal, User = userEntity.CurrYearFinishWithdrawTotal, SRT = srtEntity.CurrYearFinishWithdrawTotal, Count = vipEntity.CurrYearFinishWithdrawTotal + userEntity.CurrYearFinishWithdrawTotal + srtEntity.CurrYearFinishWithdrawTotal
            });
            result.List.Add(new WithdrawInfo()
            {
                Type = 5, Vip = vipEntity.PreAuditWithdrawNumber, User = userEntity.PreAuditWithdrawNumber, SRT = srtEntity.PreAuditWithdrawNumber, Count = vipEntity.PreAuditWithdrawNumber + userEntity.PreAuditWithdrawNumber + srtEntity.PreAuditWithdrawNumber
            });
            result.List.Add(new WithdrawInfo()
            {
                Type = 3, Vip = vipEntity.PreAuditWithdrawTotal, User = userEntity.PreAuditWithdrawTotal, SRT = srtEntity.PreAuditWithdrawTotal, Count = vipEntity.PreAuditWithdrawTotal + userEntity.PreAuditWithdrawTotal + srtEntity.PreAuditWithdrawTotal
            });
            result.List.Add(new WithdrawInfo()
            {
                Type = 6, Vip = vipEntity.CurrYearFinishWithdrawNumber, User = userEntity.CurrYearFinishWithdrawNumber, SRT = srtEntity.CurrYearFinishWithdrawNumber, Count = vipEntity.CurrYearFinishWithdrawNumber + userEntity.CurrYearFinishWithdrawNumber + srtEntity.CurrYearFinishWithdrawNumber
            });
            result.isConfigRule = bll.IsConfigRule(loggingSessionInfo.CurrentUser.customer_id);
            return(result);
        }
    }
コード例 #26
0
ファイル: TeamDb.cs プロジェクト: mexaniksay/GamePro02
		public async Task AddGGTeamToSQL(Match teamInfo,string key)
		{
			APIRequest ApiReq = new APIRequest ();
			DBComm command = new DBComm (key);
			Team team = new Team ();
			team.Name= teamInfo.Groups [2].Value;
			string logoUrl="http://www.gosugamers.net/"+teamInfo.Groups [1].Value;
			string tag=teamInfo.Groups [2].Value;
			team.Tag = tag;
			if (tag.Length > 10) {
				team.Tag = tag.Substring (0, 10);
			}
			team.LogoByte =  await ApiReq.FetchByteArrAsync (logoUrl);
			command.Connect.Insert (team);
			command.Connect.Dispose();
		}
コード例 #27
0
ファイル: Payment.cs プロジェクト: venugec/codekit-csharp
                /// <summary>
                /// This function makes API call to Get Subscription Status
                /// </summary>
                /// <param name="idType">idType</param>
                /// <param name="id">id</param>
                public SubscriptionStatusResponseObj.RootObject getSubscriptionStatus(string idType, string id)
                {
                    APIRequest apiRequest = new APIRequest("Subscriptions/" + idType + "/" + id);

                    apiRequest.accept = "application/json";

                    if (apiService.get(apiRequest))
                    {
                        SubscriptionStatusResponseObj responseObj = new SubscriptionStatusResponseObj();
                        return responseObj.deserializeSubscriptionStatusResponse(apiService.apiResponse.getResponseData());
                    }

                    throw new Exception(apiService.errorResponse);
                }
コード例 #28
0
 private void triggerFail(APIRequest req)
 {
     requestComplete = true;
     req.TriggerFailure(new WebException("Failed."));
 }
コード例 #29
0
 /// <summary>
 /// 默认构造方法,传入API请求对象。
 /// </summary>
 /// <param name="request">API请求对象。</param>
 public ClientHttpUtility(APIRequest request)
 {
     this._request = request;
 }//end constructor
コード例 #30
0
        public ActionResult Download2Disk(int id = 0)
        {
            APIRequest apiRequest = db.APIRequests.Find(id);

            string maxFileSizeS = "1000000000000000";



            int typeIndex = apiRequest.type.IndexOf("#");

            if (typeIndex > 0)
            {
                maxFileSizeS    = apiRequest.type.Substring(typeIndex + 1);
                apiRequest.type = apiRequest.type.Substring(0, typeIndex);
            }

            double maxFileSize = Double.Parse(maxFileSizeS);

            DateTime StartTime = DateTime.Now;
            DateTime EndTime   = DateTime.Now;

            if (apiRequest.type == "json")
            {
                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.ping_Json_DataSource(apiRequest.url);
                EndTime          = DateTime.Now;
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowJSON"));
            }

            if (apiRequest.type == "netCDF")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");

                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.ping_small_NetCDF_file(apiRequest.url, workingDirectorypath);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }

            if (apiRequest.type == "netCDFFtp")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");

                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.get_big_NetCDF_by_ftp(apiRequest.url, workingDirectorypath);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }

            if (apiRequest.type == "netCDFFtp2")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");

                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.get_big_NetCDF_by_ftp2(apiRequest.url, workingDirectorypath);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }

            if (apiRequest.type == "netCDFFtp3")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");

                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.get_big_NetCDF_by_ftp3(apiRequest.url, workingDirectorypath);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }

            if (apiRequest.type == "netCDFFtp4")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");

                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.get_big_NetCDF_by_ftp4(apiRequest.url, workingDirectorypath);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }

            if (apiRequest.type == "FTP-netCDF")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");

                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.get_big_NetCDF_by_ftp2(apiRequest.url, workingDirectorypath);

                EndTime = DateTime.Now;

                TimeSpan TotalTime = EndTime - StartTime;
                apiRequest.startGetTime    = StartTime;
                apiRequest.endGetTime      = EndTime;
                apiRequest.spanGetTime     = TotalTime;
                apiRequest.onDisk          = "File";
                db.Entry(apiRequest).State = System.Data.EntityState.Modified;
                db.SaveChanges();


                DataSetSchema schema = AnalyzeFileDiskAction(id);


                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }


            return(View("ShowError"));
        }
コード例 #31
0
		async Task SetHeroesImageInLayout(CancellationToken token)
		{
			refreshFlag = true;
			APIRequest ApiReq = new APIRequest ();
			HeroDb heroDb = new HeroDb ();
			for (int i = 0; i < 5; i++) {
				token.ThrowIfCancellationRequested();

				Hero newHero = new Hero ();
				if (radiantPB.ListBanView [i].HeroId != 0) {
					var viewBanRad = FindViewById<RelativeLayout> (radiantPB.ListBanView [i].ResourceId);
					var imgRad = viewBanRad.FindViewById<ImageView> (Resource.Id.imageBan);
					var imgLine = viewBanRad.FindViewById<ImageView> (Resource.Id.imageLineBan);

					if (imgRad.Tag.ToString() == "no_ban") {
						//if (imgRad.GetTag == Resources.GetDrawable( Resource.Drawable.no_ban))
						//Bitmap bitmap = (BitmapDrawable)imgRad.Drawable.;
						newHero = heroDb.GetHeroFromSQL (radiantPB.ListBanView [i].HeroId);
						Bitmap b = BitmapFactory.DecodeByteArray (newHero.ImageHero, 0, newHero.ImageHero.Length);
						imgRad.SetImageBitmap (b);
						imgRad.Tag = "on_ban";
						imgLine.SetBackgroundResource (Resource.Drawable.on_ban);
						//img.SetScaleType (ImageView.ScaleType.Center);
					}
				}
				newHero = new Hero ();
				if (direPB.ListBanView [i].HeroId != 0) {
					var viewBanDire = FindViewById<RelativeLayout> (direPB.ListBanView [i].ResourceId);
					var imgDire = viewBanDire.FindViewById<ImageView> (Resource.Id.imageBan);
					var imgLine = viewBanDire.FindViewById<ImageView> (Resource.Id.imageLineBan);
					if (imgDire.Tag.ToString() == "no_ban") {
						newHero = heroDb.GetHeroFromSQL (direPB.ListBanView [i].HeroId);
						Bitmap b1 = BitmapFactory.DecodeByteArray (newHero.ImageHero, 0, newHero.ImageHero.Length);
						imgDire.SetImageBitmap (b1);
						imgDire.Tag = "on_ban";
						imgLine.SetBackgroundResource (Resource.Drawable.on_ban);
					}
				}
			}

			for (int i = 0; i < 5; i++) {
				token.ThrowIfCancellationRequested();
				Hero newHero = new Hero ();
				if (radiantPB.ListPicksView [i].HeroId != 0) {
					var viewPickRad = FindViewById<RelativeLayout> (radiantPB.ListPicksView [i].ResourceId);
					var imgRad = viewPickRad.FindViewById<ImageView> (Resource.Id.imagePick);
					var textHero = viewPickRad.FindViewById<TextView> (Resource.Id.textHeroNamePickTemp);
					if (imgRad.Tag.ToString() =="no_pick") {
						newHero = heroDb.GetHeroFromSQL (radiantPB.ListPicksView [i].HeroId);
						byte[] arr=await ApiReq.FetchByteArrAsync (newHero.FVerImgUrl);
						Bitmap b = BitmapFactory.DecodeByteArray (arr, 0, arr.Length);
						imgRad.SetImageBitmap (b);
						imgRad.Tag = "on_pick";
						textHero.SetBackgroundResource (Resource.Drawable.gradientDarkBlueToTransp);
						textHero.Text = newHero.LocalName;
					}
				}
				newHero = new Hero ();
				if (direPB.ListPicksView [i].HeroId != 0) {
					var viewPickDire = FindViewById<RelativeLayout> (direPB.ListPicksView [i].ResourceId);
					var imgDire = viewPickDire.FindViewById<ImageView> (Resource.Id.imagePick);
					var textHero = viewPickDire.FindViewById<TextView> (Resource.Id.textHeroNamePickTemp);
					if (imgDire.Tag.ToString() == "no_pick") {
						newHero = heroDb.GetHeroFromSQL (direPB.ListPicksView [i].HeroId);
						byte[] arr=await ApiReq.FetchByteArrAsync (newHero.FVerImgUrl);
						Bitmap b1 = BitmapFactory.DecodeByteArray (arr, 0, arr.Length);
						imgDire.SetImageBitmap (b1);
						imgDire.Tag = "on_pick";
						textHero.SetBackgroundResource (Resource.Drawable.gradientDarkBlueToTransp);
						textHero.Text = newHero.LocalName;

					}
				}
			}
			refreshFlag = false;
		}
コード例 #32
0
        public ActionResult Download(int id = 0)
        {
            APIRequest apiRequest = db.APIRequests.Find(id);

            string maxFileSizeS = "1000000000000000";



            int typeIndex = apiRequest.type.IndexOf("#");

            if (typeIndex > 0)
            {
                maxFileSizeS    = apiRequest.type.Substring(typeIndex + 1);
                apiRequest.type = apiRequest.type.Substring(0, typeIndex);
            }

            double maxFileSize = Double.Parse(maxFileSizeS);

            DateTime StartTime = DateTime.Now;
            DateTime EndTime   = DateTime.Now;

            if (apiRequest.type == "json")
            {
                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.ping_Json_DataSource(apiRequest.url);
                EndTime          = DateTime.Now;
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowJSON"));
            }

            if (apiRequest.type == "netCDF")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");

                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.ping_small_NetCDF_file(apiRequest.url, workingDirectorypath);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }

            if (apiRequest.type == "netCDFFtp")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");
                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.get_big_NetCDF_by_ftp(apiRequest.url, workingDirectorypath);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }

            if (apiRequest.type == "netCDFFtp2")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");
                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.get_big_NetCDF_by_ftp2(apiRequest.url, workingDirectorypath);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }

            if (apiRequest.type == "netCDFFtp3")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");
                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.get_big_NetCDF_by_ftp3(apiRequest.url, workingDirectorypath);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }

            if (apiRequest.type == "netCDFFtp4")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");
                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.get_big_NetCDF_by_ftp4(apiRequest.url, workingDirectorypath);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }

            if (apiRequest.type == "FTP-netCDF")
            {
                string workingDirectorypath = HttpContext.Server.MapPath("~/App_Data");
                ViewBag.request  = apiRequest.url;
                ViewBag.response = apiCaller.get_big_NetCDF_by_ftp5(apiRequest.url, workingDirectorypath, maxFileSize);
                TimeSpan TotalTime = EndTime - StartTime;
                ViewBag.TotalTime = "hs: " + TotalTime.TotalHours + "mins: " + TotalTime.TotalMinutes + "secs: " + TotalTime.TotalSeconds;
                return(View("ShowNetCDF"));
            }


            return(View("ShowError"));
        }
コード例 #33
0
ファイル: ShiftPlanning.cs プロジェクト: steewsc/cs-sdk
    private string setRequest(RequestFields requestFields)
    {
        // set the request parameters
        // clear out previous request data
        this.request = new APIRequest();

        // set the default response type of JSON
        this.request.Output = output_type;
        this.request.Key = this._key;
        this.request.Token = this._token;
        this.request.RequestFields = requestFields;

        this._init = 0;
        if (requestFields["module"].ToString() == "staff.login") this._init = 1;

        return this.api();
    }
コード例 #34
0
        const int ERROR_LOAD_WRONG  = 302; //打开出错
        protected override GetSetoffToolDetailRD ProcessRequest(APIRequest <GetSetoffToolDetailRP> pRequest)
        {
            string content    = string.Empty;
            string customerId = string.Empty;
            GetSetoffToolDetailRD setoffToolDetailRD = new GetSetoffToolDetailRD();
            var para = pRequest.Parameters;

            customerId = CurrentUserInfo.CurrentUser.customer_id;
            try
            {
                var    imageUrl              = string.Empty;
                Random ro                    = new Random();
                var    iUp                   = 100000000;
                var    iDown                 = 50000000;
                var    rpVipDCode            = 0;                   //临时二维码
                var    iResult               = ro.Next(iDown, iUp); //随机数
                var    userQrCodeBll         = new WQRCodeManagerBLL(CurrentUserInfo);
                var    imgBll                = new ObjectImagesBLL(CurrentUserInfo);
                var    setOffPosterBLL       = new SetoffPosterBLL(CurrentUserInfo);
                var    SetoffToolUserViewBLL = new SetoffToolUserViewBLL(CurrentUserInfo);
                var    SetoffToolsBll        = new SetoffToolsBLL(CurrentUserInfo);
                var    SetOffPosterInfo      = setOffPosterBLL.QueryByEntity(new SetoffPosterEntity()
                {
                    SetoffPosterID = new Guid(para.ObjectId)
                }, null);                                                                                                                         //获取集客海报信息
                var setoffEventBLL  = new SetoffEventBLL(CurrentUserInfo);
                var setoffEventInfo = setoffEventBLL.QueryByEntity(new SetoffEventEntity()
                {
                    Status = "10", SetoffType = 1, CustomerId = customerId
                }, null);
                //var SetoffToolsInfo = SetoffToolsBll.QueryByEntity(new SetoffToolsEntity() { ObjectId = para.ObjectId, Status = "10", ToolType = para.ToolType, SetoffEventID = setoffEventInfo[0].SetoffEventID }, null);//获取工具信息
                //VipDcode=9生成永久二维码
                if (para.VipDCode == 9)
                {
                    //根据分享人ID和对象ID获取永久二维码信息
                    var userQrCode = userQrCodeBll.QueryByEntity(new WQRCodeManagerEntity()
                    {
                        ObjectId = para.ObjectId
                    }, null);
                    if (userQrCode != null && userQrCode.Length > 0)
                    {
                        if (para.ToolType == "Coupon")//如果类型为优惠券则返回二维码
                        {
                            setoffToolDetailRD.ToolType = para.ToolType;
                        }
                        if (para.ToolType == "SetoffPoster")//如果为集客海报则返回背景图和二维码
                        {
                            if (SetOffPosterInfo != null)
                            {
                                var backImgInfo = imgBll.QueryByEntity(new ObjectImagesEntity()
                                {
                                    ObjectId = SetOffPosterInfo[0].ImageId
                                }, null);
                                setoffToolDetailRD.ToolType   = para.ToolType;
                                setoffToolDetailRD.imageUrl   = userQrCode[0].ImageUrl;
                                setoffToolDetailRD.paraTemp   = userQrCode[0].QRCode;
                                setoffToolDetailRD.backImgUrl = backImgInfo[0].ImageURL;
                            }
                        }
                        setoffToolDetailRD.imageUrl = userQrCode[0].ImageUrl;
                        setoffToolDetailRD.paraTemp = userQrCode[0].QRCode;
                        return(setoffToolDetailRD);
                    }
                    //获取当前二维码 最大值
                    iResult    = new WQRCodeManagerBLL(CurrentUserInfo).GetMaxWQRCod() + 1;
                    rpVipDCode = 1;
                }

                #region 获取微信帐号
                var server = new WApplicationInterfaceBLL(CurrentUserInfo);
                var wxObj  = new WApplicationInterfaceEntity();
                wxObj = server.QueryByEntity(new WApplicationInterfaceEntity {
                    CustomerId = customerId
                }, null).FirstOrDefault();
                if (wxObj == null)
                {
                    throw new APIException("不存在对应的微信帐号.")
                          {
                              ErrorCode = ERROR_NULL_WXOBJ
                          };
                }
                else
                {
                    var commonServer = new CommonBLL();
                    //rpVipDCode 二维码类型  0: 临时二维码  1:永久二维码
                    imageUrl = commonServer.GetQrcodeUrl(wxObj.AppID, wxObj.AppSecret, rpVipDCode.ToString(""), iResult, CurrentUserInfo);//iResult作为场景值ID,临时二维码时为32位整型,永久二维码时只支持1--100000
                    //供本地测试时使用  "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGN7zoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL1dreENCS1htX0xxQk94SEJ6MktIAAIEUk88VwMECAcAAA==";
                }
                #endregion

                if (para.VipDCode == 9 && !string.IsNullOrEmpty(imageUrl))    //永久二维码
                {
                    #region 创建店员永久二维码匹配表
                    var    userQrTypeBll = new WQRCodeTypeBLL(CurrentUserInfo);
                    string pTypeCode     = string.Empty;
                    if (para.ToolType.ToLower() == "coupon")
                    {
                        pTypeCode = "CouponQrCode";
                    }
                    if (para.ToolType.ToLower() == "setoffposter")
                    {
                        pTypeCode = "SetoffPosterQrCode";
                    }
                    if (para.ToolType.ToLower() == "superretail")
                    {
                        pTypeCode = "SuperRetailQrCode";
                    }
                    var userQrType = userQrTypeBll.QueryByEntity(new WQRCodeTypeEntity()
                    {
                        TypeCode = pTypeCode
                    }, null);                                                                                            //"SuperRetailQrCode=超级分销商二维码"
                    if (userQrType != null && userQrType.Length > 0)
                    {
                        var userQrcodeBll = new WQRCodeManagerBLL(CurrentUserInfo);
                        var userQrCode    = new WQRCodeManagerEntity();
                        userQrCode.QRCode        = iResult.ToString();//记录传过去的二维码场景值
                        userQrCode.QRCodeTypeId  = userQrType[0].QRCodeTypeId;
                        userQrCode.IsUse         = 1;
                        userQrCode.CustomerId    = customerId;
                        userQrCode.ImageUrl      = imageUrl;
                        userQrCode.ApplicationId = wxObj.ApplicationId;
                        //objectId 为集客海报ID或者优惠券ID
                        userQrCode.ObjectId = para.ObjectId;
                        userQrcodeBll.Create(userQrCode);
                    }
                    #endregion
                }
                else
                {
                    #region 创建临时匹配表
                    VipDCodeBLL    vipDCodeServer = new VipDCodeBLL(CurrentUserInfo);
                    VipDCodeEntity info           = new VipDCodeEntity();
                    info.DCodeId    = iResult.ToString();//记录传过去的二维码场景值****(保存到数据库时没加空格)
                    info.CustomerId = customerId;
                    VipBLL vipBll = new VipBLL(CurrentUserInfo);
                    info.UnitId      = "";
                    info.Status      = "0";
                    info.IsReturn    = 0;
                    info.DCodeType   = para.VipDCode;
                    info.CreateBy    = CurrentUserInfo.UserID;
                    info.ImageUrl    = imageUrl;
                    info.VipId       = "";
                    info.ObjectId    = para.ObjectId;   //工具对象ID(优惠券或集客海报对象ID)
                    info.OwnerUserId = para.ShareVipId; //分享人ID
                    vipDCodeServer.Create(info);
                    #endregion
                }
                int flag         = 0;//定义是否需要新增打开数据,0=不需要新增,1=需要新增
                var UserViewData = SetoffToolUserViewBLL.QueryByEntity(new SetoffToolUserViewEntity()
                {
                    ObjectId = para.ObjectId, UserID = CurrentUserInfo.UserID
                }, null);
                if (!string.IsNullOrEmpty(para.SetoffToolID))
                {
                    UserViewData = SetoffToolUserViewBLL.QueryByEntity(new SetoffToolUserViewEntity()
                    {
                        ObjectId = para.ObjectId, UserID = CurrentUserInfo.UserID, SetoffToolID = new Guid(para.SetoffToolID)
                    }, null);
                }
                if (UserViewData.Length == 0 && !string.IsNullOrEmpty(para.SetoffToolID) && para.PlatformType != "3")
                {
                    flag = 1;                  //当为1时进行增加打开工具记录
                }
                if (para.ToolType == "Coupon") //如果类型为优惠券则返回二维码
                {
                    #region 用户领优惠券过程
                    var CouponTypeBLL       = new CouponTypeBLL(CurrentUserInfo);
                    var couponBLL           = new CouponBLL(CurrentUserInfo);
                    var CouponSourceBLL     = new CouponSourceBLL(CurrentUserInfo);
                    var VipCouponMappingBLL = new VipCouponMappingBLL(CurrentUserInfo);

                    int?SurplusCount   = 0; //先获得剩余张数
                    int hasCouponCount = 0; //已领张数 如果>0表示已领取过就不让他领,=0就领取
                    var couponTypeInfo = CouponTypeBLL.QueryByEntity(new CouponTypeEntity()
                    {
                        CouponTypeID = new Guid(para.ObjectId)
                    }, null);

                    if (couponTypeInfo != null)
                    {
                        string couponIsVocher = string.Empty;
                        if (couponTypeInfo[0].IsVoucher == null)
                        {
                            SurplusCount = couponTypeInfo[0].IssuedQty - 0;
                        }
                        else
                        {
                            SurplusCount = couponTypeInfo[0].IssuedQty - couponTypeInfo[0].IsVoucher;
                        }
                        if (SurplusCount != 0 && para.ShareVipId != null && para.ShareVipId != "")// 通过列表进详细自己不能领券
                        {
                            //当剩余数量不为0时,进行下一步判断是否存在已领券的信息
                            hasCouponCount = VipCouponMappingBLL.GetReceiveCouponCount(CurrentUserInfo.UserID, para.ObjectId, "Share");
                            if (hasCouponCount == 0)//如果等于零,开始领券流程
                            {
                                //关联优惠券让用户领券
                                var redisVipMappingCouponBLL = new JIT.CPOS.BS.BLL.RedisOperationBLL.Coupon.RedisVipMappingCouponBLL();
                                try
                                {
                                    //执行领取操作
                                    redisVipMappingCouponBLL.InsertDataBase(CurrentUserInfo.CurrentUser.customer_id, CurrentUserInfo.UserID, para.SetoffToolID, "Share", new CC_Coupon()
                                    {
                                        CustomerId   = CurrentUserInfo.CurrentUser.customer_id,
                                        CouponTypeId = para.ObjectId
                                    });
                                    setoffToolDetailRD.Name = couponTypeInfo[0].CouponTypeName + ",已飞入您的账户";
                                }
                                catch (Exception ex)
                                {
                                    setoffToolDetailRD.Name = "很遗憾此次优惠券" + couponTypeInfo[0].CouponTypeName + "的分享已失效,下次请及时领取.";
                                }
                            }
                        }
                        else
                        {
                            //如果剩余数量为0时,给出已领完提示
                            if (para.ShareVipId != null && para.ShareVipId != "")
                            {
                                setoffToolDetailRD.Name = "很遗憾您来迟一步优惠券" + couponTypeInfo[0].CouponTypeName + "已被领完.";
                                //throw new APIException("很遗憾您来迟一步券已被领完.") { ErrorCode = ERROR_LOAD_WRONG };
                            }
                        }
                        if (setoffToolDetailRD.Name == null || setoffToolDetailRD.Name == "")
                        {
                            setoffToolDetailRD.Name = couponTypeInfo[0].CouponTypeName;
                        }
                        setoffToolDetailRD.StartTime = couponTypeInfo[0].BeginTime == null?Convert.ToDateTime(couponTypeInfo[0].CreateTime).ToString("yyyy-MM-dd") : Convert.ToDateTime(couponTypeInfo[0].BeginTime).ToString("yyyy-MM-dd");

                        setoffToolDetailRD.EndTime     = couponTypeInfo[0].EndTime == null ? "" : Convert.ToDateTime(couponTypeInfo[0].EndTime).ToString("yyyy-MM-dd");
                        setoffToolDetailRD.ServiceLife = couponTypeInfo[0].ServiceLife.ToString();
                    }
                    #endregion
                    setoffToolDetailRD.ToolType = para.ToolType;                     //返回工具类别
                    setoffToolDetailRD.imageUrl = imageUrl;                          //返回临时二维码
                    setoffToolDetailRD.paraTemp = iResult.ToString().Insert(4, " "); //加空格,加空格有什么作用?
                }
                if (para.ToolType == "SetoffPoster")                                 //如果为集客海报则返回背景图和二维码
                {
                    if (SetOffPosterInfo != null && SetOffPosterInfo.Length > 0)
                    {
                        var backImgInfo = imgBll.QueryByEntity(new ObjectImagesEntity()
                        {
                            ImageId = SetOffPosterInfo[0].ImageId
                        }, null);
                        setoffToolDetailRD.ToolType   = para.ToolType;
                        setoffToolDetailRD.imageUrl   = imageUrl;
                        setoffToolDetailRD.paraTemp   = iResult.ToString().Insert(4, " "); //加空格,加空格有什么作用?
                        setoffToolDetailRD.backImgUrl = backImgInfo[0].ImageURL;
                        setoffToolDetailRD.Name       = SetOffPosterInfo[0].Name;
                    }
                }
                if (flag == 1)//当为1是需进行打开工具的记录
                {
                    var SetoffToolUserView = new SetoffToolUserViewEntity();
                    SetoffToolUserView.SetoffToolUserViewID = Guid.NewGuid();
                    SetoffToolUserView.SetoffEventID        = setoffEventInfo[0].SetoffEventID;
                    SetoffToolUserView.SetoffToolID         = new Guid(para.SetoffToolID);
                    SetoffToolUserView.ToolType             = para.ToolType;
                    SetoffToolUserView.ObjectId             = para.ObjectId;
                    SetoffToolUserView.NoticePlatformType   = 1;
                    SetoffToolUserView.UserID         = CurrentUserInfo.UserID;
                    SetoffToolUserView.IsOpen         = 1;
                    SetoffToolUserView.OpenTime       = System.DateTime.Now;
                    SetoffToolUserView.CustomerId     = customerId;
                    SetoffToolUserView.CreateTime     = System.DateTime.Now;
                    SetoffToolUserView.CreateBy       = CurrentUserInfo.UserID;
                    SetoffToolUserView.LastUpdateTime = System.DateTime.Now;
                    SetoffToolUserView.LastUpdateBy   = CurrentUserInfo.UserID;
                    SetoffToolUserView.IsDelete       = 0;
                    SetoffToolUserViewBLL.Create(SetoffToolUserView);
                }
            }
            catch (Exception ex)
            {
                throw new APIException(ex.Message)
                      {
                          ErrorCode = ERROR_CODES.DEFAULT_ERROR
                      };
            }
            return(setoffToolDetailRD);
        }
コード例 #35
0
        public async Task <bool> UpdateDatabase(string APIKey, string AcYear, string AcademyCode, int?LowestYear = null, int?HighestYear = null, int?ReportId = null, DateTime?Date = null)
        {
            for (int yearGroupInt = LowestYear.Value; yearGroupInt <= HighestYear.Value; yearGroupInt++)
            {
                string yearGroup;

                if (yearGroupInt == 0)
                {
                    yearGroup = "Reception";
                }
                else
                {
                    yearGroup = yearGroupInt.ToString();
                }

                try
                {
                    //Create datatable for prior attainment values.
                    var dtExamResults = new DataTable();
                    dtExamResults.Columns.Add("StudentId", typeof(String));
                    dtExamResults.Columns.Add("DataSet", typeof(String));
                    dtExamResults.Columns.Add("Academy", typeof(String));
                    dtExamResults.Columns.Add("NCYear", typeof(int));
                    dtExamResults.Columns.Add("ExamAcademicYear", typeof(String));
                    dtExamResults.Columns.Add("QAN", typeof(String));
                    dtExamResults.Columns.Add("QualificationTitle", typeof(String));
                    dtExamResults.Columns.Add("Grade", typeof(String));
                    dtExamResults.Columns.Add("KS123Literal", typeof(String));
                    dtExamResults.Columns.Add("SubjectId", typeof(String));

                    var colAdmissionDate = new DataColumn
                    {
                        DataType    = System.Type.GetType("System.DateTime"),
                        ColumnName  = "ExamDate",
                        AllowDBNull = true
                    };

                    dtExamResults.Columns.Add(colAdmissionDate);

                    //Get data from G4S API
                    APIRequest <GETExamResults, ExamResultDTO> getExamResults = new APIRequest <GETExamResults, ExamResultDTO>(_endPoint, APIKey, AcYear, yearGroup);
                    var examResultsDTO = getExamResults.ToList();


                    //Write the DTOs into the datatable.
                    foreach (var result in examResultsDTO)
                    {
                        //DateTime dateValue;

                        var row = dtExamResults.NewRow();

                        row["StudentId"]        = AcademyCode + AcYear + "-" + result.G4SStudentId;
                        row["DataSet"]          = AcYear;
                        row["Academy"]          = AcademyCode;
                        row["NCYear"]           = yearGroupInt;
                        row["ExamAcademicYear"] = result.ExamAcademicYear;
                        row["QAN"] = result.QAN;
                        row["QualificationTitle"] = result.QualificationTitle;
                        row["Grade"]        = result.Grade;
                        row["KS123Literal"] = result.KS123Literal;

                        if (result.G4SSubjectId != null)
                        {
                            row["SubjectId"] = AcademyCode + AcYear + "-" + result.G4SSubjectId;
                        }
                        else
                        {
                            row["SubjectId"] = null;
                        }


                        if (result.ExamDate != null)
                        {
                            row["ExamDate"] = result.ExamDate;
                        }
                        else
                        {
                            row["ExamDate"] = DBNull.Value;
                        }

                        dtExamResults.Rows.Add(row);
                    }

                    //Remove exisiting exam results from SQL database
                    var currentExamResults = _context.ExamResults.Where(i => i.DataSet == AcYear && i.Academy == AcademyCode && i.NCYear == yearGroupInt);
                    _context.ExamResults.RemoveRange(currentExamResults);
                    await _context.SaveChangesAsync();

                    //Write prior attainment data table to sql
                    using (var sqlBulk = new SqlBulkCopy(_connectionString))
                    {
                        sqlBulk.ColumnMappings.Add("StudentId", "StudentId");
                        sqlBulk.ColumnMappings.Add("DataSet", "DataSet");
                        sqlBulk.ColumnMappings.Add("Academy", "Academy");
                        sqlBulk.ColumnMappings.Add("NCYear", "NCYear");
                        sqlBulk.ColumnMappings.Add("ExamAcademicYear", "ExamAcademicYear");
                        sqlBulk.ColumnMappings.Add("ExamDate", "ExamDate");
                        sqlBulk.ColumnMappings.Add("QAN", "QAN");
                        sqlBulk.ColumnMappings.Add("QualificationTitle", "QualificationTitle");
                        sqlBulk.ColumnMappings.Add("Grade", "Grade");
                        sqlBulk.ColumnMappings.Add("KS123Literal", "KS123Literal");
                        sqlBulk.ColumnMappings.Add("SubjectId", "SubjectId");

                        sqlBulk.DestinationTableName = "g4s.ExamResults";
                        sqlBulk.WriteToServer(dtExamResults);
                    }

                    _context.SyncResults.Add(new SyncResult {
                        AcademyCode = AcademyCode, EndPoint = _endPoint, LoggedAt = DateTime.Now, Result = true, DataSet = AcYear, YearGroup = yearGroupInt
                    });
                    await _context.SaveChangesAsync();
                }
                catch (Exception e)
                {
                    if (e.InnerException != null)
                    {
                        _context.SyncResults.Add(new SyncResult {
                            AcademyCode = AcademyCode, DataSet = AcYear, EndPoint = _endPoint, Exception = e.Message, InnerException = e.InnerException.Message, LoggedAt = DateTime.Now, Result = false
                        });
                    }
                    else
                    {
                        _context.SyncResults.Add(new SyncResult {
                            AcademyCode = AcademyCode, DataSet = AcYear, EndPoint = _endPoint, Exception = e.Message, LoggedAt = DateTime.Now, Result = false
                        });
                    }

                    await _context.SaveChangesAsync();

                    return(false);
                }
            }
            return(true);
        }
コード例 #36
0
ファイル: APIClient.cs プロジェクト: elky84/unity-net-sample
 // 공용 에러처리
 public void commonOnError(APIRequest req)
 {
 }
コード例 #37
0
        protected override EmptyResponseData ProcessRequest(APIRequest <SetSuperRetailTraderItemInfoRP> pRequest)
        {
            SetSuperRetailTraderItemInfoRP rp = pRequest.Parameters;
            EmptyResponseData rd = new EmptyResponseData();

            var superRetailTraderItemMappingBll = new T_SuperRetailTraderItemMappingBLL(CurrentUserInfo);
            var superRetailTraderSkuMappingBll  = new T_SuperRetailTraderSkuMappingBLL(CurrentUserInfo);

            List <SuperRetailTraderItem> ItemIdList = rp.ItemList.GroupBy(n => new { n.ItemId }).Select(n => new SuperRetailTraderItem()
            {
                ItemId               = n.Key.ItemId,
                DistributerStock     = n.Sum(t => t.DistributerStock),
                DistributerCostPrice = n.Min(t => t.DistributerCostPrice)
            }).ToList();
            List <SuperRetailTraderItem> SkuIdList = rp.ItemList.Select(n => n).ToList();

            //修改商品成本价和库存
            foreach (var item in ItemIdList)
            {
                //获取商品信息
                var entity = superRetailTraderItemMappingBll.QueryByEntity(new T_SuperRetailTraderItemMappingEntity()
                {
                    ItemId = item.ItemId, CustomerID = CurrentUserInfo.ClientID
                }, null).FirstOrDefault();
                if (entity != null)
                {
                    if (entity.DistributerStock == 0 && entity.DistributerCostPrice == 0) //如果是初始化数据,直接修改
                    {
                        entity.DistributerStock     = item.DistributerStock;
                        entity.DistributerCostPrice = item.DistributerCostPrice;
                        superRetailTraderItemMappingBll.Update(entity);
                    }
                    else //如果是非初始化数据,创建新的,删除旧的
                    {
                        T_SuperRetailTraderItemMappingEntity newEntity = new T_SuperRetailTraderItemMappingEntity()
                        {
                            SuperRetailTraderItemMappingId = Guid.NewGuid(),
                            ItemId               = item.ItemId,
                            DistributerStock     = item.DistributerStock + entity.SalesQty,
                            SalesQty             = entity.SalesQty,
                            DistributerCostPrice = item.DistributerCostPrice,
                            DistributerPrice     = entity.DistributerPrice,
                            Status               = entity.Status,
                            OnShelfDatetime      = entity.OnShelfDatetime,
                            OffShelfDatetime     = entity.OffShelfDatetime,
                            CustomerID           = CurrentUserInfo.ClientID
                        };
                        superRetailTraderItemMappingBll.Delete(entity);
                        superRetailTraderItemMappingBll.Create(newEntity);
                    }
                }
            }
            //修改Sku成本价和库存
            foreach (var sku in SkuIdList)
            {
                var entity = superRetailTraderSkuMappingBll.QueryByEntity(new T_SuperRetailTraderSkuMappingEntity()
                {
                    SkuId = sku.SkuId, ItemId = sku.ItemId, CustomerID = CurrentUserInfo.ClientID
                }, null).FirstOrDefault();
                if (entity != null)
                {
                    if (entity.DistributerStock == 0 && entity.DistributerCostPrice == 0) //如果是初始化数据,直接修改
                    {
                        entity.DistributerStock     = sku.DistributerStock;
                        entity.DistributerCostPrice = sku.DistributerCostPrice;
                        superRetailTraderSkuMappingBll.Update(entity);
                    }
                    else //如果是非初始化数据,创建新的,删除旧的
                    {
                        T_SuperRetailTraderSkuMappingEntity newEntity = new T_SuperRetailTraderSkuMappingEntity()
                        {
                            SuperRetailTraderItemMappingId = entity.SuperRetailTraderItemMappingId,
                            ItemId               = entity.ItemId,
                            SkuId                = entity.SkuId,
                            DistributerStock     = sku.DistributerStock + entity.SalesQty,
                            SalesQty             = entity.SalesQty,
                            DistributerCostPrice = sku.DistributerCostPrice,
                            RefId                = entity.SuperRetailTraderItemMappingId,
                            Status               = entity.Status,
                            OnShelfDatetime      = entity.OnShelfDatetime,
                            OffShelfDatetime     = entity.OffShelfDatetime,
                            CustomerID           = CurrentUserInfo.ClientID
                        };
                        superRetailTraderSkuMappingBll.Delete(entity);
                        superRetailTraderSkuMappingBll.Create(newEntity);
                    }
                }
            }

            return(rd);
        }
コード例 #38
0
ファイル: APIClient.cs プロジェクト: elky84/unity-net-sample
 // Send packet
 public void SendPacket(APIRequest req, OnRecvHandler onRecvHandler, bool isLoadingIcon = false)
 {
     _onReceive = onRecvHandler;
     StartCoroutine(Send(req, OnOK, null));
 }
コード例 #39
0
ファイル: TeamDb.cs プロジェクト: mexaniksay/GamePro02
		public async Task AddTeamDotaToSQL(int id)
		{
		
			string url = 
				"https://api.steampowered.com/IDOTA2Match_570/GetTeamInfoByTeamID/v1/?key=6A9C411A88D047DA4C9E843EDF0B02F5&" +
				"format=json&language=en_us&start_at_team_id="+id+"&teams_requested=1";
			var ApiReq = new APIRequest ();
			//var PlayerReq = new Player ();
			var comm = new DBComm ();
			JToken temp = await ApiReq.FetchJsonAsync (url);
			//JObject jt = JObject.Parse (temp);
			string status = (string)temp.SelectToken("result.status");
			JToken teams = (JToken)temp.SelectToken("result.teams");
			if ((int)temp.SelectToken("result.teams[0].team_id")==id){
				JToken teamJS = teams[0];
					var newTeam = new Team ();
					newTeam.TeamId = (int)teamJS.SelectToken("team_id");
					newTeam.Name = (string)teamJS.SelectToken("name");
					newTeam.Tag = (string)teamJS.SelectToken("tag");
					newTeam.LogoUGCId = (string)teamJS.SelectToken("logo");
					newTeam.LogoByte = await GetTeamLogoAPI (newTeam.LogoUGCId);

					comm.Connect.Insert(newTeam);
					comm.Connect.Dispose ();
					/*
					for(int i=0;i<10;i++)
					{
						if ((teamJS.SelectToken("player_" + i + "_account_id"))!=null) {
							var newPlayer = new Player ();
							int playerId = (int)teamJS.SelectToken("player_" + i + "_account_id");
							newPlayer=await newPlayer.GetPlayerAPI (Convert.ToInt64(playerId), newTeam.TeamId);

							comm.Connect.Insert (newPlayer);
							

						} else {
							comm.Connect.Dispose ();
							break;
						}
					}*/
					System.Console.Out.WriteLine ("ID {0}", newTeam.ID);
			}
		}
コード例 #40
0
ファイル: APIClient.cs プロジェクト: elky84/unity-net-sample
    public IEnumerator Send(APIRequest req, OKHandler onOK, ErrorHandler onError = null)
    {
        bool queueing = true;

        if (!req.Validate(this))
        {
            req.error = new JsonError("ValidateError", "invalid request");
        }

        // wait until previous Send()
        float fElapsed = 0.0f;

        if (queueing)
        {
            while (isPending && fElapsed < req.timeout)
            {
                yield return(0);

                fElapsed += Time.deltaTime;
            }

            isPending = true;
        }

        string url = baseHost + req.uri;

        WWW www = null;

        bool   error     = false;
        string errorMsg  = "";
        string useragent = "";

        try
        {
            Dictionary <string, string> headers = new Dictionary <string, string>();

#if UNITY_ANDROID
            useragent = "light-elky/" + apiVersion + " gzip android";
#elif UNITY_IOS
            useragent = "light-elky/" + apiVersion + " gzip ios";
#else
            useragent = "light-elky/" + apiVersion + " gzip editor";
#endif

            headers["User-Agent"] = useragent;

            if (isAuthorized)
            {
                headers["COOKIE"] = cookie;
            }
            else
            {
                Log("  cookie: not found");
            }

            // zlib encoded
            string json       = JsonConvert.SerializeObject(req.param);
            byte[] compressed = Ionic.Zlib.GZipStream.CompressString(json);
            //headers["Accept-Encoding"] = "gzip";
            headers["Content-Type"]     = "application/json";
            headers["Content-Encoding"] = "gzip";
            www = new WWW(url, compressed, headers);             // POST only
            var strBase64 = System.Convert.ToBase64String(compressed);
            Log(strBase64);

            www.threadPriority = ThreadPriority.High;

            Log("  http request sent...");
        }
        catch (System.Exception ex)
        {
            error    = true;
            errorMsg = ex.ToString();
            LogWarning(errorMsg);
            LogError(req.uri + ":" + errorMsg);
        }

        // wait for http request
        if (!error)
        {
            while (!www.isDone && www.error == null && fElapsed < req.timeout)
            {
                yield return(0);

                fElapsed += Time.deltaTime;
            }
        }

        if (queueing)
        {
            isPending = false;
            isHandled = false;
        }

        if (error)
        {
            // handle below
            www.Dispose();
            www = null;
        }
        else if (fElapsed >= req.timeout)
        {
            www       = null;
            req.error = new JsonError("TimeoutError", fElapsed.ToString());
        }
        else if (null != www.error)
        {
            req.error = new JsonError("HttpError", www.error);
            Log(www.error);
        }
        else
        {
            try
            {
                foreach (KeyValuePair <string, string> kv in www.responseHeaders)
                {
                    Log("***** [" + kv.Key + "]" + kv.Value);
                }

                // gzip check
                string text = "";
                string contentEncoding;
                www.responseHeaders.TryGetValue("Content-Encoding", out contentEncoding);
                if (string.IsNullOrEmpty(contentEncoding))
                {
                    www.responseHeaders.TryGetValue("CONTENT-ENCODING", out contentEncoding);
                }

                if (contentEncoding == "gzip")
                {
#if UNITY_EDITOR_OSX || UNITY_IOS
                    text = www.text;
#else
                    Log("[gzip] " + www.size + "bytes");
                    Debug.LogWarning("[gzip] " + www.size + "bytes");
                    byte[] decompressed = Ionic.Zlib.GZipStream.UncompressBuffer(www.bytes);
                    text = System.Text.UTF8Encoding.UTF8.GetString(decompressed);
#endif
                }
                else if (contentEncoding == "bson")
                {
                    Log("[bson] " + www.size + "bytes");
                    Debug.LogWarning("[bson] " + www.size + "bytes");

                    MemoryStream ms = new MemoryStream(www.bytes);
                    using (BsonReader reader = new BsonReader(ms))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        object         obj        = serializer.Deserialize(reader);
                        text = obj.ToString();
                    }
                }
                else
                {
                    Debug.LogWarning("[text] " + www.size + "bytes");
                    text = www.text;
                }

                // cookie check
                string setCookie;                 // responseHeaders only have single header, until now
                bool   cookieFound = false;
                www.responseHeaders.TryGetValue("Set-Cookie", out setCookie);
                if (string.IsNullOrEmpty(setCookie))
                {
                    www.responseHeaders.TryGetValue("SET-COOKIE", out setCookie);
                }
                if (setCookie != null && setCookie.Length > 0)
                {
                    string rawCookie  = setCookie.Split(';')[0];
                    string cookieName = rawCookie.Split('=')[0]; // not to remove "
                    cookies_[cookieName] = rawCookie;
                    cookieFound          = true;
                }
                if (cookieFound)
                {
                    foreach (KeyValuePair <string, string> kv in cookies_)
                    {
                        Log("  cookie: " + kv.Value);
                    }
                }
                else if (isAuthorized)
                {
                    Log("  cookie not found from response but authorized.");
                }
                else
                {
                    Log("  cookie not found from response.");
                }

                req.responseText = text;

                // json check
                string contentType;
                bool   isJson = false;
                if (www.responseHeaders.TryGetValue("Content-Type", out contentType))
                {
                    if (contentType.Contains("json"))
                    {
                        isJson = true;
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(text) &&
                        (text[0] == '{' && text[text.Length - 1] == '}' ||
                         text[0] == '[' && text[text.Length - 1] == ']'))
                    {
                        isJson = true;
                    }
                }

                if (isJson)
                {
                    Log("json response. try to parse json...");
                    try
                    {
                        Log(text);
                        {
                            // try parse Response
                            req.Parse(text);
                        }
                    }
                    catch (Exception ex)
                    {
                        req.error = new JsonError("ParseError", ex.ToString());
                        Debug.LogError(ex);
                    }
                }
                else
                {
                    Log("non-json response. skip parsing...");
                }
            }
            catch (Exception ex)
            {
                error    = true;
                errorMsg = ex.ToString();
                LogWarning(errorMsg);
                Debug.LogError(ex);
            }
        }

        if (error)
        {
            req.error = new JsonError("ExceptionError", errorMsg);
        }

        if (req.error == null)
        {
            yield return(StartCoroutine(req.HandleResponse(this)));

            if (req.error == null && onOK != null)
            { // HandleResponse can throw error!
                yield return(StartCoroutine(onOK(req, this)));
            }
        }

        if (req.error != null)
        { // OK handler can throw error.
            yield return(StartCoroutine(req.HandleError(this)));

            if (onError != null)
            {
                yield return(StartCoroutine(onError(req, this)));
            }
            commonOnError(req);
            yield return(0);
        }

        if (queueing)
        {
            isHandled = true;
        }

        yield break;
    }
コード例 #41
0
        /// <summary>
        /// Handles an API request, while also updating the local state to match
        /// how the server would eventually respond and update an <see cref="RoomManager"/>.
        /// </summary>
        /// <param name="request">The API request to handle.</param>
        /// <param name="localUser">The local user to store in responses where required.</param>
        /// <param name="game">The game base for cases where actual online requests need to be sent.</param>
        /// <returns>Whether the request was successfully handled.</returns>
        public bool HandleRequest(APIRequest request, APIUser localUser, OsuGameBase game)
        {
            switch (request)
            {
            case CreateRoomRequest createRoomRequest:
                var apiRoom = new Room();

                apiRoom.CopyFrom(createRoomRequest.Room);

                // Passwords are explicitly not copied between rooms.
                apiRoom.HasPassword.Value = !string.IsNullOrEmpty(createRoomRequest.Room.Password.Value);
                apiRoom.Password.Value    = createRoomRequest.Room.Password.Value;

                AddServerSideRoom(apiRoom, localUser);

                var responseRoom = new APICreatedRoom();
                responseRoom.CopyFrom(createResponseRoom(apiRoom, false));

                createRoomRequest.TriggerSuccess(responseRoom);
                return(true);

            case JoinRoomRequest joinRoomRequest:
            {
                var room = ServerSideRooms.Single(r => r.RoomID.Value == joinRoomRequest.Room.RoomID.Value);

                if (joinRoomRequest.Password != room.Password.Value)
                {
                    joinRoomRequest.TriggerFailure(new InvalidOperationException("Invalid password."));
                    return(true);
                }

                joinRoomRequest.TriggerSuccess();
                return(true);
            }

            case PartRoomRequest partRoomRequest:
                partRoomRequest.TriggerSuccess();
                return(true);

            case GetRoomsRequest getRoomsRequest:
                var roomsWithoutParticipants = new List <Room>();

                foreach (var r in ServerSideRooms)
                {
                    roomsWithoutParticipants.Add(createResponseRoom(r, false));
                }

                getRoomsRequest.TriggerSuccess(roomsWithoutParticipants);
                return(true);

            case GetRoomRequest getRoomRequest:
                getRoomRequest.TriggerSuccess(createResponseRoom(ServerSideRooms.Single(r => r.RoomID.Value == getRoomRequest.RoomId), true));
                return(true);

            case GetBeatmapSetRequest getBeatmapSetRequest:
                var onlineReq = new GetBeatmapSetRequest(getBeatmapSetRequest.ID, getBeatmapSetRequest.Type);
                onlineReq.Success += res => getBeatmapSetRequest.TriggerSuccess(res);
                onlineReq.Failure += e => getBeatmapSetRequest.TriggerFailure(e);

                // Get the online API from the game's dependencies.
                game.Dependencies.Get <IAPIProvider>().Queue(onlineReq);
                return(true);

            case CreateRoomScoreRequest createRoomScoreRequest:
                createRoomScoreRequest.TriggerSuccess(new APIScoreToken {
                    ID = 1
                });
                return(true);

            case SubmitRoomScoreRequest submitRoomScoreRequest:
                submitRoomScoreRequest.TriggerSuccess(new MultiplayerScore
                {
                    ID         = currentScoreId++,
                    Accuracy   = 1,
                    EndedAt    = DateTimeOffset.Now,
                    Passed     = true,
                    Rank       = ScoreRank.S,
                    MaxCombo   = 1000,
                    TotalScore = 1000000,
                    User       = localUser,
                    Statistics = new Dictionary <HitResult, int>()
                });
                return(true);
            }

            return(false);
        }
コード例 #42
0
        protected override GetSetoffToolsRD ProcessRequest(APIRequest <GetSetoffToolsRP> pRequest)
        {
            SetoffToolsBLL    setOffToolsBLL   = new SetoffToolsBLL(CurrentUserInfo);
            IincentiveRuleBLL incentiveRuleBLL = new IincentiveRuleBLL(CurrentUserInfo);
            var para = pRequest.Parameters;
            var setoffToolsEntity = new SetoffToolsEntity();

            if (para.ToolsType != null)
            {
                setoffToolsEntity.ToolType = para.ToolsType.ToString();
            }
            GetSetoffToolsRD setoffToolsRD = new GetSetoffToolsRD();
            var setoffEventBLL             = new SetoffEventBLL(CurrentUserInfo);
            //获取集客活动信息
            string NoticePlatType = string.Empty;

            if (string.IsNullOrEmpty(para.ApplicationType))
            {
                para.ApplicationType = "0";
            }
            else
            {
                switch (para.ApplicationType)
                {
                case "1":
                    NoticePlatType = "1";
                    break;

                case "2":
                    NoticePlatType = "2";
                    break;

                case "3":
                    NoticePlatType = "2";    //传3需要进行平台类型处理 等于3时获取员工集客行动平台
                    break;

                case "4":
                    NoticePlatType = "3";    //传4需要进行平台类型处理 等于4时获取超级分销商推广行动平台
                    break;
                }
            }
            var setOffEventInfo = setoffEventBLL.QueryByEntity(new SetoffEventEntity()
            {
                Status = "10", IsDelete = 0, SetoffType = Convert.ToInt32(NoticePlatType), CustomerId = CurrentUserInfo.CurrentUser.customer_id
            }, null);
            int     SetoffToolsTotalCount = 0;
            DataSet SetoffToolsList       = null;

            if (setOffEventInfo.Length != 0)
            {
                //获取集客活动工具数量
                SetoffToolsTotalCount = setOffToolsBLL.GeSetoffToolsListCount(setoffToolsEntity, para.ApplicationType, para.BeShareVipID, setOffEventInfo[0].SetoffEventID.ToString());
                //获取集客活动工具列表
                SetoffToolsList = setOffToolsBLL.GetSetoffToolsList(setoffToolsEntity, para.ApplicationType, para.BeShareVipID, para.PageIndex, para.PageSize, setOffEventInfo[0].SetoffEventID.ToString());
            }

            //获取集客奖励信息
            var IncentiveRule = incentiveRuleBLL.GetIncentiveRule(para.ApplicationType);

            setoffToolsRD.TotalCount = SetoffToolsTotalCount;
            int remainder = 0;

            if (para.PageSize == 0)
            {
                para.PageSize = 10;
            }
            setoffToolsRD.TotalPageCount = Math.DivRem(SetoffToolsTotalCount, para.PageSize, out remainder);
            if (remainder > 0)
            {
                setoffToolsRD.TotalPageCount++;
            }
            string strHost = ConfigurationManager.AppSettings["website_url"].Trim();

            if (SetoffToolsList != null && SetoffToolsList.Tables[0].Rows.Count > 0)
            {
                //为优惠券和海报添加图片路径
                SetoffToolsList.Tables[0].Columns.Add("ImageUrl", typeof(string));
                var CustomerBasicSettingBLL = new CustomerBasicSettingBLL(CurrentUserInfo);
                var CustomerBasicInfo       = CustomerBasicSettingBLL.QueryByEntity(new CustomerBasicSettingEntity()
                {
                    CustomerID = CurrentUserInfo.CurrentUser.customer_id, SettingCode = "SetoffPosterWeChatDefaultPhoto"
                }, null).FirstOrDefault();
                var    setOffPosterBLL  = new SetoffPosterBLL(CurrentUserInfo);
                var    ObjectImagesBLL  = new ObjectImagesBLL(CurrentUserInfo);
                var    T_CTW_LEventBLL  = new T_CTW_LEventBLL(CurrentUserInfo);
                var    wMaterialTextBLL = new WMaterialTextBLL(CurrentUserInfo);
                string SourceId         = string.Empty;
                if (!string.IsNullOrEmpty(para.ApplicationType))
                {
                    switch (para.ApplicationType)
                    {
                    case "1":
                        SourceId = "3";    //会员集客
                        break;

                    case "2":
                        SourceId = "1";    //APP会员服务;
                        break;

                    case "3":
                        SourceId = "3";    //APP会员服务;
                        break;

                    case "4":
                        SourceId = "4";    //超级分销商;
                        break;
                    }
                }
                string goUrl       = string.Empty;
                string goCouponUrl = strHost + "/HtmlApps/html/common/GatheringClient/Coupon.html?customerId=";                           //拼优惠券详细页面
                string goPosterUrl = strHost + "/HtmlApps/html/common/GatheringClient/poster.html?customerId=";                           //拼海报详细页面
                string strOAuthUrl = strHost + "/WXOAuth/AuthUniversal.aspx?scope=snsapi_userinfo&SourceId=" + SourceId + "&customerId="; //拼OAuth认证
                foreach (DataRow dr in SetoffToolsList.Tables[0].Rows)
                {
                    if (dr["ToolType"].ToString() == "Coupon")
                    {
                        if (CustomerBasicInfo != null)
                        {
                            dr["ImageUrl"] = CustomerBasicInfo.SettingValue;
                        }
                        if (para.ApplicationType == "4")
                        {
                            goUrl     = goCouponUrl + CurrentUserInfo.CurrentUser.customer_id + "&pushType=IsSuperRetail&ShareVipId=" + CurrentUserInfo.UserID + "&couponId=" + dr["ObjectId"] + "&version=";
                            dr["URL"] = strOAuthUrl + CurrentUserInfo.CurrentUser.customer_id + "&objectType=Coupon&ObjectID=" + dr["ObjectId"] + "&ShareVipID=" + CurrentUserInfo.UserID + "&goUrl=" + System.Web.HttpUtility.UrlEncode(goUrl);
                        }
                        else
                        {
                            //Oauth认证加商品详情页
                            goUrl     = goCouponUrl + CurrentUserInfo.CurrentUser.customer_id + "&ShareVipId=" + CurrentUserInfo.UserID + "&couponId=" + dr["ObjectId"] + "&version=";
                            dr["URL"] = strOAuthUrl + CurrentUserInfo.CurrentUser.customer_id + "&ShareVipID=" + CurrentUserInfo.UserID + "&goUrl=" + System.Web.HttpUtility.UrlEncode(goUrl);
                        }
                    }
                    if (dr["ToolType"].ToString() == "SetoffPoster")
                    {
                        var setOffPosterInfo = setOffPosterBLL.QueryByEntity(new SetoffPosterEntity()
                        {
                            SetoffPosterID = new Guid(dr["ObjectId"].ToString())
                        }, null).FirstOrDefault();
                        if (setOffPosterInfo != null)
                        {
                            var ObjectImgsInfo = ObjectImagesBLL.QueryByEntity(new ObjectImagesEntity()
                            {
                                ImageId = setOffPosterInfo.ImageId
                            }, null).FirstOrDefault();
                            if (ObjectImgsInfo != null)
                            {
                                dr["ImageUrl"] = ObjectImgsInfo.ImageURL;
                            }
                        }
                        if (para.ApplicationType == "4")
                        {
                            goUrl     = goPosterUrl + CurrentUserInfo.CurrentUser.customer_id + "&pushType=IsSuperRetail&ShareVipId=" + CurrentUserInfo.UserID + "&ObjectId=" + dr["ObjectId"] + "&version=";
                            dr["URL"] = strOAuthUrl + CurrentUserInfo.CurrentUser.customer_id + "&objectType=SetoffPoster&ObjectID=" + dr["ObjectId"] + "&ShareVipID=" + CurrentUserInfo.UserID + "&goUrl=" + System.Web.HttpUtility.UrlEncode(goUrl);
                        }
                        else
                        {
                            //Oauth认证加海报详情页
                            goUrl     = goPosterUrl + CurrentUserInfo.CurrentUser.customer_id + "&ShareVipId=" + CurrentUserInfo.UserID + "&ObjectId=" + dr["ObjectId"] + "&version=";
                            dr["URL"] = strOAuthUrl + CurrentUserInfo.CurrentUser.customer_id + "&ShareVipID=" + CurrentUserInfo.UserID + "&goUrl=" + System.Web.HttpUtility.UrlEncode(goUrl);
                        }
                    }
                    if (dr["ToolType"].ToString() == "CTW")
                    {
                        var T_CTW_LEventInfo = T_CTW_LEventBLL.QueryByEntity(new T_CTW_LEventEntity()
                        {
                            CTWEventId = new Guid(dr["ObjectId"].ToString())
                        }, null).FirstOrDefault();
                        if (T_CTW_LEventInfo != null)
                        {
                            dr["ImageUrl"] = T_CTW_LEventInfo.ImageURL;
                        }
                        if (para.ApplicationType == "4")
                        {
                            goUrl     = dr["URL"].ToString() + "&pushType=IsSuperRetail&ShareVipId=" + CurrentUserInfo.UserID + "&ObjectId=" + dr["ObjectId"] + "&version=";
                            dr["URL"] = strOAuthUrl + CurrentUserInfo.CurrentUser.customer_id + "&objectType=CTW&ObjectID=" + dr["ObjectId"] + "&ShareVipID=" + CurrentUserInfo.UserID + "&goUrl=" + System.Web.HttpUtility.UrlEncode(goUrl);
                        }
                        else
                        {
                            goUrl     = dr["URL"].ToString() + "&ShareVipId=" + CurrentUserInfo.UserID + "&ObjectId=" + dr["ObjectId"] + "&version=";
                            dr["URL"] = strOAuthUrl + CurrentUserInfo.CurrentUser.customer_id + "&ShareVipID=" + CurrentUserInfo.UserID + "&goUrl=" + System.Web.HttpUtility.UrlEncode(goUrl);
                        }
                    }
                    if (dr["ToolType"].ToString() == "Material")//如果是图文素材
                    {
                        var wMaterialTextInfo = wMaterialTextBLL.QueryByEntity(new WMaterialTextEntity()
                        {
                            TextId = dr["ObjectId"].ToString()
                        }, null).FirstOrDefault();
                        if (wMaterialTextInfo != null)
                        {
                            dr["ImageUrl"] = wMaterialTextInfo.CoverImageUrl;
                        }
                        goUrl     = dr["URL"].ToString();
                        dr["URL"] = strOAuthUrl + CurrentUserInfo.CurrentUser.customer_id + "&objectType=Material&ObjectID=" + dr["ObjectId"] + "&ShareVipID=" + CurrentUserInfo.UserID + "&goUrl=" + System.Web.HttpUtility.UrlEncode(goUrl);
                    }
                }
                setoffToolsRD.SetOffToolsList = DataTableToObject.ConvertToList <SetOffToolsInfo>(SetoffToolsList.Tables[0]);
            }
            if (IncentiveRule != null && IncentiveRule.Tables[0].Rows.Count > 0)
            {
                setoffToolsRD.SetoffRegAwardType = Convert.ToInt32(IncentiveRule.Tables[0].Rows[0]["SetoffRegAwardType"].ToString()); //激励类型
                setoffToolsRD.SetoffRegPrize     = IncentiveRule.Tables[0].Rows[0]["SetoffRegPrize"].ToString();                      //激励值
                setoffToolsRD.SetoffOrderPer     = Convert.ToDecimal(IncentiveRule.Tables[0].Rows[0]["SetoffOrderPer"].ToString());   //订单成交提成比例
            }
            return(setoffToolsRD);
        }
コード例 #43
0
ファイル: TeamDb.cs プロジェクト: mexaniksay/GamePro02
		public async Task<Team> AddTeam(int id,string gameName)
		{
			string url = SettingsDB.ServerAPIAddress + gameName + "/GetTeam?team_id=" + id;
			var ApiReq = new APIRequest ();
			//var PlayerReq = new Player ();
			var comm = new DBComm (gameName);
			JToken temp = await ApiReq.GetJsonAsync (url);
			var team = JsonConvert.DeserializeObject<Team> (temp.ToString ());
			if (temp.ToString () != "") {
				comm.Connect.Insert (team);
				comm.Connect.Dispose ();
			}
			return team;


		}
コード例 #44
0
        protected override EmptyResponseData ProcessRequest(APIRequest <UpdateVipCardTypeRP> pRequest)
        {
            var rd   = new EmptyResponseData();
            var para = pRequest.Parameters;
            LoggingSessionInfo loggingSessionInfo = Default.GetBSLoggingSession(pRequest.CustomerID, pRequest.UserID);
            var bllVip = new VipBLL(loggingSessionInfo);
            var bllVipCardVipMapping = new VipCardVipMappingBLL(loggingSessionInfo);
            //获取当前会员信息
            List <IWhereCondition> wheres = new List <IWhereCondition>();

            wheres.Add(new EqualsCondition()
            {
                FieldName = "clientid", Value = pRequest.CustomerID
            });
            wheres.Add(new EqualsCondition()
            {
                FieldName = "VipID", Value = pRequest.UserID
            });
            wheres.Add(new EqualsCondition()
            {
                FieldName = "Status", Value = 2
            });
            wheres.Add(new DirectCondition("Phone!=''"));
            var vipInfo = bllVip.Query(wheres.ToArray(), null).FirstOrDefault();

            try
            {
                string strObjectNo = string.Empty;
                if (vipInfo != null)
                {
                    //根据当前会员执行变更卡操作
                    strObjectNo = bllVipCardVipMapping.BindVirtualItem(vipInfo.VIPID, vipInfo.VipCode, vipInfo.CouponInfo, para.VipCardTypeID);
                    if (string.IsNullOrEmpty(strObjectNo))
                    {
                        throw new APIException("绑定失败!")
                              {
                                  ErrorCode = ERROR_CODES.INVALID_BUSINESS
                              };
                    }
                    else
                    {
                        //同步相关会员信息(姓名、性别、生日、邮箱、积分、消费金额、消费次数、状态)
                        bllVip.MergeVipInfo(pRequest.CustomerID, pRequest.UserID, vipInfo.Phone, para.BindVipID);
                        //记录会员信息改变,并且把旧的会员的标识也放在契约里
                        var eventService = new EventService();
                        var vipMsg       = new EventContract
                        {
                            Operation  = OptEnum.Update,
                            EntityType = EntityTypeEnum.Vip,
                            Id         = pRequest.UserID,
                            OtherCon   = para.BindVipID
                        };
                        eventService.PublishMsg(vipMsg);

                        throw new APIException("绑定成功!")
                              {
                                  ErrorCode = 0
                              };
                    }
                }
            }
            catch (APIException ex) { throw ex; }
            return(rd);
        }
コード例 #45
0
ファイル: Payment.cs プロジェクト: venugec/codekit-csharp
                /// <summary>
                /// This function makes API call to Get Subscription detail
                /// </summary>
                /// <param name="MerchantSubscriptionId">MerchantSubscriptionId</param>
                /// <param name="ConsumerId">ConsumerId</param>
                public SubscriptionDetailResponseObj.RootObject getSubscriptionDetail(string MerchantSubscriptionId, string ConsumerId)
                {
                    APIRequest apiRequest = new APIRequest("Subscriptions/" + MerchantSubscriptionId + "/Detail/" + ConsumerId);

                    if (apiService.get(apiRequest))
                    {
                        SubscriptionDetailResponseObj responseObj = new SubscriptionDetailResponseObj();
                        return responseObj.deserializeSubscriptionDetailResponse(apiService.apiResponse.getResponseData());
                    }

                    throw new Exception(apiService.errorResponse);
                }
コード例 #46
0
        protected override GetScoreRecoveryInformationListRD ProcessRequest(APIRequest <GetQuestionListRP> pRequest)
        {
            var rd   = new GetScoreRecoveryInformationListRD();
            var para = pRequest.Parameters;
            var loggingSessionInfo = new SessionManager().CurrentUserLoginInfo;

            var ScoreRecoveryInformationBLL = new T_QN_ScoreRecoveryInformationBLL(loggingSessionInfo);


            #region 条件参数

            List <IWhereCondition> complexCondition = new List <IWhereCondition>();
            complexCondition.Add(new EqualsCondition()
            {
                FieldName = "CustomerID", Value = loggingSessionInfo.ClientID
            });
            if (!string.IsNullOrEmpty(para.QuestionnaireID))
            {
                complexCondition.Add(new EqualsCondition()
                {
                    FieldName = "QuestionnaireID", Value = para.QuestionnaireID
                });
            }


            #endregion

            #region 排序参数

            List <OrderBy> lstOrder = new List <OrderBy> {
            };
            lstOrder.Add(new OrderBy()
            {
                FieldName = "CreateTime", Direction = OrderByDirections.Desc
            });

            #endregion

            #region 获取数据集

            var tempList = ScoreRecoveryInformationBLL.PagedQuery(complexCondition.ToArray(), lstOrder.ToArray(), para.PageSize, para.PageIndex);
            rd.TotalPageCount = tempList.PageCount;
            rd.TotalCount     = tempList.RowCount;

            rd.ScoreRecoveryInformationList = tempList.Entities.Select(t => new DTO.Module.Questionnaire.Response.ScoreRecoveryInformation()
            {
                QuestionnaireID            = t.QuestionnaireID.ToString(),
                MaxScore                   = t.MaxScore.Value,
                MinScore                   = t.MinScore.Value,
                RecoveryContent            = t.RecoveryContent,
                RecoveryImg                = t.RecoveryImg,
                RecoveryType               = t.RecoveryType.Value,
                ScoreRecoveryInformationID = t.ScoreRecoveryInformationID.Value.ToString(),
                Status = t.Status.Value
            }).ToList();



            #endregion

            return(rd);
        }
コード例 #47
0
ファイル: Payment.cs プロジェクト: venugec/codekit-csharp
                /// <summary>
                /// This function makes API call to Get Transaction Status
                /// </summary>
                /// <param name="idType">idType</param>
                /// <param name="id">id</param>
                public RefundTransactionResponseObj.RootObject RefundTransaction(string refundObjJSON, string TransactionId)
                {
                    APIRequest apiRequest = new APIRequest("Transactions/" + TransactionId + "?Action=refund");

                    apiRequest.setBinaryData(refundObjJSON);

                    if (apiService.put(apiRequest))
                    {
                        RefundTransactionResponseObj responseObj = new RefundTransactionResponseObj();
                        return responseObj.deserializeRefundTransactionResponse(apiService.apiResponse.getResponseData());
                    }

                    throw new Exception(apiService.errorResponse);
                }
コード例 #48
0
        protected override SetQuestionnaireRD ProcessRequest(APIRequest <SetQuestionnaireRP> pRequest)
        {
            var rd   = new SetQuestionnaireRD();
            var para = pRequest.Parameters;
            var loggingSessionInfo = new SessionManager().CurrentUserLoginInfo;
            T_QN_QuestionnaireEntity model_QuestionnaireEntity = null;


            var QuestionBLL = new T_QN_QuestionBLL(loggingSessionInfo);
            var QuestionNaireQuestionMappingBLL = new T_QN_QuestionNaireQuestionMappingBLL(loggingSessionInfo);
            var OptionBLL = new T_QN_OptionBLL(loggingSessionInfo);

            var QuestionPicBLL = new T_QN_QuestionPicBLL(loggingSessionInfo);

            if (para != null)
            {
                #region 问卷编辑

                Guid?tempguid = null;
                if (para.QuestionnaireID != "")
                {
                    tempguid = new System.Guid(para.QuestionnaireID);
                }
                model_QuestionnaireEntity = new T_QN_QuestionnaireEntity
                {
                    BGImageSrc            = para.BGImageSrc,
                    QuestionnaireID       = tempguid,
                    ButtonName            = para.ButtonName,
                    CustomerID            = loggingSessionInfo.ClientID,
                    IsShowQRegular        = para.IsShowQRegular,
                    ModelType             = para.ModelType,
                    QRegular              = para.QRegular,
                    QResultBGColor        = para.QResultBGColor,
                    QResultBGImg          = para.QResultBGImg,
                    QResultBtnTextColor   = para.QResultBtnTextColor,
                    QResultImg            = para.QResultImg,
                    QResultTitle          = para.QResultTitle,
                    QuestionnaireName     = para.QuestionnaireName,
                    QuestionnaireType     = para.QuestionnaireType,
                    StartPageBtnBGColor   = para.StartPageBtnBGColor,
                    StartPageBtnTextColor = para.StartPageBtnTextColor,
                    Sort   = 999,
                    Status = 1
                };

                var QuestionnaireBLL = new T_QN_QuestionnaireBLL(loggingSessionInfo);

                if (para.QuestionnaireID != null && para.QuestionnaireID != "")
                {
                    QuestionnaireBLL.Update(model_QuestionnaireEntity);
                }
                else
                {
                    QuestionnaireBLL.Create(model_QuestionnaireEntity);
                }

                #endregion

                rd.QuestionnaireID = model_QuestionnaireEntity.QuestionnaireID;


                if (para.step == 3 || para.step == 4)
                {
                    #region 问卷题目删除
                    if (para.step == 3 && para.QuestionDelDatalist != null)
                    {
                        object[] dels = new object[para.QuestionDelDatalist.Count];
                        for (int j = 0; j < para.QuestionDelDatalist.Count; j++)
                        {
                            dels[j] = para.QuestionDelDatalist[j].Questionid;
                        }

                        QuestionBLL.Delete(dels);
                    }
                    #endregion

                    #region 问卷题目编辑
                    if (para.Questiondatalist != null)
                    {
                        for (int i = 0; i < para.Questiondatalist.Count; i++)
                        {
                            Question            ques           = para.Questiondatalist[i];
                            T_QN_QuestionEntity QuestionEntity = new T_QN_QuestionEntity();

                            T_QN_QuestionPicEntity QuestionPicEntity = new T_QN_QuestionPicEntity();


                            if (para.step == 3)
                            {
                                QuestionEntity.CustomerID          = loggingSessionInfo.ClientID;
                                QuestionEntity.DefaultValue        = getValue(ques.DefaultValue);
                                QuestionEntity.Isphone             = getValue(ques.Isphone);
                                QuestionEntity.IsRequired          = getValue(ques.IsRequired);
                                QuestionEntity.IsShowAddress       = getValue(ques.IsShowAddress);
                                QuestionEntity.IsShowCity          = getValue(ques.IsShowCity);
                                QuestionEntity.IsShowCounty        = getValue(ques.IsShowCounty);
                                QuestionEntity.IsShowProvince      = getValue(ques.IsShowProvince);
                                QuestionEntity.IsValidateEndDate   = getValue(ques.IsValidateEndDate);
                                QuestionEntity.IsValidateMaxChar   = getValue(ques.IsValidateMaxChar);
                                QuestionEntity.IsValidateMinChar   = getValue(ques.IsValidateMinChar);
                                QuestionEntity.IsValidateStartDate = getValue(ques.IsValidateStartDate);
                                QuestionEntity.MaxChar             = getValue(ques.MaxChar);
                                QuestionEntity.MinChar             = getValue(ques.MinChar);
                                QuestionEntity.Name           = getValue(ques.Name);
                                QuestionEntity.NoRepeat       = getValue(ques.NoRepeat);
                                QuestionEntity.Questionid     = getValue(ques.Questionid);
                                QuestionEntity.QuestionidType = getValue(ques.QuestionidType);
                                QuestionEntity.StartDate      = getValue(ques.StartDate);
                                QuestionEntity.EndDate        = getValue(ques.EndDate);
                                QuestionEntity.Sort           = i + 1;
                                QuestionEntity.Status         = getValue(ques.Status);
                            }

                            if (para.step == 4)
                            {
                                QuestionEntity.Questionid = getValue(ques.Questionid);
                                QuestionEntity.ScoreStyle = getValue(ques.ScoreStyle);

                                if (QuestionEntity.ScoreStyle == 3)
                                {
                                    QuestionEntity.MaxScore = getValue(ques.MaxScore);
                                    QuestionEntity.MinScore = getValue(ques.MinScore);
                                }
                            }

                            if (QuestionEntity.Questionid == null || QuestionEntity.Questionid.Value.ToString() == "")
                            {
                                QuestionEntity.ScoreStyle = 1;
                                QuestionBLL.Create(QuestionEntity);
                            }
                            else
                            {
                                QuestionBLL.Update(QuestionEntity, false);
                            }

                            #region 题目图片编辑

                            if (para.step == 3)
                            {
                                QuestionPicEntity.Src        = getValue(ques.Src);
                                QuestionPicEntity.QuestionID = QuestionEntity.Questionid.Value.ToString();
                                QuestionPicEntity.CustomerID = QuestionEntity.CustomerID;
                                Guid?tempguid1 = null;
                                if (ques.QuestionPicID != "")
                                {
                                    tempguid1 = new System.Guid(ques.QuestionPicID);
                                }
                                QuestionPicEntity.QuestionPicID = tempguid1;
                                if (ques.QuestionPicID != null && ques.QuestionPicID != "")
                                {
                                    QuestionPicBLL.Update(QuestionPicEntity);
                                }
                                else
                                {
                                    QuestionPicBLL.Create(QuestionPicEntity);
                                }
                            }
                            #endregion


                            if (ques.Optionlist != null)
                            {
                                #region  项编辑
                                for (int j = 0; j < ques.Optionlist.Count; j++)
                                {
                                    Option            opt          = ques.Optionlist[j];
                                    T_QN_OptionEntity OptionEntity = new T_QN_OptionEntity();


                                    if (para.step == 3)
                                    {
                                        OptionEntity.CustomerID     = loggingSessionInfo.ClientID;
                                        OptionEntity.OptionContent  = getValue(opt.OptionContent);
                                        OptionEntity.OptionPicSrc   = getValue(opt.OptionPicSrc);
                                        OptionEntity.QuestionID     = getValue(QuestionEntity.Questionid.ToString());
                                        OptionEntity.QuestionidType = getValue(QuestionEntity.QuestionidType);
                                        OptionEntity.Sort           = j + 1;
                                        OptionEntity.OptionID       = getValue(opt.OptionID);
                                        OptionEntity.Status         = getValue(opt.Status);
                                    }

                                    if (para.step == 4)
                                    {
                                        OptionEntity.IsRightValue   = getValue(opt.IsRightValue);
                                        OptionEntity.NoOptionScore  = getValue(opt.NoOptionScore);
                                        OptionEntity.OptionID       = getValue(opt.OptionID);
                                        OptionEntity.YesOptionScore = getValue(opt.YesOptionScore);
                                    }

                                    if (OptionEntity.OptionID == null || OptionEntity.OptionID.Value.ToString() == "")
                                    {
                                        OptionEntity.IsRightValue   = 0;
                                        OptionEntity.NoOptionScore  = 0;
                                        OptionEntity.YesOptionScore = 0;
                                        OptionBLL.Create(OptionEntity);
                                    }
                                    else
                                    {
                                        OptionBLL.Update(OptionEntity, false);
                                    }
                                }

                                #endregion

                                #region  项删除
                                if (para.step == 3 && ques.OptionDelDatalist != null)
                                {
                                    object[] dels = new object[ques.OptionDelDatalist.Count];
                                    for (int j = 0; j < ques.OptionDelDatalist.Count; j++)
                                    {
                                        dels[j] = ques.OptionDelDatalist[j].OptionID;
                                    }

                                    OptionBLL.Delete(dels);
                                }

                                #endregion
                            }


                            #region 问卷关联题目添加
                            T_QN_QuestionNaireQuestionMappingEntity QuestionNaireQuestionMappingEntity = new T_QN_QuestionNaireQuestionMappingEntity()
                            {
                                CustomerID      = loggingSessionInfo.ClientID,
                                QuestionID      = QuestionEntity.Questionid.ToString(),
                                QuestionnaireID = model_QuestionnaireEntity.QuestionnaireID.ToString(),
                                Sort            = 999,
                                Status          = 0
                            };

                            QuestionNaireQuestionMappingBLL.Create(QuestionNaireQuestionMappingEntity);
                            #endregion
                        }
                    }
                    #endregion
                }
            }



            return(rd);
        }
コード例 #49
0
ファイル: Tests.cs プロジェクト: siwater/cloudstack_dotnetsdk
 internal void ListAsyncJobs()
 {
     try
     {
         Client session = new Client(serviceUri, apiKey, secretKey);
         APIRequest request = new APIRequest("listAsyncJobs");
         var deployResp = session.SendRequest(request);
         logWriter(deployResp.ToString());
     }
     catch (System.Exception wex)
     {
         logWriter(wex.Message);
     }
 }
コード例 #50
0
        protected override GetOrderDeliveryTimeRangeRD ProcessRequest(APIRequest <GetOrderDeliveryTimeRangeRP> pRequest)
        {
            GetOrderDeliveryTimeRangeRD rd = new GetOrderDeliveryTimeRangeRD();
            //定义变量,取当前时间
            var now = DateTime.Now;
            //当前小时
            var startPoint = now.Hour;

            //如果当前分钟大于0。则从下一小时开始取
            if (now.Minute > 0)
            {
                startPoint = startPoint + 1;
            }
            //开始时间
            DateTime begin = DateTime.Now;

            //结束时间
            DateTime end = DateTime.Now;

            //当前小时在0-9,不在工作时间范围的,统一从11点开始
            if (startPoint <= 9)
            {                                  //早上9点之前
                begin = now.Date.AddHours(11); //开始时间从11点开始
            }
            //当前小时在19点到凌晨24点的时间,开始时间统一从第二天早上11点开始
            else if (startPoint >= 19)
            {
                begin = now.Date.AddDays(1).AddHours(11);//晚上19:00之后的,开始时间都从第二天的11点开始
            }
            else
            {
                begin = now.Date.AddHours(startPoint + 2); //除此之外的时间段,开始时间统一在2小小时之后。
            }

            end = begin.Date.AddDays(3).AddHours(21);   //结束时间为起始时间的3天之后的晚上9点
            //获取时间分段
            List <DateInfo> list = new List <DateInfo>();
            var             dt1  = new DateInfo();   //第一天

            dt1.Date = begin.ToString("yyyy-MM-dd"); //第一天的日期部分
            list.Add(dt1);

            List <DateTimeRangeInfo> range1 = new List <DateTimeRangeInfo>();
            var day1Begin = begin;                        //第一天的开始时间
            var day1End   = begin.Date.AddHours(21);      //第一天的结束时间

            while (day1Begin < day1End)                   //当开始时间小于结束时间的时候
            {
                var beginSection = day1Begin;             //开始时间等于第一天的开始时间
                var endSection   = day1Begin.AddHours(2); //结束时间等于开始时间+2小时
                if (endSection.Hour <= 21)                //当结束时间小于当天晚上21点的时候
                {                                         //时间段的结束时间不超过晚9点的,则2小时一划分
                    DateTimeRangeInfo r1 = new DateTimeRangeInfo();
                    r1.BeginTime = beginSection.ToString("HH:mm");
                    r1.EndTime   = endSection.ToString("HH:mm");
                    r1.Desc      = string.Format("{0} - {1}", r1.BeginTime, r1.EndTime);
                    range1.Add(r1);
                }
                else
                {//否则结束时间就为晚9点
                    DateTimeRangeInfo r1 = new DateTimeRangeInfo();
                    r1.BeginTime = beginSection.ToString("HH:mm");
                    r1.EndTime   = beginSection.Date.AddHours(21).ToString("HH:mm");
                    r1.Desc      = string.Format("{0} - {1}", r1.BeginTime, r1.EndTime);
                    range1.Add(r1);
                }
                //设置下一个时间分段的起始时间
                day1Begin = day1Begin.AddHours(2);
            }
            dt1.Ranges = range1.ToArray();

            //第二天
            var dt2 = new DateInfo();

            //日期天加一天。其余小时部分都从早上9点到晚上9点
            dt2.Date = begin.Date.AddDays(1).ToString("yyyy-MM-dd");
            list.Add(dt2);

            dt2.Ranges = new DateTimeRangeInfo[] {
                new DateTimeRangeInfo()
                {
                    BeginTime = "9:00", EndTime = "11:00", Desc = "9:00 - 11:00"
                }
                , new DateTimeRangeInfo()
                {
                    BeginTime = "11:00", EndTime = "13:00", Desc = "11:00 - 13:00"
                }
                , new DateTimeRangeInfo()
                {
                    BeginTime = "13:00", EndTime = "15:00", Desc = "13:00 - 15:00"
                }
                , new DateTimeRangeInfo()
                {
                    BeginTime = "15:00", EndTime = "17:00", Desc = "15:00 - 17:00"
                }
                , new DateTimeRangeInfo()
                {
                    BeginTime = "17:00", EndTime = "19:00", Desc = "17:00 - 19:00"
                }
                , new DateTimeRangeInfo()
                {
                    BeginTime = "19:00", EndTime = "21:00", Desc = "19:00 - 21:00"
                }
            };

            //第三天

            var dt3 = new DateInfo();

            //日期天加二天。其余小时部分都从早上9点到晚上9点
            dt3.Date = begin.Date.AddDays(2).ToString("yyyy-MM-dd");
            list.Add(dt3);

            dt3.Ranges = new DateTimeRangeInfo[] {
                new DateTimeRangeInfo()
                {
                    BeginTime = "9:00", EndTime = "11:00", Desc = "9:00 - 11:00"
                }
                , new DateTimeRangeInfo()
                {
                    BeginTime = "11:00", EndTime = "13:00", Desc = "11:00 - 13:00"
                }
                , new DateTimeRangeInfo()
                {
                    BeginTime = "13:00", EndTime = "15:00", Desc = "13:00 - 15:00"
                }
                , new DateTimeRangeInfo()
                {
                    BeginTime = "15:00", EndTime = "17:00", Desc = "15:00 - 17:00"
                }
                , new DateTimeRangeInfo()
                {
                    BeginTime = "17:00", EndTime = "19:00", Desc = "17:00 - 19:00"
                }
                , new DateTimeRangeInfo()
                {
                    BeginTime = "19:00", EndTime = "21:00", Desc = "19:00 - 21:00"
                }
            };
            //
            rd.DateRange = list.ToArray();
            return(rd);
        }
コード例 #51
0
		async Task OnRefresh(CancellationToken token)
		{
			APIRequest ApiReq = new APIRequest ();
			PicksBansOld pickBans=new PicksBansOld();
			//cts = new CancellationTokenSource ();
			refreshFlag = true;
			token.ThrowIfCancellationRequested ();
			var url =SettingsApp.ServerAPIAddress+SettingsApp.GameName+"/GetDetailInfo?match_id="+matchInfo.MatchId;
			var jMatchResponce = await ApiReq.GetJsonAsync (url);

			var jDetailMatchInfo= JsonConvert.DeserializeObject<JDetailMatchInfo>(jMatchResponce.ToString());
			var jMatchDetails=JToken.Parse(jDetailMatchInfo.JMatchDetails);
			matchInfo=JsonConvert.DeserializeObject<MatchInfo>(jMatchDetails.ToString());
			dotaMatchInfo=JsonConvert.DeserializeObject<List<DotaMatchInfo>>(jMatchDetails.SelectToken("DetailsMatch").ToString());
			List<DetailInfo> listDetail=new List<DetailInfo>();
			listDetail.AddRange(dotaMatchInfo);
			matchInfo.DetailsMatch=listDetail;

			radiantPB = pickBans.ParseJsonToRadPick (dotaMatchInfo[0].RadiantPicks);
			direPB = pickBans.ParseJsonToDirePick (dotaMatchInfo[0].DirePicks);
			token.ThrowIfCancellationRequested ();
			await SetHeroesImageInLayout (token);

			var analisPick=new AnalysisPick();
			var textRadiant=FindViewById<TextView>(Resource.Id.textTeamFP);
			var textDire=FindViewById<TextView>(Resource.Id.textTeamSP);
			var value=analisPick.GetAnalysisTeam(dotaMatchInfo[0].RadiantPicks.ListPicks,dotaMatchInfo[0].DirePicks.ListPicks);
			textRadiant.Text=Resources.GetString(Resource.String.radiant)+"  "+value[0].ToString();
			textDire.Text=Resources.GetString(Resource.String.dire)+"  "+(value[1].ToString());
			Toast.MakeText (this, Resources.GetString(Resource.String.updated), ToastLength.Short).Show ();
			refreshFlag = false;
		}
コード例 #52
0
        protected override SetEvaluationRD ProcessRequest(APIRequest <SetEvaluationItemRP> pRequest)
        {
            SetEvaluationRD rd    = new SetEvaluationRD();
            var             bll   = new ObjectEvaluationBLL(CurrentUserInfo);
            var             pTran = bll.GetTran();//事务

            using (pTran.Connection)
            {
                try
                {
                    SetEvaluationItemRP rp = pRequest.Parameters;
                    var inoutBll           = new T_InoutBLL(CurrentUserInfo);
                    //评论订单
                    var entity = new ObjectEvaluationEntity()
                    {
                        EvaluationID = Guid.NewGuid().ToString(),
                        CustomerID   = pRequest.CustomerID,
                        VipID        = pRequest.UserID,
                        ObjectID     = rp.OrderID,
                        OrderID      = rp.OrderID,
                        Type         = rp.Type,
                        Content      = rp.Content,
                        StarLevel    = rp.StarLevel,
                        StarLevel1   = rp.StarLevel1,
                        StarLevel2   = rp.StarLevel2,
                        StarLevel3   = rp.StarLevel3,
                        StarLevel4   = rp.StarLevel4,
                        StarLevel5   = rp.StarLevel5,
                        Platform     = rp.Platform,
                        IsAnonymity  = rp.IsAnonymity
                    };
                    bll.Create(entity, pTran);

                    //批量评论商品
                    if (rp.ItemEvaluationInfo != null)
                    {
                        ObjectEvaluationEntity evaluation = null;
                        foreach (var item in rp.ItemEvaluationInfo)
                        {
                            evaluation             = new ObjectEvaluationEntity();
                            evaluation.ObjectID    = item.ObjectID;
                            evaluation.StarLevel   = item.StarLevel;
                            evaluation.Content     = item.Content;
                            evaluation.Remark      = item.Remark;
                            evaluation.CustomerID  = pRequest.CustomerID;
                            evaluation.IsAnonymity = rp.IsAnonymity;
                            evaluation.OrderID     = rp.OrderID;
                            evaluation.Type        = rp.Type;
                            evaluation.VipID       = pRequest.UserID;
                            bll.Create(evaluation, pTran);
                        }
                    }

                    //修改订单评论状态
                    var order = inoutBll.GetByID(rp.OrderID);
                    if (order != null)
                    {
                        order.IsEvaluation = 1;
                        inoutBll.Update(order, pTran);
                    }
                    pTran.Commit(); //提交事物

                    #region 评论触点活动奖励

                    var bllPrize = new LPrizesBLL(CurrentUserInfo);
                    //bllPrize.CheckIsWinnerForShare(CurrentUserInfo.UserID, "", "Comment");

                    RedisContactBLL redisContactBll = new RedisContactBLL();
                    redisContactBll.SetRedisContact(new RedisOpenAPIClient.Models.CC.CC_Contact()
                    {
                        CustomerId  = CurrentUserInfo.ClientID,
                        ContactType = "Comment",
                        VipId       = CurrentUserInfo.UserID
                    });

                    #endregion

                    try
                    {
                        var msg = new EventContract
                        {
                            Operation  = OptEnum.Create,
                            EntityType = EntityTypeEnum.OrderComment,
                            Id         = rp.OrderID
                        };
                        var eventService = new EventService();
                        eventService.PublishMsg(msg);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    pTran.Rollback();
                    throw new APIException(ex.Message);
                }
            }

            return(rd);
        }
コード例 #53
0
		protected override async void OnCreate (Bundle bundle)
		{
			//Window.RequestFeature(WindowFeatures.NoTitle);
			try{

				base.OnCreate (bundle);
				SetContentView (Resource.Layout.PicksLayout);
				pb = FindViewById<ProgressBar> (Resource.Id.progressBar3);
				ActionBarTitle.SetTitle (this,Resource.Layout.ActionBarLayout,Resources.GetString(Resource.String.capitanMod),"DOTA 2");
				buttonRefresh=FindViewById<Button>(Resource.Id.buttonRefreshActionBar);
				buttonRefresh.Click+=ButtonRefreshClick;
				buttonRefresh.Visibility=ViewStates.Invisible;
				var buttonBack=FindViewById<Button>(Resource.Id.buttonBackActionBar);
				buttonBack.Click+=ButtonBackClick;
				pb=FindViewById<ProgressBar> (Resource.Id.progressBar3);
				pb.Visibility= ViewStates.Visible;
				APIRequest ApiReq = new APIRequest ();
				PicksBansOld pickBans=new PicksBansOld();
				Player playerReq=new Player();
				gameInfo=Intent.GetStringExtra("matchDetail");
				var jDetailMatchInfo= JsonConvert.DeserializeObject<JDetailMatchInfo>(gameInfo);
				var jMatchDetails=JToken.Parse(jDetailMatchInfo.JMatchDetails);
				matchInfo=JsonConvert.DeserializeObject<MatchInfo>(jMatchDetails.ToString());
				dotaMatchInfo=JsonConvert.DeserializeObject<List<DotaMatchInfo>>(jMatchDetails.SelectToken("DetailsMatch").ToString());
				List<DetailInfo> listDetail=new List<DetailInfo>();
				listDetail.AddRange(dotaMatchInfo);
				matchInfo.DetailsMatch=listDetail;

				liveFlag=Intent.GetStringExtra("liveFlag");
				title=Intent.GetStringExtra("title");



			TextView radiantName, direName,textRadiant,textDire;
			ImageView radiantLogo, direLogo;
			LinearLayout llradiantTeam, lldireTeam;
				radiantName=FindViewById<TextView>(Resource.Id.radiantTeamName);
				direName=FindViewById<TextView>(Resource.Id.direTeamName);
				radiantLogo=FindViewById<ImageView>(Resource.Id.logoRadiantTeam);
				direLogo=FindViewById<ImageView>(Resource.Id.logoDireTeam);
				llradiantTeam=FindViewById<LinearLayout>(Resource.Id.llradiantTeam);
				lldireTeam=FindViewById<LinearLayout>(Resource.Id.lldireTeam);
					textRadiant=FindViewById<TextView>(Resource.Id.textTeamFP);
					textDire=FindViewById<TextView>(Resource.Id.textTeamSP);

				var analisPick=new AnalysisPick();
				var value=analisPick.GetAnalysisTeam(dotaMatchInfo[0].RadiantPicks.ListPicks,dotaMatchInfo[0].DirePicks.ListPicks);
				textRadiant.Text=Resources.GetString(Resource.String.radiant)+"  "+value[0].ToString();
				textDire.Text=Resources.GetString(Resource.String.dire)+"  "+(value[1].ToString());
				textRadiant.SetTextAppearance(this,Resource.Style.RadiantName);
				textDire.SetTextAppearance(this,Resource.Style.DireName);

				TeamDb teamDb=new TeamDb();
				var radiantTeam= await teamDb.GetTeam(matchInfo.Team1Id,"DOTA2");
				var direTeam= await teamDb.GetTeam(matchInfo.Team2Id,"DOTA2");
				if(radiantTeam != null){
					radiantName.Text=radiantTeam.Name;
					if(radiantTeam.LogoByte!=null){
						Bitmap bmp1= BitmapFactory.DecodeByteArray (radiantTeam.LogoByte, 0, radiantTeam.LogoByte.Length);
						radiantLogo.SetImageBitmap(bmp1);
					}
				}
				if(direTeam != null){
					direName.Text=direTeam.Name;
					if(direTeam.LogoByte!=null){
						Bitmap bmp2= BitmapFactory.DecodeByteArray (direTeam.LogoByte, 0, direTeam.LogoByte.Length);
						direLogo.SetImageBitmap(bmp2);
					}
				}
				var bluePlayer=llradiantTeam.FindViewById<TextView>(Resource.Id.textPlayer1);
				var cyanPlayer=llradiantTeam.FindViewById<TextView>(Resource.Id.textPlayer2);
				var purpurePlayer=llradiantTeam.FindViewById<TextView>(Resource.Id.textPlayer3);
				var yellowPlayer=llradiantTeam.FindViewById<TextView>(Resource.Id.textPlayer4);
				var orangePlayer=llradiantTeam.FindViewById<TextView>(Resource.Id.textPlayer5);
			 
			var pinkPlayer=lldireTeam.FindViewById<TextView>(Resource.Id.textPlayer1);
			var olivePlayer=lldireTeam.FindViewById<TextView>(Resource.Id.textPlayer2);
			var aquaPlayer=lldireTeam.FindViewById<TextView>(Resource.Id.textPlayer3);
			var darkgreenPlayer=lldireTeam.FindViewById<TextView>(Resource.Id.textPlayer4);
			var chokolatePlayer=lldireTeam.FindViewById<TextView>(Resource.Id.textPlayer5);
				var listTextView = new List<TextView> (){bluePlayer,cyanPlayer,purpurePlayer,yellowPlayer,orangePlayer,
				pinkPlayer,olivePlayer,aquaPlayer,darkgreenPlayer,chokolatePlayer};
			
				var allPlayerInfo = dotaMatchInfo[0].Players;
			for (var i = 0; i < allPlayerInfo.Count(); i++) {
					int color=ColorsOnMatch.GetColorPlayer(i);
				listTextView [i].Text = allPlayerInfo [i].PlayerName;
				listTextView[i].SetTextColor(Resources.GetColor(color));
			}
				radiantPB = pickBans.ParseJsonToRadPick (dotaMatchInfo[0].RadiantPicks);
				direPB = pickBans.ParseJsonToDirePick (dotaMatchInfo[0].DirePicks);
				cts=new CancellationTokenSource();
				cts.Token.ThrowIfCancellationRequested ();
				await SetHeroesImageInLayout (cts.Token);
				cts = null;
			}
			catch(Exception e){
				Console.WriteLine (e);
			}
			pb.Visibility= ViewStates.Gone;
			buttonRefresh.Visibility = ViewStates.Visible;
		}
コード例 #54
0
        /// <summary>
        /// Handle the input API call.
        /// </summary>
        /// <param name="request">The request object for the API call</param>
        /// <returns>The input response</returns>
        public APIResponse Handle(APIRequest request)
        {
            _log.Trace($"Handle input from client. Content-Type is '{request.Headers.ContentType}'");
            var response = new APIResponse();


            // Check the Content-Type
            // If it is application/json
            // TODO: if will be parsed into IOData that may contain multiple
            // TODO: Define custom JSON? application/vnd.limitless.input+json?
            // inputs.
            if (request.Headers.ContentType == MimeType.Json)
            {
                _log.Debug("Received JSON, parse into usable type");
                throw new NotImplementedException("JSON received. Needs to be parsed into usable type");
            }

            // Find out what Mime/Language input combinations are supported by the interaction engine
            // This will determine what the input pipeline should attempt to produce
            // TODO: Support multiple IO combinations for more advanced engines
            SupportedIOCombination engineCombinations = _engine.GetSupportedIOCombinations().First();

            // TODO: Resolve multi-request parallel - ie. speech recognition + voice recognition id
            // Attempt to process input to reach the engineCombinations
            var ioData = new IOData(new MimeLanguage(request.Headers.ContentType, request.Headers.RequestLanguage), request.Data);

            ioData = Resolve(ioData, engineCombinations.SupportedInput, _inputProviders);

            // Let the engine do its thing
            ioData = _engine.ProcessInput(ioData);

            // TODO Find solution to multiple accepted languages
            // What is the client expecting in return
            Tuple <string, decimal> preferredMime = request.Headers.Accept.OrderByDescending(x => x.Item2).First();
            // Multiple languages could be present, this selects the language with the highest weighted value
            // More on languages and weighted values: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language
            // The tuple contains <language,weight>
            Tuple <string, decimal> preferredLanguage = request.Headers.AcceptLanguage.OrderByDescending(x => x.Item2).First();

            ioData = Resolve(ioData, new MimeLanguage(preferredMime.Item1, preferredLanguage.Item1), _outputProviders);

            // Set the headers for the data.
            // TODO: In future this will be part of the response
            // not just a list.
            response.Data = ioData.Data;
            var header = new
            {
                Header = "Content-Type",
                Value  = ioData.MimeLanguage.Mime
            };

            response.Headers.Add(header);
            header = new
            {
                Header = "Language",
                Value  = ioData.MimeLanguage.Language
            };
            response.Headers.Add(header);

            return(response);
        }
コード例 #55
0
        protected override TemplateDetailRD ProcessRequest(APIRequest <TemplateDetailRP> pRequest)
        {
            var rd = new TemplateDetailRD();

            var para = pRequest.Parameters;
            var loggingSessionInfo = new SessionManager().CurrentUserLoginInfo;

            CTW_LEventThemeBLL        bllTheme         = new CTW_LEventThemeBLL(loggingSessionInfo);
            CTW_LEventInteractionBLL  bllInteraction   = new CTW_LEventInteractionBLL(loggingSessionInfo);
            CTW_SpreadSettingBLL      bllSpreadSetting = new CTW_SpreadSettingBLL(loggingSessionInfo);
            T_CTW_LEventsBLL          bllEvents        = new T_CTW_LEventsBLL(loggingSessionInfo);
            T_CTW_PanicbuyingEventBLL bllPanicbuying   = new T_CTW_PanicbuyingEventBLL(loggingSessionInfo);
            //更新模板点击数量
            T_CTW_LEventTemplateBLL bllTemplate = new T_CTW_LEventTemplateBLL(loggingSessionInfo);

            try
            {
                bllTemplate.UpdateTemplateInfo(para.TemplateId, 2);
            }
            catch { }
            ///获取模版信息
            DataSet dsInteraction = bllInteraction.GetEventInteractionByTemplateId(para.TemplateId);

            if (dsInteraction != null && dsInteraction.Tables[0].Rows.Count > 0)
            {
                var entityInteraction = DataTableToObject.ConvertToList <EventInteractionInfo>(dsInteraction.Tables[0]);

                var entityTheme = DataTableToObject.ConvertToList <CTW_LEventThemeEntity>(bllTheme.GetThemeInfo(para.TemplateId).Tables[0]);//.QueryByEntity(new CTW_LEventThemeEntity() { TemplateId = new Guid(para.TemplateId), IsDelete = 0 }, null);
                List <CTW_LEventThemeEntity> listTheme = new List <CTW_LEventThemeEntity>();
                foreach (var theme in entityTheme)
                {
                    List <EventInteractionInfo> listEventInteractionInfo = new List <EventInteractionInfo>();

                    ///互动信息
                    foreach (var itemAction in entityInteraction.Where(a => a.ThemeId == theme.ThemeId.ToString() && a.TemplateId == theme.TemplateId.ToString()))
                    {
                        listEventInteractionInfo.Add(itemAction);
                        if (itemAction.InteractionType == 1)
                        {
                            itemAction.GameEventImageList = DataTableToObject.ConvertToList <GameEventImageInfo>(bllEvents.GetImageList(itemAction.LeventId).Tables[0]);
                        }
                        if (itemAction.InteractionType == 2)//促销
                        {
                            itemAction.PanicbuyingEventImage = DataTableToObject.ConvertToObject <PanicbuyingEventImageInfo>(bllPanicbuying.GetPanicbuyingEventImage(itemAction.LeventId).Tables[0].Rows[0]);
                        }
                        theme.EventInteractionList = listEventInteractionInfo;
                    }
                    ;
                    listTheme.Add(theme);
                    rd.TemplateThemeList = listTheme;
                }
                rd.ActivityGroupId = entityTheme.FirstOrDefault().ActivityGroupId;
                rd.TemplateId      = entityTheme.FirstOrDefault().TemplateId.ToString();
                rd.TemplateName    = entityTheme.FirstOrDefault().TemplateName;
                rd.ImageURL        = dsInteraction.Tables[0].Rows[0]["ImageURL"].ToString();
                //推广设置
                DataSet dsSpresd = bllSpreadSetting.GetSpreadSettingInfoByTemplateId(para.TemplateId);
                if (dsSpresd != null && dsSpresd.Tables[0].Rows.Count > 0)
                {
                    rd.TemplateSpreadSettingList = DataTableToObject.ConvertToList <CTW_SpreadSettingEntity>(dsSpresd.Tables[0]);
                }

                ///获取商户所有信息
                if (!string.IsNullOrEmpty(para.CTWEventId))
                {
                    T_CTW_LEventBLL bllCTWEvent = new T_CTW_LEventBLL(loggingSessionInfo);
                    DataSet         dsCTWEvent  = bllCTWEvent.GetLeventInfoByCTWEventId(para.CTWEventId);
                    ObjectImagesBLL bllImage    = new ObjectImagesBLL(loggingSessionInfo);
                    var             bllPrizes   = new LPrizesBLL(loggingSessionInfo);

                    T_CTW_SpreadSettingBLL bllCustomerSpreadSetting = new T_CTW_SpreadSettingBLL(loggingSessionInfo);
                    if (dsCTWEvent != null && dsCTWEvent.Tables.Count > 0 && dsCTWEvent.Tables[0].Rows.Count > 0)
                    {
                        rd.CustomerCTWEventInfo = DataTableToObject.ConvertToObject <CustomerCTWEventInfo>(dsCTWEvent.Tables[0].Rows[0]);
                        //游戏活动信息
                        if (dsCTWEvent.Tables[0].Rows[0]["InteractionType"].ToString() == "1")
                        {
                            LEventsBLL bllLevents = new LEventsBLL(loggingSessionInfo);
                            string     strEventId = dsCTWEvent.Tables[0].Rows[0]["LeventId"].ToString();
                            var        ds         = bllLevents.GetNewEventInfo(strEventId);
                            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                            {
                                rd.CustomerCTWEventInfo.EventInfo = DataTableToObject.ConvertToObject <LEventsInfo>(ds.Tables[0].Rows[0]);//直接根据所需要的字段反序列化
                            }
                            DataSet dsPrizes = bllPrizes.GetPirzeList(strEventId);
                            if (dsPrizes.Tables != null && dsPrizes.Tables.Count > 0 && dsPrizes.Tables[0] != null && dsPrizes.Tables[0].Rows.Count > 0)
                            {
                                rd.CustomerCTWEventInfo.EventInfo.PrizeList = DataTableToObject.ConvertToList <Prize>(dsPrizes.Tables[0]);
                            }


                            rd.CustomerCTWEventInfo.EventInfo.ImageList = bllImage.QueryByEntity(new ObjectImagesEntity()
                            {
                                ObjectId = strEventId, IsDelete = 0
                            }, null).ToList();
                        }
                        //促销活动信息
                        if (dsCTWEvent.Tables[0].Rows[0]["InteractionType"].ToString() == "2")
                        {
                            T_CTW_PanicbuyingEventKVBLL bllPanicbuyingEventKV = new T_CTW_PanicbuyingEventKVBLL(loggingSessionInfo);
                            rd.CustomerCTWEventInfo.PanicbuyingEventInfo = DataTableToObject.ConvertToObject <T_CTW_PanicbuyingEventKVEntity>(bllPanicbuyingEventKV.GetPanicbuyingEventKV(para.CTWEventId).Tables[0].Rows[0]);
                            T_CTW_LEventInteractionBLL bllEventInteraction = new T_CTW_LEventInteractionBLL(loggingSessionInfo);
                            DataSet dsP = bllEventInteraction.GetPanicbuyingEventId(para.CTWEventId);
                            if (dsP != null && dsP.Tables.Count > 0 && dsP.Tables[0].Rows.Count > 0)
                            {
                                rd.CustomerCTWEventInfo.PanicbuyingEventInfo.PanicbuyingEventList = DataTableToObject.ConvertToList <PanicbuyingEventId>(dsP.Tables[0]);
                            }
                        }

                        //图文信息
                        var ds2 = bllCTWEvent.GetMaterialTextInfo(dsCTWEvent.Tables[0].Rows[0]["OnlineQRCodeId"].ToString());//活动图文素材对应的keyword其实是这个活动的标识,也就是生成二维码的关键字
                        if (ds2 != null && ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
                        {
                            rd.CustomerCTWEventInfo.MaterialText = DataTableToObject.ConvertToObject <WMaterialTextEntity>(ds2.Tables[0].Rows[0]);//直接根据所需要的字段反序列化
                            rd.CustomerCTWEventInfo.MappingId    = ds2.Tables[0].Rows[0]["MappingId"].ToString();
                        }
                        //推广设置

                        DataSet dsCustomerSpread = bllCustomerSpreadSetting.GetSpreadSettingByCTWEventId(para.CTWEventId);
                        if (dsCustomerSpread != null && dsCustomerSpread.Tables[0].Rows.Count > 0)
                        {
                            rd.CustomerCTWEventInfo.SpreadSettingList = DataTableToObject.ConvertToList <T_CTW_SpreadSettingEntity>(dsCustomerSpread.Tables[0]);
                        }
                        //触点
                        ContactEventBLL bllContactEvent = new ContactEventBLL(loggingSessionInfo);
                        DataSet         dsContact       = bllContactEvent.GetContactEventByCTWEventId(para.CTWEventId);
                        if (dsContact != null && dsContact.Tables[0].Rows.Count > 0)
                        {
                            List <ContactEventInfo> ContactInfoList = new List <ContactEventInfo>();
                            ContactEventInfo        ContactInfo     = new ContactEventInfo();
                            foreach (DataRow dr in dsContact.Tables[0].Rows)
                            {
                                ContactInfo = new ContactEventInfo();
                                ContactInfo.ContactTypeCode = dr["ContactTypeCode"].ToString();
                                DataSet dsPrizes = bllPrizes.GetPirzeListForCTW(dr["ContactEventId"].ToString());
                                if (dsPrizes.Tables != null && dsPrizes.Tables.Count > 0 && dsPrizes.Tables[0] != null && dsPrizes.Tables[0].Rows.Count > 0)
                                {
                                    ContactInfo.ContactPrizeList = DataTableToObject.ConvertToList <Prize>(dsPrizes.Tables[0]);
                                }
                                ContactInfoList.Add(ContactInfo);
                            }
                            rd.CustomerCTWEventInfo.ContactEventList = ContactInfoList;
                        }
                    }


                    rd.CTWEventId = para.CTWEventId;
                }
                else
                {
                    rd.CTWEventId = Guid.NewGuid().ToString();
                }
            }
            return(rd);
        }
コード例 #56
0
        public async Task <bool> UpdateDatabase(string APIKey, string AcYear, string AcademyCode, int?LowestYear = null, int?HighestYear = null, int?ReportId = null, DateTime?Date = null)
        {
            try
            {
                APIRequest <GETEducationDetails, StudentEducationDetailsDTO> getEducationDetails = new APIRequest <GETEducationDetails, StudentEducationDetailsDTO>(_endPoint, APIKey, AcYear);
                var educationDetailsDTOs = getEducationDetails.ToList();

                var dtEdDetails = new DataTable();
                dtEdDetails.Columns.Add("StudentId", typeof(string));
                dtEdDetails.Columns.Add("Academy", typeof(string));
                dtEdDetails.Columns.Add("DataSet", typeof(string));
                dtEdDetails.Columns.Add("G4SStuId", typeof(int));
                dtEdDetails.Columns.Add("UPN", typeof(string));
                dtEdDetails.Columns.Add("FormerUPN", typeof(string));
                dtEdDetails.Columns.Add("NCYear", typeof(string));
                dtEdDetails.Columns.Add("RegistrationGroup", typeof(string));
                dtEdDetails.Columns.Add("House", typeof(string));

                var colAdmissionDate = new DataColumn
                {
                    DataType    = System.Type.GetType("System.DateTime"),
                    ColumnName  = "AdmissionDate",
                    AllowDBNull = true
                };

                dtEdDetails.Columns.Add(colAdmissionDate);

                var colLeavingDate = new DataColumn
                {
                    DataType    = System.Type.GetType("System.DateTime"),
                    ColumnName  = "LeavingDate",
                    AllowDBNull = true
                };

                dtEdDetails.Columns.Add(colLeavingDate);

                var dtStuAttributes = new DataTable();
                dtStuAttributes.Columns.Add("StudentAttributeId", typeof(string));
                dtStuAttributes.Columns.Add("StudentId", typeof(string));
                dtStuAttributes.Columns.Add("G4SStuId", typeof(int));
                dtStuAttributes.Columns.Add("AttributeId", typeof(int));
                dtStuAttributes.Columns.Add("Code", typeof(string));
                dtStuAttributes.Columns.Add("Name", typeof(string));
                dtStuAttributes.Columns.Add("IsSystem", typeof(bool));

                var dtStuAttribValues = new DataTable();
                dtStuAttribValues.Columns.Add("StudentAttributeId", typeof(string));
                dtStuAttribValues.Columns.Add("Value", typeof(string));
                dtStuAttribValues.Columns.Add("AcademicYear", typeof(String));
                var colAttribDate = new DataColumn
                {
                    DataType    = System.Type.GetType("System.DateTime"),
                    ColumnName  = "Date",
                    AllowDBNull = true
                };
                dtStuAttribValues.Columns.Add(colAttribDate);

                foreach (var item in educationDetailsDTOs)
                {
                    if (item.StuEdAttributes != null)
                    {
                        foreach (var stuAttrib in item.StuEdAttributes)
                        {
                            foreach (var attribValue in stuAttrib.AttributeValues)
                            {
                                //Populate Attribute Values Datatable
                                DateTime dateAttrib;
                                DateTime?dateAttribNullable;

                                if (DateTime.TryParseExact(attribValue.Date, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateAttrib))
                                {
                                    dateAttribNullable = dateAttrib.Date;
                                }
                                else
                                {
                                    dateAttribNullable = null;
                                }

                                var rowStuAttribVal = dtStuAttribValues.NewRow();
                                rowStuAttribVal["StudentAttributeId"] = AcademyCode + AcYear + "-" + item.G4SStuId.ToString() + "-" + stuAttrib.AttributeId.ToString();
                                rowStuAttribVal["Value"]        = attribValue.Value;
                                rowStuAttribVal["AcademicYear"] = attribValue.AcademicYear;

                                if (dateAttribNullable == null)
                                {
                                    rowStuAttribVal["Date"] = DBNull.Value;
                                }
                                else
                                {
                                    rowStuAttribVal["Date"] = dateAttribNullable.Value;
                                }

                                dtStuAttribValues.Rows.Add(rowStuAttribVal);
                            }
                            //Populate Student Arribute DataTable
                            var rowStuAttrib = dtStuAttributes.NewRow();
                            rowStuAttrib["StudentAttributeId"] = AcademyCode + AcYear + "-" + item.G4SStuId.ToString() + "-" + stuAttrib.AttributeId.ToString();
                            rowStuAttrib["StudentId"]          = AcademyCode + AcYear + "-" + item.G4SStuId.ToString();
                            rowStuAttrib["G4SStuId"]           = item.G4SStuId;
                            rowStuAttrib["AttributeId"]        = stuAttrib.AttributeId;
                            rowStuAttrib["Code"]     = stuAttrib.Code;
                            rowStuAttrib["Name"]     = stuAttrib.Name;
                            rowStuAttrib["IsSystem"] = stuAttrib.IsSystem;

                            dtStuAttributes.Rows.Add(rowStuAttrib);
                        }
                    }



                    //Populate Education Details DataTable

                    DateTime dateValueAdmission;
                    DateTime?dateValueNullableAdmission;

                    if (DateTime.TryParseExact(item.AdmissionDate, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValueAdmission))
                    {
                        dateValueNullableAdmission = dateValueAdmission.Date;
                    }
                    else
                    {
                        dateValueNullableAdmission = null;
                    }

                    DateTime dateValueLeaving;
                    DateTime?dateValueNullableLeaving;

                    if (DateTime.TryParseExact(item.LeavingDate, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValueLeaving))
                    {
                        dateValueNullableLeaving = dateValueLeaving.Date;
                    }
                    else
                    {
                        dateValueNullableLeaving = null;
                    }


                    var row = dtEdDetails.NewRow();
                    row["StudentId"]         = AcademyCode + AcYear + "-" + item.G4SStuId.ToString();
                    row["Academy"]           = AcademyCode;
                    row["DataSet"]           = AcYear;
                    row["G4SStuId"]          = item.G4SStuId;
                    row["UPN"]               = item.UPN;
                    row["FormerUPN"]         = item.FormerUPN;
                    row["NCYear"]            = item.NCYear;
                    row["RegistrationGroup"] = item.RegistrationGroup;
                    row["House"]             = item.House;

                    if (dateValueNullableAdmission == null)
                    {
                        row["AdmissionDate"] = DBNull.Value;
                    }
                    else
                    {
                        row["AdmissionDate"] = dateValueNullableAdmission;
                    }

                    if (dateValueNullableLeaving == null)
                    {
                        row["LeavingDate"] = DBNull.Value;
                    }
                    else
                    {
                        row["LeavingDate"] = dateValueNullableLeaving;
                    }

                    dtEdDetails.Rows.Add(row);
                }


                var currentEducationDetails = _context.EducationDetails
                                              .Where(i => i.DataSet == AcYear && i.Academy == AcademyCode);

                _context.EducationDetails.RemoveRange(currentEducationDetails);
                await _context.SaveChangesAsync();


                using (var sqlBulk = new SqlBulkCopy(_connectionString))
                {
                    // Set the timeout.
                    sqlBulk.BulkCopyTimeout = 60;

                    sqlBulk.ColumnMappings.Add("StudentId", "StudentId");
                    sqlBulk.ColumnMappings.Add("G4SStuId", "G4SStuId");
                    sqlBulk.ColumnMappings.Add("DataSet", "DataSet");
                    sqlBulk.ColumnMappings.Add("Academy", "Academy");
                    sqlBulk.ColumnMappings.Add("UPN", "UPN");
                    sqlBulk.ColumnMappings.Add("FormerUPN", "FormerUPN");
                    sqlBulk.ColumnMappings.Add("NCYear", "NCYear");
                    sqlBulk.ColumnMappings.Add("RegistrationGroup", "RegistrationGroup");
                    sqlBulk.ColumnMappings.Add("House", "House");
                    sqlBulk.ColumnMappings.Add("AdmissionDate", "AdmissionDate");
                    sqlBulk.ColumnMappings.Add("LeavingDate", "LeavingDate");

                    sqlBulk.DestinationTableName = "g4s.EducationDetails";
                    sqlBulk.WriteToServer(dtEdDetails);
                }

                using (var sqlBulk = new SqlBulkCopy(_connectionString))
                {
                    // Set the timeout.
                    sqlBulk.BulkCopyTimeout = 60;

                    sqlBulk.ColumnMappings.Add("StudentAttributeId", "StudentAttributeId");
                    sqlBulk.ColumnMappings.Add("StudentId", "StudentId");
                    sqlBulk.ColumnMappings.Add("G4SStuId", "G4SStuId");
                    sqlBulk.ColumnMappings.Add("AttributeId", "AttributeId");
                    sqlBulk.ColumnMappings.Add("Code", "Code");
                    sqlBulk.ColumnMappings.Add("Name", "Name");
                    sqlBulk.ColumnMappings.Add("IsSystem", "IsSystem");

                    sqlBulk.DestinationTableName = "g4s.StudentAttributes";
                    sqlBulk.WriteToServer(dtStuAttributes);
                }

                using (var sqlBulk = new SqlBulkCopy(_connectionString))
                {
                    // Set the timeout.
                    sqlBulk.BulkCopyTimeout = 60;

                    sqlBulk.ColumnMappings.Add("StudentAttributeId", "StudentAttributeId");
                    sqlBulk.ColumnMappings.Add("Value", "Value");
                    sqlBulk.ColumnMappings.Add("AcademicYear", "AcademicYear");
                    sqlBulk.ColumnMappings.Add("Date", "Date");

                    sqlBulk.DestinationTableName = "g4s.StudentAttributeValues";
                    sqlBulk.WriteToServer(dtStuAttribValues);
                }
                _context.SyncResults.Add(new SyncResult {
                    AcademyCode = AcademyCode, DataSet = AcYear, EndPoint = _endPoint, LoggedAt = DateTime.Now, Result = true
                });
                return(true);
            }

            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    _context.SyncResults.Add(new SyncResult {
                        AcademyCode = AcademyCode, DataSet = AcYear, EndPoint = _endPoint, Exception = e.Message, InnerException = e.InnerException.Message, LoggedAt = DateTime.Now, Result = false
                    });
                }
                else
                {
                    _context.SyncResults.Add(new SyncResult {
                        AcademyCode = AcademyCode, DataSet = AcYear, EndPoint = _endPoint, Exception = e.Message, LoggedAt = DateTime.Now, Result = false
                    });
                }

                await _context.SaveChangesAsync();

                return(false);
            }
        }
コード例 #57
0
ファイル: APIAccess.cs プロジェクト: yheno/osu
 public void Queue(APIRequest request)
 {
     queue.Enqueue(request);
 }
コード例 #58
0
		async Task OnRefresh (CancellationToken token){

			APIRequest ApiReq = new APIRequest ();
			refreshFlag = true;
			titleFlag = false;

			token.ThrowIfCancellationRequested ();
			if (listMatchInfo.Count > 0) {
				matchInfo_2 = listMatchInfo [0];
			}
			FillTitleMatch ();
			CreateFragment (Resource.Id.cs_llayout_match_draft, new FragmentCSMatchDraft (listMatchInfo));
			cts = null;
			refreshFlag = false;
			Toast.MakeText (this, Resources.GetString(Resource.String.updated), ToastLength.Short).Show ();
		}
コード例 #59
0
        public async Task <bool> UpdateDatabase(string APIKey, string AcYear, string AcademyCode, int?LowestYear = null, int?HighestYear = null, int?ReportId = null, DateTime?Date = null)
        {
            try
            {
                APIRequest <GETStudentDetails, StudentDTO> getStudents = new APIRequest <GETStudentDetails, StudentDTO>(_endPoint, APIKey, AcYear);
                var studentsDTO = getStudents.ToList();

                var dtStudents = new DataTable();
                dtStudents.Columns.Add("StudentId", typeof(String));
                dtStudents.Columns.Add("DataSet", typeof(String));
                dtStudents.Columns.Add("Academy", typeof(String));
                dtStudents.Columns.Add("G4SStuId", typeof(int));
                dtStudents.Columns.Add("LegalFirstName", typeof(String));
                dtStudents.Columns.Add("LegalLastName", typeof(String));
                dtStudents.Columns.Add("PreferredFirstName", typeof(String));
                dtStudents.Columns.Add("PreferredLastName", typeof(String));
                dtStudents.Columns.Add("MiddleNames", typeof(String));
                dtStudents.Columns.Add("Sex", typeof(String));
                dtStudents.Columns.Add("DateOfBirth", typeof(DateTime));

                foreach (var studentDTO in studentsDTO)
                {
                    var row = dtStudents.NewRow();

                    row["StudentId"]          = AcademyCode + AcYear + "-" + studentDTO.Id.ToString();
                    row["DataSet"]            = AcYear;
                    row["Academy"]            = AcademyCode;
                    row["G4SStuId"]           = studentDTO.Id;
                    row["LegalFirstName"]     = studentDTO.LegalFirstName;
                    row["LegalLastName"]      = studentDTO.LegalLastName;
                    row["PreferredFirstName"] = studentDTO.PreferredFirstName;
                    row["PreferredLastName"]  = studentDTO.PreferredLastName;
                    row["MiddleNames"]        = studentDTO.MiddleNames;
                    row["Sex"]         = studentDTO.Sex;
                    row["DateOfBirth"] = DateTime.ParseExact(studentDTO.DateOfBirth, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);

                    dtStudents.Rows.Add(row);
                }

                var currentStudents = _context.Students.Where(i => i.DataSet == AcYear && i.Academy == AcademyCode);
                _context.Students.RemoveRange(currentStudents);
                await _context.SaveChangesAsync();


                using (var sqlBulk = new SqlBulkCopy(_connectionString))
                {
                    //Add Mappings
                    sqlBulk.ColumnMappings.Add("StudentId", "StudentId");
                    sqlBulk.ColumnMappings.Add("G4SStuId", "G4SStuId");
                    sqlBulk.ColumnMappings.Add("DataSet", "DataSet");
                    sqlBulk.ColumnMappings.Add("Academy", "Academy");
                    sqlBulk.ColumnMappings.Add("DateOfBirth", "DateOfBirth");
                    sqlBulk.ColumnMappings.Add("Sex", "Sex");
                    sqlBulk.ColumnMappings.Add("LegalFirstName", "LegalFirstName");
                    sqlBulk.ColumnMappings.Add("LegalLastName", "LegalLastName");
                    sqlBulk.ColumnMappings.Add("PreferredFirstName", "PreferredFirstName");
                    sqlBulk.ColumnMappings.Add("PreferredLastName", "PreferredLastName");
                    sqlBulk.ColumnMappings.Add("MiddleNames", "MiddleNames");
                    sqlBulk.DestinationTableName = "g4s.Students";
                    sqlBulk.WriteToServer(dtStudents);
                }

                _context.SyncResults.Add(new SyncResult {
                    AcademyCode = AcademyCode, EndPoint = _endPoint, LoggedAt = DateTime.Now, Result = true, DataSet = AcYear
                });
                await _context.SaveChangesAsync();

                return(true);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    _context.SyncResults.Add(new SyncResult {
                        AcademyCode = AcademyCode, DataSet = AcYear, EndPoint = _endPoint, Exception = e.Message, InnerException = e.InnerException.Message, LoggedAt = DateTime.Now, Result = false
                    });
                }
                else
                {
                    _context.SyncResults.Add(new SyncResult {
                        AcademyCode = AcademyCode, DataSet = AcYear, EndPoint = _endPoint, Exception = e.Message, LoggedAt = DateTime.Now, Result = false
                    });
                }

                await _context.SaveChangesAsync();

                return(false);
            }
        }
コード例 #60
0
        public ActionResult <int> Get(string postcode, string address)
        {
            int score = APIRequest.GetScore(postcode, address);

            return(score);
        }