public ATTPayment() { this.endPoint = ConfigurationManager.AppSettings["endpoint"]; List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.Payment); this.requestFactory = new RequestFactory(this.endPoint, ConfigurationManager.AppSettings["api_key"], ConfigurationManager.AppSettings["secret_key"], scopes, null, null); }
/// <summary> /// The Page_Load event is triggered when a page loads, and ASP.NET will automatically call the subroutine Page_Load, and execute the code inside it. /// </summary> /// <param name="sender">an object that raised the event</param> /// <param name="e">Type EventArgs</param> protected void Page_Load(object sender, EventArgs e) { try { bool ableToRead = this.ReadConfigFile(); if (!ableToRead) { return; } // Instantiate RequestFactory Instance. List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.Payment); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); List<NotificationId> notificationIds = this.requestFactory.GetNotificationIds(Request.InputStream); this.SaveNotificationDetails(notificationIds); } catch (InvalidResponseException ie) { this.LogError(ie.Body); } catch (Exception ex) { this.LogError(ex.Message); } }
private GeoNorge(RequestFactory requestFactory, RequestRunner requestRunner) { _requestFactory = requestFactory; _requestRunner = requestRunner; _requestRunner.OnLogEventInfo += new GeoNorgeAPI.LogEventHandlerInfo(LogEventsInfo); _requestRunner.OnLogEventDebug += new GeoNorgeAPI.LogEventHandlerDebug(LogEventsDebug); _requestRunner.OnLogEventError += new GeoNorgeAPI.LogEventHandlerError(LogEventsError); }
// Use this for initialization void Start () { // API Gateway Endpoint. https://api.att.com string endPoint = "https://api.att.com"; // Application key registered at developer portal. string apiKey = "895610308e6400c200add4820a535e87"; //Secret Key of the application as registered at developer portal. string secretKey = "b71e400f2211a424"; // OAuth redirect URL configured at developer portal. This is required only for apps having Authorization credential model. string redirectURI = null; // Scopes the application is granted. List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.Speech); ServicePointManager.ServerCertificateValidationCallback = Validator; requestFactory = new RequestFactory(endPoint, apiKey, secretKey, scopes, redirectURI, null); }
public static HttpWebResponse GetResponse(string initialUri, RequestFactory requestFactory) { string uri = initialUri; for (int i = 0; i < 50; i++) { HttpWebRequest request = requestFactory(uri); request.AllowAutoRedirect = false; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if ((int)response.StatusCode >= 300 && (int)response.StatusCode < 400) { string redirectedLocation = response.Headers["Location"]; if (redirectedLocation == null || redirectedLocation == string.Empty) throw new BlogClientInvalidServerResponseException(initialUri, "An invalid redirect was returned (Location header was expected but not found)", string.Empty); uri = MergeUris(uri, redirectedLocation); response.Close(); continue; } return response; } throw new BlogClientInvalidServerResponseException(initialUri, "Allowed number of redirects (50) was exceeded", string.Empty); }
protected override void InitializeCommands() { base.InitializeCommands(); Delete = new RelayCommand(o => { ApplicationViewModel.RestClient.ExecuteAsync <Artist>(ApplicationViewModel.RequestFactory.DeleteArtistRequest(model.Id), (r, c) => { if (r.Succeeded()) { ApplicationViewModel.Search.Execute(model.Name); ApplicationViewModel.ClearHistory(); } else { ApplicationViewModel.HandlExceptionResponse(r.ExceptionResponse()); } }); /* * Response<bool> response = DataProvider.DeleteArtist(model.Id); * if (!response.Status) ApplicationViewModel.HandleError(response.Error); * else * { * ApplicationViewModel.Search.Execute(model.Name); * ApplicationViewModel.ClearHistory(); * }*/ }); CreateAlbum = new RelayCommand(o => { ApplicationViewModel.CreateView.Execute(new CreateAlbumViewModel(ApplicationViewModel, DataProvider, model)); }); NextCommentPage = new RelayCommand(o => RefreshComments(Model.Id, CommentPage.PageNumber + 1)); PreviousCommentPage = new RelayCommand(o => RefreshComments(Model.Id, CommentPage.PageNumber - 1)); PostComment = new RelayCommand(o => { Comment comment = new Comment() { EntityType = EntityType.ARTIST, User = LoginSession.Authentication.User, EntityId = Model.Id, Content = CommentContent }; RestClient.ExecuteAsync <Comment>(RequestFactory.AddCommentRequest(comment), (resp, handle) => { if (resp.Succeeded()) { RefreshComments(Model.Id, 1); } else { ApplicationViewModel.HandlExceptionResponse(resp.ExceptionResponse()); } }); }); AdminDeleteComment = new RelayCommand(o => { if (!(o is Comment)) { return; } Comment comment = o as Comment; RestClient.ExecuteAsync(RequestFactory.DeleteCommentRequest(comment.Id), (resp, handle) => { if (resp.Succeeded()) { RefreshComments(Model.Id, CommentPage.PageNumber); } else { ApplicationViewModel.HandlExceptionResponse(resp.ExceptionResponse()); } }); }); }
public async Task <RequestResult <List <Project> > > Accessible() { var request = RequestFactory.Create("projects"); return(await request.Execute <List <Project> >()); }
private static IEnumerable <ODataMediaTypeFormatter> CreateOutputFormatters(IEdmModel model) { var request = RequestFactory.CreateFromModel(model, "http://any"); return(ODataMediaTypeFormatters.Create().Select(f => f.GetPerRequestFormatterInstance(typeof(void), request, null) as ODataMediaTypeFormatter)); }
protected override void OnButtonHit() { WWW startGameRequest = RequestFactory.CreateStart(); Service.Get <RequestHandler>().HandleRequest(startGameRequest, gs => { }); }
public BasicHandler(FrontController front_controller, RequestFactory request_factory) { this.front_controller = front_controller; this.request_factory = request_factory; }
public void Property_Request_RoundTrips() { ReflectionAssert.Property(_context, (c) => c.Request, null, allowNull: true, roundTripTestValue: RequestFactory.Create()); }
/// <summary> /// Initialized RequestFactory with instance variable values. /// </summary> private void InitializeRequestFactory() { List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.CallControl); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); }
/// <summary> /// 下载简历 /// </summary> private static void DownloadResume() { while (true) { ZhaopinStaff staff; if (!staffQueue.TryDequeue(out staff)) { Thread.Sleep(10 * 1000); continue; } try { if (!dictionary.TryAdd(staff.Id, staff.CompanyId)) { continue; } var cookieContainer = staff.Cookie.Serialize(".zhaopin.com"); var isWhile = true; if (staff.Source.Contains("5.5")) { #region 网聘 5.5 while (isWhile) { var param = new { S_ResumeState = "1", S_CreateDate = $"{DateTime.Now.AddDays(-90):yyMMdd},{DateTime.Now:yyMMdd}", S_feedback = "", page = 1, pageSize = 100 }; var requestResult = RequestFactory.QueryRequest("https://rdapi.zhaopin.com/rd/resume/list", JsonConvert.SerializeObject(param), RequestEnum.POST, cookieContainer, contentType: ContentTypeEnum.Json.Description()); if (!requestResult.IsSuccess) { Trace.TraceWarning(requestResult.ErrorMsg); continue; } var content = JsonConvert.DeserializeObject <dynamic>(requestResult.Data); if ((int)content.code == 4) // 登录过期 { using (var db = new MangningXssDBEntities()) { var zhaopinStaff = db.ZhaopinStaff.FirstOrDefault(f => f.Id == staff.Id); if (zhaopinStaff != null) { zhaopinStaff.Cookie = null; db.SaveChanges(); dictionary.TryRemove(staff.Id, out companyId); } } Trace.WriteLine($"{DateTime.Now} > Loging Timeout ! Username = {staff.Username}, Message = {content.message}."); break; } if ((int)content.code != 0) { Trace.WriteLine($"{DateTime.Now} > Get Resume List Error ! Username = {staff.Username}, Message = {content.message}."); continue; } var resumes = content.data.dataList; var unhandled = (int)content.data.total; if (resumes.Count == 0) { break; } HandleResumes(resumes, unhandled, staff, ref isWhile, cookieContainer); } #endregion } else { #region 新系統 foreach (var orderFlag in new[] { "deal", "commu", "interview" }) { while (isWhile) { var requestResult = GetResumes(cookieContainer, 0, 60, orderFlag); if (!requestResult.IsSuccess) { Trace.TraceWarning(requestResult.ErrorMsg); continue; } var content = JsonConvert.DeserializeObject <dynamic>(requestResult.Data); if ((int)content.code == 6001) // 登录过期 { using (var db = new MangningXssDBEntities()) { var zhaopinStaff = db.ZhaopinStaff.FirstOrDefault(f => f.Id == staff.Id); if (zhaopinStaff != null) { zhaopinStaff.Cookie = null; db.SaveChanges(); dictionary.TryRemove(staff.Id, out companyId); } } Trace.WriteLine($"{DateTime.Now} > Loging Timeout ! Username = {staff.Username}, Message = {content.message}."); isWhile = false; break; } if ((int)content.code != 1) { Trace.WriteLine($"{DateTime.Now} > Get Resume List Error ! Username = {staff.Username}, Message = {content.message}."); continue; } var resumes = content.data[orderFlag].results; var unhandled = (int)content.data[orderFlag].numFound; if (resumes.Count == 0) { break; } HandleResumes(resumes, unhandled, staff, ref isWhile, cookieContainer); } } #endregion } } catch (Exception ex) { Trace.TraceError(ex.ToString()); } finally { dictionary.TryRemove(staff.Id, out companyId); } } }
public GSAsyncReliableRequest(RequestFactory requestFactory, Func<GSAsyncRequest, bool> resendPredicate, AsyncCallback callback, object state) : base(state, new ManualResetEvent(false), false, false) { this.requestFactory = requestFactory; this.resendPredicate = resendPredicate; this.callback = callback; FetchNewRequest(); }
public Task Should_fail_when_given_an_incorrect_client_id() => ShouldFail(RequestFactory.PasswordAuthenticationRequestWithIncorrectClientId());
public Task Should_fail_when_given_an_incorrect_scope() => ShouldFail(RequestFactory.PasswordAuthenticationRequestWithIncorrectScope());
public Task Should_fail_when_given_an_incorrect_apy_key() => ShouldFail(RequestFactory.PasswordAuthenticationRequestWithIncorrectApiKey());
public Task Should_fail_when_given_incorrect_credentials() => ShouldFail(RequestFactory.PasswordAuthenticationRequestWithIncorrectCredentials());
public void ProcessLevelsCorrectly_WithAutoExpand(string url) { // Arrange var model = GetAutoExpandEdmModel(); var context = new ODataQueryContext( model, model.FindDeclaredType("Microsoft.Test.AspNet.OData.Common.Models.AutoExpandCustomer")); var request = RequestFactory.Create(HttpMethod.Get, url); var queryOption = new ODataQueryOptions(context, request); queryOption.AddAutoSelectExpandProperties(); var selectExpand = queryOption.SelectExpand; // Act SelectExpandClause clause = selectExpand.ProcessLevels(); // Assert Assert.True(clause.AllSelected); Assert.Equal(2, clause.SelectedItems.Count()); // Level 1 of Customer. var cutomer = Assert.Single( clause.SelectedItems.OfType<ExpandedNavigationSelectItem>().Where( item => item.PathToNavigationProperty.FirstSegment is NavigationPropertySegment && ((NavigationPropertySegment) item.PathToNavigationProperty.FirstSegment).NavigationProperty .Name == "Friend") ); var clauseOfCustomer = cutomer.SelectAndExpand; Assert.True(clauseOfCustomer.AllSelected); Assert.Equal(2, clauseOfCustomer.SelectedItems.Count()); // Order under Customer. var order = Assert.Single( clause.SelectedItems.OfType<ExpandedNavigationSelectItem>().Where( item => item.PathToNavigationProperty.FirstSegment is NavigationPropertySegment && ((NavigationPropertySegment) item.PathToNavigationProperty.FirstSegment).NavigationProperty .Name == "Order") ); Assert.Null(order.LevelsOption); var clauseOfOrder = order.SelectAndExpand; Assert.True(clauseOfOrder.AllSelected); Assert.Single(clauseOfOrder.SelectedItems); // Choice Order under Order var choiceOrder = Assert.IsType<ExpandedNavigationSelectItem>(clauseOfOrder.SelectedItems.Single()); Assert.Null(choiceOrder.LevelsOption); Assert.True(choiceOrder.SelectAndExpand.AllSelected); Assert.Empty(choiceOrder.SelectAndExpand.SelectedItems); // Level 2 of Order. order = Assert.Single( clauseOfCustomer.SelectedItems.OfType<ExpandedNavigationSelectItem>().Where( item => item.PathToNavigationProperty.FirstSegment is NavigationPropertySegment && ((NavigationPropertySegment) item.PathToNavigationProperty.FirstSegment).NavigationProperty .Name == "Order") ); Assert.Null(order.LevelsOption); clauseOfOrder = order.SelectAndExpand; Assert.True(clauseOfOrder.AllSelected); Assert.Empty(clauseOfOrder.SelectedItems); // Level 2 of Customer. cutomer = Assert.Single( clauseOfCustomer.SelectedItems.OfType<ExpandedNavigationSelectItem>().Where( item => item.PathToNavigationProperty.FirstSegment is NavigationPropertySegment && ((NavigationPropertySegment) item.PathToNavigationProperty.FirstSegment).NavigationProperty .Name == "Friend") ); Assert.Null(cutomer.LevelsOption); clauseOfCustomer = cutomer.SelectAndExpand; Assert.True(clauseOfCustomer.AllSelected); Assert.Empty(clauseOfCustomer.SelectedItems); }
/// <summary> /// Reads the values from config file and initializes the instance of RequestFactory /// </summary> /// <returns>true/false; true if able to initialize successfully, else false</returns> private bool Initialize() { this.apiKey = ConfigurationManager.AppSettings["api_key"]; if (string.IsNullOrEmpty(this.apiKey)) { this.DrawPanelForFailure(notaryPanel, "api_key is not defined in the config file"); return false; } this.secretKey = ConfigurationManager.AppSettings["secret_key"]; if (string.IsNullOrEmpty(this.secretKey)) { this.DrawPanelForFailure(notaryPanel, "secret_key is not defined in the config file"); return false; } this.endPoint = ConfigurationManager.AppSettings["endpoint"]; if (string.IsNullOrEmpty(this.endPoint)) { this.DrawPanelForFailure(notaryPanel, "endpoint is not defined in the config file"); return false; } List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.Payment); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); return true; }
/// <summary> /// 處理簡歷列表 /// </summary> /// <param name="resumes"></param> /// <param name="unhandled"></param> /// <param name="staff"></param> /// <param name="isWhile"></param> /// <param name="cookieContainer"></param> private static void HandleResumes(dynamic resumes, int unhandled, ZhaopinStaff staff, ref bool isWhile, CookieContainer cookieContainer) { var stopwatch = new Stopwatch(); foreach (var item in resumes) { #region Handle resume try { stopwatch.Restart(); #region Save resume and Upload var requestResult = RequestFactory.QueryRequest($"http://ihr.zhaopin.com/resumesearch/getresumedetial.do?resumeNo={item.id}_{item.jobNumber}_{item.number}_1_1&resumeSource=3", cookieContainer: cookieContainer); if (!requestResult.IsSuccess) { Trace.TraceWarning(requestResult.ErrorMsg); continue; } var content = JsonConvert.DeserializeObject <dynamic>(requestResult.Data); if ((int)content.code == 6001) // 登录过期 { using (var db = new MangningXssDBEntities()) { var zhaopinStaff = db.ZhaopinStaff.FirstOrDefault(f => f.Id == staff.Id); if (zhaopinStaff != null) { zhaopinStaff.Cookie = null; db.SaveChanges(); dictionary.TryRemove(staff.Id, out companyId); } } Trace.WriteLine($"{DateTime.Now} > Loging Timeout ! Username = {staff.Username}, Message = {content.message}."); isWhile = false; break; } if ((int)content.code != 1) { Trace.WriteLine($"{DateTime.Now} > Get Resume Detail Error ! Username = {staff.Username}, Message = {content.message}."); continue; } var resumeData = content.data; var resumeDetail = JsonConvert.DeserializeObject(resumeData.detialJSonStr.ToString()); var refreshTime = BaseFanctory.GetTime((string)resumeDetail.DateLastReleased).ToUniversalTime(); resumeData.detialJSonStr = resumeDetail; var resumeNumber = ((string)resumeData.resumeNo).Substring(0, 10); var userId = (int)resumeData.userDetials.userMasterId; var resumeId = resumeData.resumeId != null ? (int)resumeData.resumeId : resumeDetail.ResumeId != null ? (int)resumeDetail.ResumeId : 0; var status = "Handle"; using (var db = new MangningXssDBEntities()) { var resume = db.ZhaopinResume.FirstOrDefault(f => f.Id == resumeId); if (!(resume?.RefreshTime != null && resume.RefreshTime.Value.Date >= refreshTime.Date)) { if (resume != null) { resume.RandomNumber = resumeNumber; resume.RefreshTime = refreshTime; resume.UpdateTime = DateTime.UtcNow; if (string.IsNullOrEmpty(resume.UserExtId)) { resume.UserExtId = resumeDetail.UserMasterExtId.ToString(); } resume.Source = !resume.Source.Contains("Deliver") ? resume.Source += ",Deliver" : resume.Source; resume.Flag = 0xE; } else { resume = new ZhaopinResume { Id = resumeId, RandomNumber = resumeNumber, UserId = userId, RefreshTime = refreshTime, UpdateTime = DateTime.UtcNow, UserExtId = resumeDetail.UserMasterExtId.ToString(), DeliveryNumber = null, Source = "Deliver", Flag = 0xE }; db.ZhaopinResume.Add(resume); } var user = db.ZhaopinUser.FirstOrDefault(f => f.Id == userId); if (user != null) { if (!user.Source.Contains("MANUAL")) { user.ModifyTime = BaseFanctory.GetTime((string)resumeDetail.DateModified).ToUniversalTime(); user.CreateTime = BaseFanctory.GetTime((string)resumeDetail.DateCreated).ToUniversalTime(); user.Cellphone = resumeData.userDetials.mobilePhone.ToString(); user.Email = resumeData.userDetials.email.ToString(); user.Name = resumeData.userDetials.userName.ToString(); user.UpdateTime = DateTime.UtcNow; user.Username = resumeData.userDetials.email.ToString(); } } else { user = new ZhaopinUser { Id = userId, Source = "Deliver", ModifyTime = BaseFanctory.GetTime((string)resumeDetail.DateModified).ToUniversalTime(), CreateTime = BaseFanctory.GetTime((string)resumeDetail.DateCreated).ToUniversalTime(), Cellphone = resumeData.userDetials.mobilePhone.ToString(), Email = resumeData.userDetials.email.ToString(), Name = resumeData.userDetials.userName.ToString(), UpdateTime = DateTime.UtcNow, Username = resumeData.userDetials.email.ToString() }; db.ZhaopinUser.Add(user); } var resumeContent = JsonConvert.SerializeObject(resumeData); using (var jsonStream = new MemoryStream(GZip.Compress(Encoding.UTF8.GetBytes(resumeContent)))) { mangningOssClient.PutObject(mangningBucketName, $"Zhaopin/Resume/{resumeId}", jsonStream); } var resumePath = $"{uploadFilePath}{resumeId}.json"; File.WriteAllText(resumePath, JsonConvert.SerializeObject(resumeData)); db.SaveChanges(); } else { status = "NoHandle"; } } #endregion Thread.Sleep(3000); #region SignResume var data = HttpUtility.UrlEncode(JsonConvert.SerializeObject(new { signTag = "noSuit", resumeList = new List <dynamic> { new { resumeNo = $"{item.jobNumber}_{item.number}_{item.version}_1", resumenumber = item.number, item.version, lanType = 1, jobname = ((string)resumeData?.jobName)?.Replace("\"", "\\\"").Replace("\\", "\\\\"), jobno = item.jobNumber, resumesource = item.resumeSource, resumeJobId = item.id, resumerName = ((string)item?.userName).Replace("\r", "").Replace("\n", "").Replace("\"", "\\\""), resumejlName = ((string)item?.name).Replace("\r", "").Replace("\n", "").Replace("\"", "\\'").Replace("\\", "\\\\"), resumerId = item.userId } }, mark = "" })); requestResult = RequestFactory.QueryRequest("https://ihr.zhaopin.com/resumemanage/resumesignstate.do", $"data={data}", RequestEnum.POST, cookieContainer); if (!requestResult.IsSuccess) { Trace.TraceWarning(requestResult.ErrorMsg); continue; } content = JsonConvert.DeserializeObject <dynamic>(requestResult.Data); if ((int)content.code == 6001) // 登录过期 { using (var db = new MangningXssDBEntities()) { var zhaopinStaff = db.ZhaopinStaff.FirstOrDefault(f => f.Id == staff.Id); if (zhaopinStaff != null) { zhaopinStaff.Cookie = null; db.SaveChanges(); dictionary.TryRemove(staff.Id, out companyId); } } Trace.WriteLine($"{DateTime.Now} > Loging Timeout ! Username = {staff.Username}, Message = {content.message}."); isWhile = false; break; } if ((int)content.code != 1) { Trace.WriteLine($"{DateTime.Now} > Sign Resume Error ! Username = {staff.Username}, Message = {content.message}, ResumeId = {resumeId}."); continue; } #endregion stopwatch.Stop(); var elapsed = stopwatch.ElapsedMilliseconds; Interlocked.Increment(ref count); Console.WriteLine($"{DateTime.Now} > {count} {status} {staff.Username}:Unhandled = {--unhandled}, RId = {resumeId}, Elapsed = {elapsed} ms."); } catch (Exception ex) { Trace.TraceError(ex.ToString()); } #endregion } }
public void RequestSpeech(AudioClip audio, GameObject receiver, string callback) { float[] clipData = new float[audio.samples * audio.channels]; audio.GetData(clipData, 0); WaveGen.WaveFormatChunk format = new WaveGen().MakeFormat(audio); try { string filename = GetTempFileName() + ".wav"; FileStream stream = File.OpenWrite(filename); new WaveGen().Write(clipData, format, stream); stream.Close(); Debug.Log("Request Start time: " + DateTime.Now.ToLongTimeString()); if (requestFactory == null) { requestFactory = BuildRequestFactory(RequestFactory.ScopeTypes.Speech); } if (clientToken == null) { clientToken = GetAccessToken(); } if (null != clientToken) { requestFactory.ClientCredential = clientToken; } ATT_MSSDK.Speechv3.SpeechResponse response = SpeechToTextService(filename, "Generic", "audio/wav"); string speechOutput = response.Recognition.NBest[0].ResultText; if (clientToken == null) { clientToken = requestFactory.ClientCredential; SaveAccessToken(); } Debug.Log("Response received time: " + DateTime.Now.ToLongTimeString()); showProcess = false; Debug.Log("response: " + speechOutput); File.Delete(filename); } catch (System.Exception e) { Debug.LogError(e); } }
/// <summary> Gets information about the license for the server's GitLab installation. </summary> /// <returns> A <see cref="RequestResult{GitLabLicense}" /> representing the results of the request. </returns> public async Task <RequestResult <GitLabLicense> > Get() { var request = RequestFactory.Create("license", Method.Get); return(await request.Execute <GitLabLicense>()); }
private void SearchByText(string text) { songPage = null; albumPage = null; artistPage = null; int amount = searchFocus == SearchFocus.Any ? 3 : 10; if (SearchFocus == SearchFocus.Any) { RestClient.ExecuteAsync <CommonSearchResult>(RequestFactory.CommonSearchRequest(text, Page, amount), (r, c) => { if (r.Succeeded()) { var data = r.Data; songPage = data.songResult; albumPage = data.albumResult; artistPage = data.artistResult; ShowSearchResults(); } else { ApplicationViewModel.HandlExceptionResponse(r.ExceptionResponse()); } }); } if (SearchFocus == SearchFocus.Songs) { RestClient.ExecuteAsync <Page <Song> >(RequestFactory.SearchSongsRequest(text, Page, amount), (r, c) => { if (r.Succeeded()) { songPage = r.Data; ShowSearchResults(); } else { ApplicationViewModel.HandlExceptionResponse(r.ExceptionResponse()); } }); /*Response<Page<Song>> response = DataProvider.SearchSongsByTitle(text, Page, amount); * if (!response.Status) * { * ApplicationViewModel.HandleError(response.Error); * return; * } * songPage = response.Content;*/ } if (SearchFocus == SearchFocus.Albums) { RestClient.ExecuteAsync <Page <Album> >(RequestFactory.SearchAlbumsRequest(text, Page, amount), (r, c) => { if (r.Succeeded()) { albumPage = r.Data; ShowSearchResults(); } else { ApplicationViewModel.HandlExceptionResponse(r.ExceptionResponse()); } }); /*Response<Page<Album>> response = DataProvider.SearchAlbumsByName(text, Page, amount); * if (!response.Status) * { * ApplicationViewModel.HandleError(response.Error); * return; * } * albumPage = response.Content;*/ } if (SearchFocus == SearchFocus.Artists) { RestClient.ExecuteAsync <Page <Artist> >(RequestFactory.SearchArtistsRequest(text, Page, amount), (r, c) => { if (r.Succeeded()) { artistPage = r.Data; ShowSearchResults(); } else { ApplicationViewModel.HandlExceptionResponse(r.ExceptionResponse()); } }); /*Response<Page<Artist>> response = DataProvider.SearchArtistsByName(text, Page, amount); * if (!response.Status) * { * ApplicationViewModel.HandleError(response.Error); * return; * } * artistPage = response.Content;*/ } }
/// <summary> /// 登录获取 Cookie /// </summary> /// <param name="email"></param> /// <param name="passWord"></param> /// <param name="host"></param> public static DataResult <CookieContainer> Login(string email, string passWord, string host) { var cookie = new CookieContainer(); var result = new DataResult <CookieContainer>(); var jumpsTimes = 0; Jumps: var param = $"username={email}&password={passWord}&remember=on"; var dataResult = RequestFactory.QueryRequest("http://www.jianlika.com/Index/login.html", param, RequestEnum.POST, cookie, host: host); if (!dataResult.IsSuccess) { result.IsSuccess = false; result.ErrorMsg = $"用户登录异常!异常用户:{email}"; return(result); } var jObject = JsonConvert.DeserializeObject(dataResult.Data) as JObject; if (jObject != null) { if ((int)jObject["status"] != 1) { ++jumpsTimes; if (jumpsTimes < 2) { using (var db = new ResumeMatchDBEntities()) { var user = db.User.FirstOrDefault(f => f.Email == email); if (user != null) { user.IsEnable = false; db.TransactionSaveChanges(); } } result.IsSuccess = false; result.ErrorMsg = $"用户登录异常!异常用户:{email},异常信息:{(string)jObject["message"]}"; return(result); } goto Jumps; } result.Data = cookie; var retryCount = 0; Retry: try { RefreshFreeDownloadNumber(email, cookie, host); } catch (Exception ex) { retryCount++; if (retryCount < 2) { goto Retry; } LogFactory.Error($"刷新简历下载数异常!异常信息:{ex.Message} 堆栈信息:{ex.TargetSite}", MessageSubjectEnum.JianLiKa); } return(result); } return(result); }
/// <summary> /// 激活 /// </summary> /// <returns></returns> private DataResult Activation() { var dataResult = new DataResult(); using (var db = new ResumeRepairDBEntities()) { var list = db.FenJianLi.Where(w => !w.IsActivation).ToList(); if (list.Count == 0) { return(dataResult); } #region 获取未读邮件列表 var seenUids = new List <string>(); var messages = EmailFactory.FetchUnseenMessages("pop.exmail.qq.com", 995, true, Global.Email, Global.PassWord, seenUids); foreach (var userEmail in list) { var message = messages.FirstOrDefault(f => f.message.Headers.To.FirstOrDefault()?.Address == userEmail.Email); if (message == null) { //dataResult.IsSuccess = false; //dataResult.ErrorMsg += $"获取激活邮件失败!,找不到邮件!邮箱地址:{userEmail.Email}"; continue; } var content = Encoding.Default.GetString(message.message.RawMessage); var url = string.Empty; if (Regex.IsMatch(content, "(?s)code=(.+?)</a>")) { url = "http://www.fenjianli.com/register/checkEmailOfCode.htm?code=" + Regex.Match(content, "(?s)code=(.+?)</a>").Result("$1").Substring(2); } var html = RequestFactory.QueryRequest(url); if (!html.Contains("成功")) { dataResult.IsSuccess = false; dataResult.ErrorMsg += $"激活失败!,邮箱地址:{userEmail.Email}{Environment.NewLine}"; continue; } userEmail.IsActivation = true; FenJianLiScheduling.ssf.SetText(FenJianLiScheduling.ssf.fjl_tbx_RegisterActivation, $"激活成功!邮箱:{userEmail.Email}"); if (!EmailFactory.DeleteMessageByMessageId("pop.exmail.qq.com", 995, true, Global.Email, Global.PassWord, message.message.Headers.MessageId)) { FenJianLiScheduling.ssf.SetText(FenJianLiScheduling.ssf.fjl_tbx_RegisterActivation, $"删除激活邮件失败,邮箱地址:{userEmail.Email}"); } } #endregion db.SaveChanges(); } return(dataResult); }
public async Task <HttpResponseMessage> GetSessionAsync(string url, CookieContainer cookieContainer) { return(await HttpProxyServer.SendRequest(RequestFactory.CreateGetRequest(url), cookieContainer)); }
public static List <ResumeComplete> ZhaoPinGou(List <ResumeComplete> list) { Login: lock (lockObj) { if (string.IsNullOrWhiteSpace(signature)) { signature = Login(); } } dynamic param = new { Username = Global.UserName, Signature = signature, ResumeSummaries = new List <object>() }; param.ResumeSummaries.AddRange(list.Select(s => new { ResumeId = s.MatchResumeId, s.ResumeNumber })); for (var i = 0; i < 3; i++) { var dataResult = RequestFactory.QueryRequest(Global.HostChen + "/api/zhaopingou/query", JsonConvert.SerializeObject(param), RequestEnum.POST, contentType: ContentTypeEnum.Json.Description()); using (var db = new ResumeMatchDBEntities()) { if (dataResult.IsSuccess) { var jObject = JsonConvert.DeserializeObject(dataResult.Data) as JObject; if (jObject == null) { continue; } if ((int)jObject["Code"] == 3) { signature = string.Empty; goto Login; } if ((int)jObject["Code"] == 0) { var jArray = jObject["ResumeSummaries"] as JArray; if (jArray == null) { continue; } if (jArray.Count > 0) { Global.TotalMatchSuccess += jArray.Count; Global.TotalDownload += jArray.Count; var matchedResult = jArray.Select(s => new ResumeMatchResult { Cellphone = (string)s["Cellphone"], Email = (string)s["Email"], ResumeNumber = (string)s["ResumeNumber"], Status = 2 }).ToList(); var isPostSuccess = PostResumes(matchedResult); var arr = matchedResult.Select(s => s.ResumeNumber).ToArray(); var resumes = db.ResumeComplete.Where(w => arr.Any(a => a.Equals(w.ResumeNumber))).ToList(); foreach (var resume in resumes) { resume.Status = 6; resume.Cellphone = matchedResult.FirstOrDefault(f => f.ResumeNumber == resume.ResumeNumber)?.Cellphone; resume.Email = matchedResult.FirstOrDefault(f => f.ResumeNumber == resume.ResumeNumber)?.Email; resume.DownloadTime = DateTime.UtcNow; resume.LibraryExist = 1; resume.PostBackStatus = isPostSuccess ? (short)1 : (short)2; LogFactory.Info($"简历库匹配成功!ResumeId:{resume.ResumeId}", MessageSubjectEnum.ZhaoPinGou); } Finish(resumes); list.RemoveAll(r => arr.Any(a => a == r.ResumeNumber)); } var resumesArr = list.Select(s => s.ResumeNumber).ToArray(); var resumeItems = db.ResumeComplete.Where(w => resumesArr.Any(a => a == w.ResumeNumber)).ToList(); foreach (var resume in resumeItems) { resume.LibraryExist = 2; } db.TransactionSaveChanges(); break; } LogFactory.Warn("简历过滤 API 筛选简历异常!异常信息:" + jObject["Message"], MessageSubjectEnum.API); } } } return(list); }
public BaseService() { RequestFactory = new RequestFactory(); }
public DescargaMasivaSATImpl() { _requestFactory = new RequestFactory(); _userAgent = new UserAgent(); }
public object Invoke(CallParameters data) { using (var client = new HttpClient()) { var tuple = MapParametersToUrl(data.Url, data.Parameters); var url = tuple.Item1; var unprocessedParameters = tuple.Item2; var request = new RequestFactory().Create(data.Method, client); client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(data.Accept)); var contentSource = new ObjectContentWriter { Accept = data.Accept, ContentType = data.ContentType }; HttpContent content = null; if (unprocessedParameters.Any()) { content = contentSource.Create(unprocessedParameters.FirstOrDefault().Value); } Task<HttpResponseMessage> response = request.Make(url, content); var result = contentSource.Read(response, data.ReturnType); return result; } }
public async Task <RequestResult <List <Project> > > Owned() { var request = RequestFactory.Create("projects/owned"); return(await request.Execute <List <Project> >()); }
internal AFoxxAdmin(RequestFactory requestFactory, ADatabase connection) { _requestFactory = requestFactory; _connection = connection; }
public void SetUp() { // arrange _factory = new RequestFactory(); }
public UsingDefaultConfigurationWithDummyValueFactory() { this.requestFactory = new RequestFactory(); }
/// <summary> /// Initializes instance members of the <see cref="SMS_App1"/> class. /// </summary> /// <returns>true/false; true if able to read from config file and assigns to instance variables; else false</returns> private bool InitializeValues() { if (this.requestFactory == null) { this.endPoint = ConfigurationManager.AppSettings["endPoint"]; if (string.IsNullOrEmpty(this.endPoint)) { this.DrawPanelForFailure(sendSMSPanel, "endPoint is not defined in configuration file"); return false; } this.shortCode = ConfigurationManager.AppSettings["short_code"]; if (string.IsNullOrEmpty(this.shortCode)) { this.DrawPanelForFailure(sendSMSPanel, "short_code is not defined in configuration file"); return false; } this.apiKey = ConfigurationManager.AppSettings["api_key"]; if (string.IsNullOrEmpty(this.apiKey)) { this.DrawPanelForFailure(sendSMSPanel, "api_key is not defined in configuration file"); return false; } this.secretKey = ConfigurationManager.AppSettings["secret_key"]; if (string.IsNullOrEmpty(this.secretKey)) { this.DrawPanelForFailure(sendSMSPanel, "secret_key is not defined in configuration file"); return false; } List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.SMS); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); } return true; }
/// <summary> /// Initializes local variables with values from config file and creates requestFactory object /// </summary> private void Initialize() { if (this.requestFactory == null) { this.apiKey = ConfigurationManager.AppSettings["api_key"]; if (string.IsNullOrEmpty(this.apiKey)) { this.DrawPanelForFailure(sendMessagePanel, "api_key is not defined in configuration file"); return; } this.secretKey = ConfigurationManager.AppSettings["secret_key"]; if (string.IsNullOrEmpty(this.secretKey)) { this.DrawPanelForFailure(sendMessagePanel, "secret_key is not defined in configuration file"); return; } this.endPoint = ConfigurationManager.AppSettings["endPoint"]; if (string.IsNullOrEmpty(this.endPoint)) { this.DrawPanelForFailure(sendMessagePanel, "endPoint is not defined in configuration file"); return; } this.mmsAttachments = new List<string>(); List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.MMS); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); } }
/// <summary> /// This method will be called during loading the page /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">event arguments</param> protected void Page_Load(object sender, EventArgs e) { lblServerTime.Text = DateTime.UtcNow.ToString("ddd MMM dd yyyy hh:mm:ss tt", CultureInfo.InvariantCulture) + " UTC"; if ((Request["signed_payload"] != null) && (Request["signed_signature"] != null) && (Request["goBackURL"] != null) && (Request["signed_request"] != null)) { signPayLoadButton.Text = "Back"; requestText.Text = Request["signed_request"]; SignedPayLoadTextBox.Text = Request["signed_payload"]; SignatureTextBox.Text = Request["signed_signature"]; this.goBackURL = Request["goBackURL"]; } else if ((Request["request_to_sign"] != null) && (Request["goBackURL"] != null) && (Request["api_key"] != null) && (Request["secret_key"] != null)) { this.payLoadStringFromRequest = Request["request_to_sign"]; this.goBackURL = Request["goBackURL"]; SignedPayLoadTextBox.Text = this.payLoadStringFromRequest; this.apiKey = Request["api_key"]; this.secretKey = Request["secret_key"]; this.requestFactory = null; this.endPoint = ConfigurationManager.AppSettings["endpoint"]; List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.Payment); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); this.ExecuteSignedPayloadFromRequest(); } else { if (ConfigurationManager.AppSettings["paymentType"] == null) { this.DrawPanelForFailure(notaryPanel, "paymentType is not defined in configuration file"); return; } this.paymentType = ConfigurationManager.AppSettings["paymentType"]; if (this.paymentType.Equals("Transaction", StringComparison.OrdinalIgnoreCase)) { this.ReadTransactionParametersFromConfigurationFile(); } else if (this.paymentType.Equals("Subscription", StringComparison.OrdinalIgnoreCase)) { if (!Page.IsPostBack) { this.ReadTransactionParametersFromConfigurationFile(); this.ReadSubscriptionParametersFromConfigurationFile(); } } else { this.DrawPanelForFailure(notaryPanel, "paymentType is defined with invalid value in configuration file. Valid values are Transaction or Subscription."); return; } if (!Page.IsPostBack) { string payLoadString = "{'Amount':'" + this.amount.ToString() + "','Category':'" + this.category.ToString() + "','Channel':'" + this.channel + "','Description':'" + this.description + "','MerchantTransactionId':'" + this.merchantTransactionId + "','MerchantProductId':'" + this.merchantProductId + "','MerchantApplicaitonId':'" + this.merchantApplicationId + "','MerchantPaymentRedirectUrl':'" + this.merchantRedirectURI.ToString() + "','MerchantSubscriptionIdList':'" + this.merchantSubscriptionIdList + "','IsPurchaseOnNoActiveSubscription':'" + this.isPurchaseOnNoActiveSubscription + "','SubscriptionRecurringNumber':'" + this.subscriptionRecurringNumber.ToString() + "','SubscriptionRecurringPeriod':'" + this.subscriptionRecurringPeriod + "','SubscriptionRecurringPeriodAmount':'" + this.subscriptionRecurringPeriodAmount.ToString(); requestText.Text = payLoadString; } } }
/// <summary> /// Initialize a new instance of RequestFactory. /// </summary> private void InitializeRequestFactory() { List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.IMMN); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, this.redirectUrl, null); if (null != Session["CSMOBO_ACCESS_TOKEN"]) { this.requestFactory.AuthorizeCredential = (OAuthToken)Session["CSMOBO_ACCESS_TOKEN"]; } }
private RequestFactory BuildRequestFactory(RequestFactory.ScopeTypes scope) { List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(scope); return new RequestFactory(endpoint, apiKey, secretKey, scopes, null, null); }
/// <summary> /// Read from config and initialize RequestFactory object /// </summary> /// <returns>true/false; true - if able to read from config file; else false</returns> private bool ReadConfigAndInitialize() { this.apiKey = ConfigurationManager.AppSettings["apiKey"]; if (string.IsNullOrEmpty(this.apiKey)) { this.DrawPanelForFailure(statusPanel, "apiKey is not defined in the config file"); return false; } this.secretKey = ConfigurationManager.AppSettings["secretKey"]; if (string.IsNullOrEmpty(this.secretKey)) { this.DrawPanelForFailure(statusPanel, "secretKey is not defined in the config file"); return false; } this.endPoint = ConfigurationManager.AppSettings["endpoint"]; if (string.IsNullOrEmpty(this.endPoint)) { this.DrawPanelForFailure(statusPanel, "endpoint is not defined in the config file"); return false; } List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.Speech); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); this.commonXArg = ConfigurationManager.AppSettings["X-Arg"]; this.xArgTVContext = ConfigurationManager.AppSettings["X-ArgTVContext"]; this.xArgSocialMediaContext = ConfigurationManager.AppSettings["X-ArgSocialMedia"]; return true; }
protected override IRequest ConstructRequest(Uri uri, string method, Dictionary <string, object> parameters, bool signed) { var uriString = uri.ToString(); if (!signed && parameters != null) { if (!uriString.EndsWith("?")) { uriString += "?"; } uriString += $"{string.Join("&", parameters.Select(s => $"{s.Key}={s.Value}"))}"; } var request = RequestFactory.Create(uriString); request.Method = method; request.ContentType = "application/json"; request.Accept = "application/json"; if (!signed) { return(request); } if (uri.ToString().Contains("v2")) { if (parameters == null) { parameters = new Dictionary <string, object>(); } var json = JsonConvert.SerializeObject(parameters); var data = Encoding.UTF8.GetBytes(json); var n = nonce; var signature = $"/api{uri.PathAndQuery}{n}{json}"; var signedData = authProvider.Sign(signature); request.Headers.Add($"bfx-nonce: {n}"); request.Headers.Add($"bfx-apikey: {authProvider.Credentials.Key}"); request.Headers.Add($"bfx-signature: {signedData.ToLower()}"); using (var stream = request.GetRequestStream().Result) stream.Write(data, 0, data.Length); } else { var path = uri.PathAndQuery; var n = nonce; var signature = new JObject { ["request"] = path, ["nonce"] = n }; if (parameters != null) { foreach (var keyvalue in parameters) { signature.Add(keyvalue.Key, JToken.FromObject(keyvalue.Value)); } } var payload = Convert.ToBase64String(Encoding.ASCII.GetBytes(signature.ToString())); var signedData = authProvider.Sign(payload); request.Headers.Add($"X-BFX-APIKEY: {authProvider.Credentials.Key}"); request.Headers.Add($"X-BFX-PAYLOAD: {payload}"); request.Headers.Add($"X-BFX-SIGNATURE: {signedData.ToLower()}"); } return(request); }
internal DocumentCreate(RequestFactory requestFactory, ACollection <T> collection, IJsonSerializer jsonSerializer) { _requestFactory = requestFactory; _collection = collection; _jsonSerializer = jsonSerializer; }
/// <summary> /// Instantiate RequestFactory of ATT_MSSDK by passing endPoint, apiKey, secretKey, scopes /// </summary> /// <returns>true/false; true if able to read else false</returns> private bool Initialize() { if (this.requestFactory == null) { this.apiKey = ConfigurationManager.AppSettings["api_key"]; if (string.IsNullOrEmpty(this.apiKey)) { this.DrawPanelForFailure(sendMMSPanel, "api_key is not defined in configuration file"); return false; } this.secretKey = ConfigurationManager.AppSettings["secret_key"]; if (string.IsNullOrEmpty(this.secretKey)) { this.DrawPanelForFailure(sendMMSPanel, "secret_key is not defined in configuration file"); return false; } this.endPoint = ConfigurationManager.AppSettings["endPoint"]; if (string.IsNullOrEmpty(this.endPoint)) { this.DrawPanelForFailure(sendMMSPanel, "endPoint is not defined in configuration file"); return false; } this.messageFilePath = ConfigurationManager.AppSettings["messageFilePath"]; if (string.IsNullOrEmpty(this.messageFilePath)) { this.DrawPanelForFailure(sendMMSPanel, "Message file path is missing in configuration file"); return false; } this.phoneListFilePath = ConfigurationManager.AppSettings["phoneListFilePath"]; if (string.IsNullOrEmpty(this.phoneListFilePath)) { this.DrawPanelForFailure(sendMMSPanel, "Phone list file path is missing in configuration file"); return false; } this.couponFilePath = ConfigurationManager.AppSettings["couponFilePath"]; if (string.IsNullOrEmpty(this.couponFilePath)) { this.DrawPanelForFailure(sendMMSPanel, "Coupon file name is missing in configuration file"); return false; } List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.MMS); this.mmsAddressList = new List<string>(); this.mmsAttachments = new List<string>(); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); } return true; }
public void Setup() { targetBaseUrl = _restConfiguration.Hostname; thermoDataRequester = RequestFactory.CreateRestService(targetBaseUrl, _stoppingToken, _logger); _messageSender = MessageBusServiceFactory.CreateServiceBusMessageSender(_serviceBusConfiguration, _logger); }
/// <summary> /// Reads from config file and assigns to local variables /// </summary> /// <returns>true/false; true if all required parameters are specified, else false</returns> private bool ReadConfigFile() { this.endPoint = ConfigurationManager.AppSettings["endPoint"]; if (string.IsNullOrEmpty(this.endPoint)) { this.DrawPanelForFailure(tlPanel, "endPoint is not defined in configuration file"); return false; } this.apiKey = ConfigurationManager.AppSettings["api_key"]; if (string.IsNullOrEmpty(this.apiKey)) { this.DrawPanelForFailure(tlPanel, "api_key is not defined in configuration file"); return false; } this.secretKey = ConfigurationManager.AppSettings["secret_key"]; if (string.IsNullOrEmpty(this.secretKey)) { this.DrawPanelForFailure(tlPanel, "secret_key is not defined in configuration file"); return false; } this.authorizeRedirectUri = ConfigurationManager.AppSettings["authorize_redirect_uri"]; if (string.IsNullOrEmpty(this.authorizeRedirectUri)) { this.DrawPanelForFailure(tlPanel, "authorize_redirect_uri is not defined in configuration file"); return false; } List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.TerminalLocation); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, this.authorizeRedirectUri, null); if (null != Session["CSTL_ACCESS_TOKEN"]) { this.requestFactory.AuthorizeCredential = (OAuthToken)Session["CSTL_ACCESS_TOKEN"]; } return true; }
/// <summary> /// Creates a <see cref="SubscriptionRequest"/>. /// </summary> /// <param name="paymentMethodToken"> /// The payment method token. /// </param> /// <param name="planId"> /// The plan id. /// </param> /// <param name="trialDuration"> /// The trial duration. /// </param> /// <param name="trialDurationUnit"> /// The trial duration unit. /// </param> /// <param name="addTrialPeriod"> /// The add trial period. /// </param> /// <returns> /// The <see cref="Attempt{Subscription}"/>. /// </returns> public Attempt <Subscription> Create(string paymentMethodToken, string planId, int trialDuration, SubscriptionDurationUnit trialDurationUnit, bool addTrialPeriod = false) { return(Create(RequestFactory.CreateSubscriptionRequest(paymentMethodToken, planId, trialDuration, trialDurationUnit, addTrialPeriod))); }
public RequestHandler(RequestFactory request_factory, FrontController front_controller) { this.request_factory = request_factory; this.front_controller = front_controller; }
/// <summary> /// Creates a <see cref="SubscriptionRequest"/>. /// </summary> /// <param name="paymentMethodToken"> /// The payment method token. /// </param> /// <param name="planId"> /// The plan id. /// </param> /// <param name="firstBillingDate"> /// The first billing date. /// </param> /// <returns> /// The <see cref="SubscriptionRequest"/>. /// </returns> public Attempt <Subscription> Create(string paymentMethodToken, string planId, DateTime firstBillingDate) { return(Create(RequestFactory.CreateSubscriptionRequest(paymentMethodToken, planId, firstBillingDate))); }
/// <summary> /// Instantiate RequestFactory of ATT_MSSDK by passing endPoint, apiKey, secretKey, scopes /// scope should contain Payment as RequestFactory.ScopeTypes /// </summary> /// <returns>Returns Boolean</returns> private bool Initialize() { this.MinTransactionAmount = ConfigurationManager.AppSettings["MinTransactionAmount"]; if (string.IsNullOrEmpty(this.MinTransactionAmount)) { this.MinTransactionAmount = "0.00"; } lstMinAmount.Text = "Buy product 1 for $" + this.MinTransactionAmount; this.MaxTransactionAmount = ConfigurationManager.AppSettings["MaxTransactionAmount"]; if (string.IsNullOrEmpty(this.MaxTransactionAmount)) { this.MaxTransactionAmount = "2.99"; } lstMaxAmount.Text = "Buy product 2 for $" + this.MaxTransactionAmount; if (this.requestFactory == null) { this.apiKey = ConfigurationManager.AppSettings["api_key"]; if (string.IsNullOrEmpty(this.apiKey)) { this.DrawPanelForFailure(newTransactionPanel, "api_key is not defined in configuration file."); return false; } this.secretKey = ConfigurationManager.AppSettings["secret_key"]; if (string.IsNullOrEmpty(this.secretKey)) { this.DrawPanelForFailure(newTransactionPanel, "secret_key is not defined in configuration file."); return false; } this.endPoint = ConfigurationManager.AppSettings["endpoint"]; if (string.IsNullOrEmpty(this.endPoint)) { this.DrawPanelForFailure(newTransactionPanel, "endpoint is not defined in configuration file."); return false; } this.merchantRedirectURI = ConfigurationManager.AppSettings["MerchantPaymentRedirectUrl"]; if (string.IsNullOrEmpty(this.merchantRedirectURI)) { this.DrawPanelForFailure(newTransactionPanel, "MerchantPaymentRedirectUrl is not defined in configuration file"); return false; } this.notificationDetailsFile = ConfigurationManager.AppSettings["notificationFilePath"]; if (string.IsNullOrEmpty(this.notificationDetailsFile)) { this.notificationDetailsFile = "Xmlnotification.txt"; } this.refundFilePath = ConfigurationManager.AppSettings["refundFilePath"]; if (string.IsNullOrEmpty(this.refundFilePath)) { this.refundFilePath = "refund.txt"; } if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["noOfNotificationsToDisplay"])) { this.noOfNotificationsToDisplay = 5; } else { this.noOfNotificationsToDisplay = Convert.ToInt32(ConfigurationManager.AppSettings["noOfNotificationsToDisplay"]); } if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["refundCountToDisplay"])) { this.refundCountToDisplay = 5; } else { this.refundCountToDisplay = Convert.ToInt32(ConfigurationManager.AppSettings["refundCountToDisplay"]); } this.refundList = new List<KeyValuePair<string, string>>(); this.latestFive = true; List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.Payment); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); } return true; }
/// <summary> /// Creates a <see cref="SubscriptionRequest"/>. /// </summary> /// <param name="paymentMethodToken"> /// The payment method token. /// </param> /// <param name="planId"> /// The plan id. /// </param> /// <param name="price"> /// An optional price used to override the plan price. /// </param> /// <returns> /// The <see cref="Attempt{Subscription}"/>. /// </returns> public Attempt <Subscription> Create(string paymentMethodToken, string planId, decimal?price = null) { return(Create(RequestFactory.CreateSubscriptionRequest(paymentMethodToken, planId, price))); }
/// <summary> /// Initializes instance variables from Config file /// </summary> /// <returns>true/false; true if able to read from config file and able to instantiate values; else false</returns> private bool Initialize() { this.apiKey = ConfigurationManager.AppSettings["api_key"]; if (string.IsNullOrEmpty(this.apiKey)) { this.DrawPanelForFailure(newSubscriptionPanel, "api_key is not defined in config file"); return false; } this.secretKey = ConfigurationManager.AppSettings["secret_key"]; if (string.IsNullOrEmpty(this.secretKey)) { this.DrawPanelForFailure(newSubscriptionPanel, "secret_key is not defined in config file"); return false; } this.endPoint = ConfigurationManager.AppSettings["endpoint"]; if (string.IsNullOrEmpty(this.endPoint)) { this.DrawPanelForFailure(newSubscriptionPanel, "endPoint is not defined in config file"); return false; } this.merchantRedirectURI = ConfigurationManager.AppSettings["MerchantPaymentRedirectUrl"]; if (string.IsNullOrEmpty(this.merchantRedirectURI)) { this.DrawPanelForFailure(newSubscriptionPanel, "MerchantPaymentRedirectUrl is not defined in config file"); return false; } this.refundFilePath = ConfigurationManager.AppSettings["subscriptionRefundFilePath"]; if (string.IsNullOrEmpty(this.refundFilePath)) { this.refundFilePath = "subscriptionRefund.txt"; } this.subscriptionDetailsFilePath = ConfigurationManager.AppSettings["subscriptionDetailsFilePath"]; if (string.IsNullOrEmpty(this.subscriptionDetailsFilePath)) { this.subscriptionDetailsFilePath = Request.MapPath("subscriptionDetails.txt"); } else { this.subscriptionDetailsFilePath = Request.MapPath(this.subscriptionDetailsFilePath); } this.notificationDetailsFile = ConfigurationManager.AppSettings["notificationFilePath"]; if (string.IsNullOrEmpty(this.notificationDetailsFile)) { this.notificationDetailsFile = "notificationDetails.txt"; } this.noOfNotificationsToDisplay = 5; if (ConfigurationManager.AppSettings["notificationCountToDisplay"] != null) { this.noOfNotificationsToDisplay = Convert.ToInt32(ConfigurationManager.AppSettings["notificationCountToDisplay"]); } this.subsDetailsCountToDisplay = 5; if (ConfigurationManager.AppSettings["subsDetailsCountToDisplay"] != null) { this.subsDetailsCountToDisplay = Convert.ToInt32(ConfigurationManager.AppSettings["subsDetailsCountToDisplay"]); } List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.Payment); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); return true; }
/// <summary> /// Read from config and initialize RequestFactory object /// </summary> /// <returns>true/false; true - if able to read from config file; else false</returns> private bool ReadConfigAndInitialize() { this.apiKey = ConfigurationManager.AppSettings["apiKey"]; if (string.IsNullOrEmpty(this.apiKey)) { this.DrawPanelForFailure(statusPanel, "apiKey is not defined in the config file"); return false; } this.secretKey = ConfigurationManager.AppSettings["secretKey"]; if (string.IsNullOrEmpty(this.secretKey)) { this.DrawPanelForFailure(statusPanel, "secretKey is not defined in the config file"); return false; } this.endPoint = ConfigurationManager.AppSettings["endpoint"]; if (string.IsNullOrEmpty(this.endPoint)) { this.DrawPanelForFailure(statusPanel, "endpoint is not defined in the config file"); return false; } if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["SpeechFilesDir"])) { this.SpeechFilesDir = Request.MapPath(ConfigurationManager.AppSettings["SpeechFilesDir"]); } this.xArgData = ConfigurationManager.AppSettings["X-Arg"]; this.grammarFilePath = ConfigurationManager.AppSettings["X-Grammar"]; this.dictionaryFilePath = ConfigurationManager.AppSettings["X-Dictionary"]; txtXArgs.Text = this.xArgData.Replace(",", "," + Environment.NewLine); if (!Page.IsPostBack) { string speechContxt = ConfigurationManager.AppSettings["SpeechContext"]; if (!string.IsNullOrEmpty(speechContxt)) { string[] speechContexts = speechContxt.Split(';'); foreach (string speechContext in speechContexts) { ddlSpeechContext.Items.Add(speechContext); } if (ddlSpeechContext.Items.Count > 0) { ddlSpeechContext.Items[0].Selected = true; } } if (!string.IsNullOrEmpty(SpeechFilesDir)) { string[] filePaths = Directory.GetFiles(this.SpeechFilesDir); foreach (string filePath in filePaths) { ddlAudioFile.Items.Add(Path.GetFileName(filePath)); } if (filePaths.Length > 0) { ddlAudioFile.Items[0].Selected = true; } } } List<RequestFactory.ScopeTypes> scopes = new List<RequestFactory.ScopeTypes>(); scopes.Add(RequestFactory.ScopeTypes.STTC); this.requestFactory = new RequestFactory(this.endPoint, this.apiKey, this.secretKey, scopes, null, null); return true; }