public async Task<IHttpActionResult> Send(ApiRequest apiRequest)
        {
            try
            {
                var typeInformation = new RequestTypeInformation(apiRequest);

                var result = JsonConvert.DeserializeObject(apiRequest.RequestJson, typeInformation.RequestType,
                    new EnumerationConverter());

                var response = await mediator.SendAsync(result, typeInformation.ResponseType);
                return Ok(response);
            }
            catch (AuthenticationException ex)
            {
                logger.Error(ex, "Authentication error");
                return this.StatusCode(HttpStatusCode.Unauthorized, new HttpError(ex, includeErrorDetail: true));
            }
            catch (SecurityException ex)
            {
                logger.Error(ex, "Authorization error");
                return this.StatusCode(HttpStatusCode.Forbidden, new HttpError(ex, includeErrorDetail: true));
            }
            catch (RequestAuthorizationException ex)
            {
                logger.Error(ex, "Request authorization error");
                return this.StatusCode(HttpStatusCode.Forbidden, new HttpError(ex, includeErrorDetail: true));
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Unhandled error");
                throw;
            }
        }
        protected ApiRequest BuildAccessTokenRequest(string authorizationCode, string redirectUri)
        {
            if (string.IsNullOrWhiteSpace(ClientId))
            {
                throw new InvalidOperationException("Authorization.ClientId should be a non-null, non-whitespace string");
            }
            if (string.IsNullOrWhiteSpace(ClientSecret))
            {
                throw new InvalidOperationException(
                    "Authorization.ClientSecret should be a non-null, non-whitespace string");
            }
            if (string.IsNullOrWhiteSpace(authorizationCode))
            {
                throw new ArgumentException("authorizationCode should be a non-null, non-whitespace string");
            }
            if (string.IsNullOrWhiteSpace(redirectUri))
            {
                throw new ArgumentException("redirectUri should be a valid Uri");
            }

            var request = new ApiRequest(ClientId, ClientSecret);
            request.Method = Method.POST;
            request.Path = Endpoints.AccessToken;
            SetAccessTokenQueryParams(request, authorizationCode, redirectUri);

            return request;
        }
        public IApiRequest AuthorizedRequest(string accessToken, Method method, string endpoint, IDictionary<string, string> urlSubstitutions = null, IParameterProvider additionalParameters = null)
        {
            // Verify the provided parameters at least have a chance of succeeding, otherwise, exit early via exception...
            VerifyAccessToken(accessToken);
            VerifyParameters(additionalParameters);

            // Generate a basic request...
            ApiRequest request = new ApiRequest(accessToken);
            request.Method = method;
            request.Path = endpoint;

            // Add url parameters if they are present...
            if (urlSubstitutions != null)
            {
                foreach (var item in urlSubstitutions)
                {
                    request.UrlSegments.Add(item);
                }
            }

            // Add query or body parameters if present...
            if (additionalParameters != null)
            {
                foreach (var parameter in additionalParameters.GetParameterValues())
                {
                    request.Query.Add(parameter);
                }
            }

            return request;
        }
        /// <summary>
        /// Returns a summary of per-user access information for all students in a course. This includes total page views, total participations, and a breakdown of on-time/late status for all homework submissions in the course. The data is returned as a list in lexical order on the student name.
        /// Each student's summary also includes the maximum number of page views and participations by any student in the course, which may be useful for some visualizations (since determining maximums client side can be tricky with pagination).
        /// </summary>
        /// <param name="courseId">The ID of the course.</param>
        /// <returns></returns>
        public async Task<IEnumerable<StudentSummary>> GetStudentSummaries(string courseId)
        {
            courseId.ThrowIfNull("courseId");

            var request = new ApiRequest(_config.CoursesEndpointUri, courseId + "/analytics/student_summaries");
            return await GetReponseAsync<IEnumerable<StudentSummary>>(request).ConfigureAwait(false);
        }
        /// <summary>
        /// Returns page view hits and participation numbers grouped by day through the entire history of the course.
        /// </summary>
        /// <param name="courseId">The ID of the course.</param>
        /// <returns></returns>
        public async Task<IEnumerable<CourseParticipation>> GetCourseParticipations(string courseId)
        {
            courseId.ThrowIfNull("courseId");

            var request = new ApiRequest(_config.CoursesEndpointUri, courseId + "/analytics/activity");
            return await GetReponseAsync<IEnumerable<CourseParticipation>>(request).ConfigureAwait(false);
        }
        /// <summary>
        /// Performs a HTTP "DELETE" request to Delete a Field.
        /// API Request: DELETE /v2/fields/{fieldId}
        /// Important: This API has a lower rate limit than the rest of the API platform. This API's limit is 1 request per second.
        /// </summary>
        /// <param name="fieldId">The ID of the Field that you used when you created it.</param>
        /// <returns></returns>
        public async Task DeleteFieldByIdAsync(string fieldId) {
            var request = new ApiRequest<Field>(ApiConnection);
            string uri = BaseUrl + FieldModel.FIELDS_ENDPOINT + fieldId;

            var deletedField = await request.MakeApiCall("DELETE", uri, null);

        }
        public async Task QueueTask_MultipleThreads_OrderedResponse()
        {
            /*** Arrange ***/
            int numTasks = 1000;

            int count = 0;

            // Increments the access token each time a call is made to the API
            _handler.Setup(h => h.ExecuteAsync<OAuth2Session>(It.IsAny<IApiRequest>()))
                .Returns(() => Task.FromResult<IApiResponse<OAuth2Session>>(new ApiResponse<OAuth2Session>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = "{\"access_token\": \"" + count + "\",\"expires_in\": 3600,\"token_type\": \"bearer\",\"refresh_token\": \"J7rxTiWOHMoSC1isKZKBZWizoRXjkQzig5C6jFgCVJ9bUnsUfGMinKBDLZWP9BgR\"}"
                })).Callback(() => System.Threading.Interlocked.Increment(ref count));

            /*** Act ***/
            IApiRequest request = new ApiRequest(new Uri("http://example.com"), "folders");

            List<Task<IApiResponse<OAuth2Session>>> tasks = new List<Task<IApiResponse<OAuth2Session>>>();
            for (int i = 0; i < numTasks; i++)
                tasks.Add(_service.EnqueueAsync<OAuth2Session>(request));

            await Task.WhenAll(tasks);

            /*** Assert ***/
            for (int i = 0; i < numTasks; i++)
            {
                OAuth2Session session = _converter.Parse<OAuth2Session>(tasks[i].Result.ContentString);
                Assert.AreEqual(session.AccessToken, i.ToString());
            }
        }
        /// <summary>
        /// Get a user profile for the indicated SIS Login ID. This method only applies for institutions using SIS Import to load data into Canvas.
        /// </summary>
        /// <param name="sisLoginId">The SIS Login ID of the user</param>
        /// <returns></returns>
        public async Task<User> GetBySisLoginId(string sisLoginId)
        {
            sisLoginId.ThrowIfNullOrWhiteSpace("sisLoginId");

            var request = new ApiRequest(_config.UsersEndpointUri, string.Format("sis_login_id:{0}/profile",sisLoginId));
            return await GetReponseAsync<User>(request).ConfigureAwait(false);
        }
示例#9
0
 public static Gw2StatsMatchEntry GetGw2StatsMatchEntry(bool objectives = false, bool ratings = false, bool ignoreCache = true)
 {
     var parser = new Gw2StatsMatchEntryParser();
     ApiRequest request = new ApiRequest(Constants.gw2_matches);
     request.AddParameter("objectives", objectives ? "true" : "false");
     request.AddParameter("ratings", ratings ? "true" : "false");
     return GwApi.HandleRequest(request, parser, Network, ignoreCache);
 }
        /// <summary>
        /// Returns a list of assignments for the course sorted by due date. For each assignment returns basic assignment information, the grade breakdown (including the student's actual grade), and the basic submission information for the student's submission if it exists.
        /// </summary>
        /// <param name="courseId">The ID of the course.</param>
        /// <param name="studentId">The ID of the student.</param>
        /// <returns></returns>
        public async Task<IEnumerable<StudentAssignment>> GetStudentAssignments(string courseId, string studentId)
        {
            courseId.ThrowIfNull("courseId");
            studentId.ThrowIfNull("studentId");

            var request = new ApiRequest(_config.CoursesEndpointUri, courseId + "/analytics/users/" + studentId + "/assignments");
            return await GetReponseAsync<IEnumerable<StudentAssignment>>(request).ConfigureAwait(false);
        }
        public void ShouldReturnListOfLanguages()
        {
            ApiRequest apiRequest = new ApiRequest(requestSettings);

              var languages = apiRequest.GetLanguages();

              Assert.AreEqual(5, languages.Count);
        }
        /// <summary>
        /// Performs a HTTP "POST" request to Create a Field.
        /// </summary>
        /// <returns></returns>
        public async Task CreateFieldPostRequestAsync() {
            var fieldPayload = new Field();
            string uri = BaseUrl + FieldModel.FIELDS_ENDPOINT;
            fieldPayload = fieldPayload.BuildRandomField();

            var postRequest = new ApiRequest<Field>(ApiConnection);
            await postRequest.MakeApiCall("POST", uri, fieldPayload);
        }
        /// <summary>
        /// Get a user profile for the indicated user ID.
        /// </summary>
        /// <param name="id">The ID of the user. Defaults to the user represented by the current OAuth2 token.</param>
        /// <returns></returns>
        public async Task<User> Get(long? id = null)
        {
            if (id.HasValue) id.Value.ThrowIfUnassigned("id");

            var userId = id.HasValue ? id.Value.ToString() : "self";
            var request = new ApiRequest(_config.UsersEndpointUri, userId + "/profile");
            return await GetReponseAsync<User>(request).ConfigureAwait(false);
        }
            public void ShouldReturnAListOfMessages()
            {
                ApiRequest apiRequest = new ApiRequest(requestSettings);
                int profileId = 280976;

                ProfileMessageCollection collection = apiRequest.GetMessageCollection(profileId);

                Assert.AreEqual(2, collection.threads.Length);
            }
        public void ShouldReturnAListOfCountries()
        {
            ApiRequest request = new ApiRequest(requestSettings);

              var countries = request.GetCountries();

              Assert.IsNotNull(countries);
              Assert.AreEqual(230, countries.Count);
        }
            public void ShouldCheckIfAccountDoesntExists()
            {
                string username = "******";

                ApiRequest apiRequest = new ApiRequest(requestSettings);

                var exists = apiRequest.GetProfileExists(username);

                Assert.AreEqual(false, exists);
            }
            public void ShouldCheckIfAccountExists()
            {
                string username = "******";

                ApiRequest apiRequest = new ApiRequest(requestSettings);

                var exists = apiRequest.GetProfileExists(username);

                Assert.AreEqual(true, exists);
            }
示例#18
0
 public static StatusCodeDescriptions GetGw2StatsStatusCodes(bool ignoreCache = false)
 {
     var parser = new Gw2StatsStatusCodeParser();
     ApiRequest request = new ApiRequest(Constants.gw2_status_codes);
     var codes = GwApi.HandleRequest(request, parser, Network, ignoreCache);
     _statusCodes = _statusCodes ?? new StatusCodeDescriptions();
     _statusCodes.Clear();
     _statusCodes.AddRange(codes);
     return codes;
 }
            public void ShouldReturn2UnreadMessageCount()
            {
                ApiRequest apiRequest = new ApiRequest(requestSettings);

                int profileId = 280976;

                ProfileUnreadMessage unread = apiRequest.GetUnreadMessages(profileId);

                Assert.AreEqual(1, unread.UnreadMessages);
            }
示例#20
0
 public static Gw2StatsObjectives GetGw2StatsObjectives(Gw2StatsObjectives.ObjectiveType type, string id,
                                                    bool ignoreCache = true)
 {
     var parser = new Gw2StatsObjectivesParser(type);
     ApiRequest request = new ApiRequest(Constants.gw2_objectives);
     request.AddParameter("type", type.ToString().ToLower());
     if (type != Gw2StatsObjectives.ObjectiveType.All)
         request.AddParameter("id", id);
     return GwApi.HandleRequest(request, parser, Network, ignoreCache);
 }
            public void ShouldReturnAMessageThread()
            {
                ApiRequest apiRequest = new ApiRequest(requestSettings);
                int profileId = 280976;
                int targetProfileId = 324317;

                MessageThread thread = apiRequest.GetMessageThread(profileId, targetProfileId);

                Assert.IsNotNull(thread);
                Assert.AreEqual(2, thread.TotalMessageCount);
            }
            public void ShouldReturnAListOfFavourites()
            {
                int profileId = 324784;

                ApiRequest request = new ApiRequest(requestSettings);

                var result = request.GetFavourites(profileId);

                Assert.IsNotNull(result);
                Assert.AreEqual(1, result.Count);
            }
            public void ShouldGenerateEmailVerificationCode()
            {
                int profileId = 324784;
                string email = "";

                IApiRequest apiRequest = new ApiRequest(requestSettings);

                var verifcationCode = apiRequest.GetEmailVerificationCode(profileId, email);

                Assert.IsNotNull(verifcationCode);
                Assert.AreEqual(email, verifcationCode.Email);
            }
            public RequestTypeInformation(ApiRequest apiRequest)
            {
                RequestType = Type.GetType(apiRequest.TypeName);

                if (RequestType == null)
                {
                    throw new InvalidOperationException(
                        "The passed type name could not be resolved to a type! Type name: " + apiRequest.TypeName);
                }

                ResponseType = RequestType.GetInterfaces()[0].GenericTypeArguments[0];
            }
        /// <summary>
        /// Performs a HTTP "GET" request to obtain information about an individual Field.
        /// API Request: GET /v2/fields/{fieldId}
        /// </summary>
        /// <param name="fieldId">The ID of the Field that you used when you created it.</param>
        /// <returns></returns>
        public async Task GetFieldByIdAsync(string fieldId) {
            var request = new ApiRequest<Field>(ApiConnection);
            string uri = BaseUrl + FieldModel.FIELDS_ENDPOINT + fieldId;

            var singleFieldModel = await request.MakeApiCall("GET", uri, null);

            if (singleFieldModel != null) {
                Menus.PrintBlankSpace(3);
                Menus.DrawCenteredTitle(String.Format("You requested information about {0}. Here are the results:", fieldId));

                Menus.WriteLineCentered(String.Format("The Field ID is {0}, the Field Name is {1}. Acres: {2} Farm ID: {3} Location: {4}", singleFieldModel.id, singleFieldModel.name, singleFieldModel.acres, singleFieldModel.farmId, singleFieldModel.centerPoint.ToString()));
            }
        }
            public void ShouldGeneratePhoneVerificationCode()
            {
                int profileId = 324784;
                string countryCode = "";
                string phoneNumber = "";

                IApiRequest apiRequest = new ApiRequest(requestSettings);

                var verificationResponse = apiRequest.GetPhoneVerificationCode(profileId, countryCode, phoneNumber);

                Assert.IsNotNull(verificationResponse);
                Assert.AreEqual(countryCode, verificationResponse.CountryCode);
            }
示例#27
0
        public object Get(ApiRequest request)
        {
            string username = "";
            string password = "";
            bool unattended_auth = false;

            if (!string.IsNullOrEmpty (request.Username) &&
                !string.IsNullOrEmpty (request.Password)) {
                unattended_auth = true;
                username = request.Username;
                password = request.Password;
            }

            // if the user sends oauth data, we look for an oauth token
            // and checks if is valid. If so, we provide the right user-ref url
            if (Request.Headers.AllKeys.Contains ("Authorization")) {
                var auth_header = Request.Headers["Authorization"];
                var splits = auth_header.Split (new string[] { "oauth_token=\"" }, StringSplitOptions.None);
                var next_quote = splits[1].IndexOf("\"");
                var token_string = splits[1].Substring(0, next_quote);
                var token = RainyStandaloneServer.OAuth.AccessTokens.GetToken (token_string);
                username = token.UserName;
            }

            Logger.Debug ("ApiRequest received");
            var response = new DTO.ApiResponse ();
            var baseUri = ((HttpListenerRequest)this.Request.OriginalRequest).Url;
            string baseUrl = baseUri.Scheme + "://" + baseUri.Authority + "/";

            // should only be set if authenticated
            response.UserRef = new DTO.ContentRef () {
                ApiRef = baseUrl + "api/1.0/" + username,
                Href = baseUrl + username
            };

            response.ApiVersion = "1.0";
            string oauthBaseUrl = baseUrl + "oauth/";
            response.OAuthRequestTokenUrl = oauthBaseUrl + "request_token";
            response.OAuthAccessTokenUrl = oauthBaseUrl + "access_token";

            if (unattended_auth)
                response.OAuthAuthorizeUrl = oauthBaseUrl + "authorize/"
                    + username + "/"
                    + password + "/";
            else
                response.OAuthAuthorizeUrl = oauthBaseUrl + "authorize/";

            return response;
        }
示例#28
0
		public async Task<JsonValue> get(ApiRequest requestType, Dictionary<string, string> data, int timeOut){
			var httpClient = new HttpClient(){
				Timeout = TimeSpan.FromMilliseconds(3000)


			};
			string url;
            string method;
			switch(requestType){
			case ApiRequest.FIND_MOVIE:
				url = "http://www.omdbapi.com/";
                method = "GET";
                break;
			case ApiRequest.MOVIE_DATA:
				url = "http://www.omdbapi.com/";
                method = "GET";
                break;
			default:
				url = "";
                method = "GET";
                break;
			}

			try{
				HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri (url + buildParams(data)));
				request.ContentType = "application/json";
				request.Method = method;

				// Send the request to the server and wait for the response:
				using (WebResponse response = await request.GetResponseAsync ())
				{
					// Get a stream representation of the HTTP web response:
					using (Stream stream = response.GetResponseStream ())
					{
						// Use this stream to build a JSON document object:
						JsonValue jsonDoc = await Task.Run (() => JsonObject.Load (stream));
						Console.Out.WriteLine("Response: {0}", jsonDoc.ToString ());
						// Return the JSON document:
						return JsonValue.Parse(jsonDoc.ToString()) ;
					}
				}
			}catch(HttpRequestException e){
				//oops		
				return null;
			}finally{				
				Thread.Sleep (timeOut);
			}
		}
示例#29
0
        private async void searchBtn_Click_1(object sender, RoutedEventArgs e)
        {
            try
                {
                    var searchRequest = new ApiRequest("user/search");
                    searchRequest.Authenticated = true;
                    searchRequest.Parameters.Add("search", queryTxtBox.Text);
                    results = await searchRequest.ExecuteAsync<IList<User>>();
                    itemGridView.ItemsSource = results;
                    itemListView.ItemsSource = results;
                }
                catch (Exception ex)
                {

                }
        }
        protected override ApiRequest ParseRequestInfo(IDictionary<string,string> groups, Tenant t)
        {
            var callInfo = new ApiRequest("community/" + groups["type"])
                {
                    Parameters = new List<RequestParameter>
                        {
                            new RequestParameter("content", new HtmlContentResolver()),
                            new RequestParameter("title", new TitleResolver(BlogTagsResolver.Pattern)),
                            new RequestParameter("subscribeComments", true),
                            new RequestParameter("type", 1),
                            new RequestParameter("tags", new BlogTagsResolver())
                        }
                };

            return callInfo;
        }
示例#31
0
        public void HandleCheckInCurrentBook(ApiRequest request)
        {
            Action <float> reportCheckinProgress = (fraction) =>
            {
                dynamic messageBundle = new DynamicJson();
                messageBundle.fraction = fraction;
                _socketServer.SendBundle("checkinProgress", "progress", messageBundle);
                // The status panel is supposed to be showing a progress bar in response to getting the bundle,
                // but since we're doing the checkin on the UI thread, it doesn't get painted without this.
                Application.DoEvents();
            };

            try
            {
                // Right before calling this API, the status panel makes a change that
                // should make the progress bar visible. But this method is running on
                // the UI thread so without this call it won't appear until later, when
                // we have Application.DoEvents() as part of reporting progress. We do
                // quite a bit on large books before the first file is written to the
                // zip, so one more DoEvents() here lets the bar appear at once.
                Application.DoEvents();
                _bookSelection.CurrentSelection.Save();
                if (!_tcManager.CheckConnection())
                {
                    request.Failed();
                    return;
                }

                var bookName = Path.GetFileName(_bookSelection.CurrentSelection.FolderPath);
                if (_tcManager.CurrentCollection.OkToCheckIn(bookName))
                {
                    // review: not super happy about this being here in the api. Was stymied by
                    // PutBook not knowing about the actual book object, but maybe that could be passed in.
                    // It's important that this is done BEFORE the checkin: we want other users to see the
                    // comment, and NOT see the pending comment as if it was their own if they check out.
                    var message = BookHistory.GetPendingCheckinMessage(_bookSelection.CurrentSelection);
                    BookHistory.AddEvent(_bookSelection.CurrentSelection, BookHistoryEventType.CheckIn, message);
                    BookHistory.SetPendingCheckinMessage(_bookSelection.CurrentSelection, "");
                    _tcManager.CurrentCollection.PutBook(_bookSelection.CurrentSelection.FolderPath, true, false, reportCheckinProgress);
                    reportCheckinProgress(0);                     // hides the progress bar (important if a different book has been selected that is still checked out)

                    Analytics.Track("TeamCollectionCheckinBook",
                                    new Dictionary <string, string>()
                    {
                        { "CollectionId", _settings?.CollectionId },
                        { "CollectionName", _settings?.CollectionName },
                        { "Backend", _tcManager?.CurrentCollection?.GetBackendType() },
                        { "User", CurrentUser },
                        { "BookId", _bookSelection?.CurrentSelection.ID },
                        { "BookName", _bookSelection?.CurrentSelection.Title }
                    });
                }
                else
                {
                    // We can't check in! The system has broken down...perhaps conflicting checkouts while offline.
                    // Save our version in Lost-and-Found
                    _tcManager.CurrentCollection.PutBook(_bookSelection.CurrentSelection.FolderPath, false, true, reportCheckinProgress);
                    reportCheckinProgress(0);                     // cleans up panel for next time
                    // overwrite it with the current repo version.
                    _tcManager.CurrentCollection.CopyBookFromRepoToLocal(bookName, dialogOnError: true);
                    // Force a full reload of the book from disk and update the UI to match.
                    _bookSelection.SelectBook(_bookServer.GetBookFromBookInfo(_bookSelection.CurrentSelection.BookInfo, true));
                    var msg = LocalizationManager.GetString("TeamCollection.ConflictingEditOrCheckout",
                                                            "Someone else has edited this book or checked it out even though you were editing it! Your changes have been saved to Lost and Found");
                    ErrorReport.NotifyUserOfProblem(msg);
                    Analytics.Track("TeamCollectionConflictingEditOrCheckout",
                                    new Dictionary <string, string>()
                    {
                        { "CollectionId", _settings?.CollectionId },
                        { "CollectionName", _settings?.CollectionName },
                        { "Backend", _tcManager?.CurrentCollection?.GetBackendType() },
                        { "User", CurrentUser },
                        { "BookId", _bookSelection?.CurrentSelection?.ID },
                        { "BookName", _bookSelection?.CurrentSelection?.Title }
                    });
                }
                UpdateUiForBook();
                request.PostSucceeded();

                Application.Idle += OnIdleConnectionCheck;
            }
            catch (Exception e)
            {
                reportCheckinProgress(0);                 // cleans up panel progress indicator
                var msgId      = "TeamCollection.ErrorCheckingBookIn";
                var msgEnglish = "Error checking in {0}: {1}";
                var log        = _tcManager?.CurrentCollection?.MessageLog;
                // Pushing an error into the log will show the Reload Collection button. It's not obvious this
                // is useful here, since we don't know exactly what went wrong. However, it at least gives the user
                // the option to try it.
                if (log != null)
                {
                    log.WriteMessage(MessageAndMilestoneType.Error, msgId, msgEnglish, _bookSelection?.CurrentSelection?.FolderPath, e.Message);
                }
                Logger.WriteError(String.Format(msgEnglish, _bookSelection?.CurrentSelection?.FolderPath, e.Message), e);
                NonFatalProblem.ReportSentryOnly(e, $"Something went wrong for {request.LocalPath()} ({_bookSelection?.CurrentSelection?.FolderPath})");
                request.Failed("checkin failed");
            }
        }
示例#32
0
        /// <summary>
        /// Get all indexes.
        /// </summary>
        /// <returns></returns>
        public Task <IApiResponse <IEnumerable <Index> > > GetIndexesAsync()
        {
            var request = new ApiRequest("indexes", HttpMethod.Get);

            return(_connection.Execute(request, IndexList.GetIndexes));
        }
示例#33
0
 public void Init()
 {
     Api = new ApiRequest(Apikey);
 }
示例#34
0
        public JObject SaveOrUpdateCallHistory(string callId, string parentCallId, string answeredBy = null, DateTime?queueDate = null,
                                               DateTime?answerDate = null, DateTime?endDialDate = null, string recordUrl = null, string recordDuration = null, decimal?price = null)
        {
            try
            {
                var request = new ApiRequest(string.Format("crm/voip/callhistory/{0}", callId), Cookie)
                {
                    Method       = HttpMethod.Post,
                    ResponseType = ResponseType.Json
                };

                request.Parameters.Add(new RequestParameter {
                    Name = "parentCallId", Value = parentCallId
                });

                if (!string.IsNullOrEmpty(answeredBy))
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "answeredBy", Value = answeredBy
                    });
                }

                if (queueDate.HasValue)
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "queueDate", Value = queueDate.Value
                    });
                }

                if (answerDate.HasValue)
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "answerDate", Value = answerDate.Value
                    });
                }

                if (endDialDate.HasValue)
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "endDialDate", Value = endDialDate.Value
                    });
                }

                if (!string.IsNullOrEmpty(recordUrl))
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "recordUrl", Value = recordUrl
                    });
                }

                if (!string.IsNullOrEmpty(recordDuration))
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "recordDuration", Value = recordDuration
                    });
                }

                if (price.HasValue)
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "price", Value = price.Value.ToString(CultureInfo.InvariantCulture)
                    });
                }

                return(JObject.Parse(ApiClient.GetResponse(request).Response));
            }
            catch (ApiErrorException e)
            {
                Log.ErrorFormat("SaveOrUpdateCallHistory: StackTrace:{0}, Message: {1}", e.ErrorStackTrace, e.ErrorMessage);
            }
            catch (Exception e)
            {
                Log.ErrorFormat("SaveOrUpdateCallHistory: StackTrace:{0}, Message: {1}", e.StackTrace, e.Message);
            }

            return(new JObject());
        }
示例#35
0
 public AirtimeDataService()
 {
     _apiService = new ApiRequest();
 }
        public override void DoProcessRequest(HttpContext context)
        {
            Exception error = null;

            try
            {
                // Set response headers
                context.Response.ContentType     = "application/json";
                context.Response.ContentEncoding = Encoding.UTF8;

                // Notify 'request begins' to extensions
                Extensions.OnRequestAction(new ApiExtensionResponseData {
                    action = context.Request.HttpMethod, context = "BEGIN", data = null
                });

                // Extract request parts via an ApiRequest wrapper
                ApiRequest request      = new ApiRequest(context);
                bool       isDatasetAPI = request.IsDatasetApi;
                string     methodName   = request.MethodName;

                // Enable GZip Compression if client support it
                AddGZipCompression(context, request.AcceptGZip);

                switch (context.Request.HttpMethod)
                {
                case "GET":
                case "POST":
                {
                    switch (methodName)
                    {
                    case "getembeddedreporturl":
                    {
                        // Notify Extensions
                        {
                            var args = new Dictionary <string, string>()
                            {
                                { "reportId", context.Request["reportId"] },
                                { "payload", context.Request["payload"] },
                            };

                            // Notify method call to extensions
                            Extensions.OnRequestAction(new ApiExtensionResponseData {
                                        action = "GetEmbeddedReportUrl", context = "BEFORE_CALL", data = JsonConvert.SerializeObject(args)
                                    });
                        }

                        var result = JsonGOReportsHelperService.GetEmbeddedReportUrl(String.IsNullOrEmpty(context.Request["reportId"]) ? Guid.Empty : Guid.Parse(context.Request["reportId"]), String.IsNullOrEmpty(context.Request["payload"]) ? null : Convert.ToString(context.Request["payload"]));

                        // Seralise result, if not already json encoded string
                        string json = result;

                        if (!IsJson(result))
                        {
                            json = JsonConvert.SerializeObject(result, GetSerializationSettings(false));
                        }

                        // Notify result to extensions
                        Extensions.OnRequestAction(new ApiExtensionResponseData {
                                    action = "GetEmbeddedReportUrl", context = "JSON", data = json
                                });

                        WriteResponse(context, json);
                    }
                    break;

                    default:
                        _logEngine.LogError("Unknown json method: " + methodName, "Unknown json method: " + methodName, "JsonGOReportsHelperServiceHandler", null);
                        throw new PulpException("Unknow json method: " + methodName);
                    }
                }
                break;

                case "OPTIONS":
                    return;

                default:
                    throw new InvalidOperationException("Invalid Verb " + context.Request.HttpMethod);
                }
            }
            catch (Exception exception)
            {
                error = exception;

                // Notify to extensions and re-throw
                Extensions.OnRequestAction(new ApiExtensionResponseData {
                    action = "EXCEPTION", context = exception.GetType().Name, data = exception.ToString(), error = true
                });
                throw;
            }
            finally
            {
                // Check no transaction left running
                DatabaseTransaction.AbortAnyOngoingTransaction(error);
            }
        }
示例#37
0
        public ActionResult Index()
        {
            var model = new ApiRequest();

            return(View(model));
        }
示例#38
0
        /// <summary>
        /// Gets an application
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="credentials"></param>
        /// <returns></returns>
        public static AppResponse Get(string appId, Credentials credentials = null)
        {
            var response = ApiRequest.DoRequest(ApiRequest.GetBaseUriFor(typeof(ApplicationV2), $"/v2/applications/{appId}"), credentials);

            return(JsonConvert.DeserializeObject <AppResponse>(response));
        }
示例#39
0
        public async void Start_Call_Action(string type)
        {
            try
            {
                if (type == "call")
                {
                    DurationTextView.Text = GetText(Resource.String.Lbl_Calling);
                    var apiStartCall = await ApiRequest.Create_Agora_Call_Event_Async(UserId, "audio");

                    if (apiStartCall != null && !string.IsNullOrEmpty(apiStartCall.RoomName) && !string.IsNullOrEmpty(apiStartCall.Id))
                    {
                        if (!string.IsNullOrEmpty(apiStartCall.RoomName))
                        {
                            RoomName = apiStartCall.RoomName;
                        }
                        if (!string.IsNullOrEmpty(apiStartCall.Id))
                        {
                            CallId = apiStartCall.Id;
                        }
                        Methods.AudioRecorderAndPlayer.PlayAudioFromAsset("mystic_call.mp3", "left");

                        TimerRequestWaiter          = new Timer();
                        TimerRequestWaiter.Interval = 5000;
                        TimerRequestWaiter.Elapsed += TimerCallRequestAnswer_Waiter_Elapsed;
                        TimerRequestWaiter.Start();
                        InitAgoraEngineAndJoinChannel(RoomName); //the caller Is Joining agora Server
                    }
                }
                else
                {
                    RoomName = Intent?.GetStringExtra("room_name");
                    CallId   = Intent?.GetStringExtra("CallID");
                    DurationTextView.Text = GetText(Resource.String.Lbl_Waiting_to_connect);

                    var apiStartCall = await ApiRequest.Send_Agora_Call_Action_Async("answer", CallId);

                    if (apiStartCall == "200")
                    {
                        var ckd = GlobalContext?.LastCallsTab?.MAdapter?.MCallUser?.FirstOrDefault(a => a.Id == CallId); // id >> Call_Id
                        if (ckd == null)
                        {
                            Classes.CallUser cv = new Classes.CallUser
                            {
                                Id        = CallId,
                                UserId    = UserId,
                                Avatar    = Avatar,
                                Name      = Name,
                                FromId    = FromId,
                                Active    = Active,
                                Time      = "Answered call",
                                Status    = Status,
                                RoomName  = RoomName,
                                Type      = CallType,
                                TypeIcon  = "Accept",
                                TypeColor = "#008000"
                            };

                            GlobalContext?.LastCallsTab?.MAdapter?.Insert(cv);

                            SqLiteDatabase dbDatabase = new SqLiteDatabase();
                            dbDatabase.Insert_CallUser(cv);
                        }
                        InitAgoraEngineAndJoinChannel(RoomName); //the caller Is Joining agora Server
                    }
                    else
                    {
                        var ckd = GlobalContext?.LastCallsTab?.MAdapter?.MCallUser?.FirstOrDefault(a => a.Id == CallId); // id >> Call_Id
                        if (ckd == null)
                        {
                            Classes.CallUser cv = new Classes.CallUser
                            {
                                Id        = CallId,
                                UserId    = UserId,
                                Avatar    = Avatar,
                                Name      = Name,
                                FromId    = FromId,
                                Active    = Active,
                                Time      = "Missed call",
                                Status    = Status,
                                RoomName  = RoomName,
                                Type      = CallType,
                                TypeIcon  = "Cancel",
                                TypeColor = "#FF0000"
                            };

                            GlobalContext?.LastCallsTab?.MAdapter?.Insert(cv);

                            SqLiteDatabase dbDatabase = new SqLiteDatabase();
                            dbDatabase.Insert_CallUser(cv);
                        }

                        DurationTextView.Text = GetText(Resource.String.Lbl_Faild_to_connect);
                    }
                }
            }
            catch (Exception e)
            {
                Methods.DisplayReportResultTrack(e);
            }
        }
示例#40
0
        private async void TimerCallRequestAnswer_Waiter_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                var callResultGeneration = await ApiRequest.Check_Agora_Call_Answer_Async(CallId, "audio");

                if (string.IsNullOrEmpty(callResultGeneration))
                {
                    return;
                }

                if (callResultGeneration == "answered")
                {
                    TimerRequestWaiter.Enabled = false;
                    TimerRequestWaiter.Stop();
                    TimerRequestWaiter.Close();

                    RunOnUiThread(() =>
                    {
                        Methods.AudioRecorderAndPlayer.StopAudioFromAsset();
                        InitAgoraEngineAndJoinChannel(RoomName);
                    });

                    var ckd = GlobalContext?.LastCallsTab?.MAdapter?.MCallUser?.FirstOrDefault(a => a.Id == CallId); // id >> Call_Id
                    if (ckd == null)
                    {
                        Classes.CallUser cv = new Classes.CallUser
                        {
                            Id        = CallId,
                            UserId    = UserId,
                            Avatar    = Avatar,
                            Name      = Name,
                            FromId    = FromId,
                            Active    = Active,
                            Time      = "Answered call",
                            Status    = Status,
                            RoomName  = RoomName,
                            Type      = CallType,
                            TypeIcon  = "Accept",
                            TypeColor = "#008000"
                        };

                        GlobalContext?.LastCallsTab?.MAdapter?.Insert(cv);

                        SqLiteDatabase dbDatabase = new SqLiteDatabase();
                        dbDatabase.Insert_CallUser(cv);
                    }
                }
                else if (callResultGeneration == "calling")
                {
                    if (CountSecoundsOfOutgoingCall < 80)
                    {
                        CountSecoundsOfOutgoingCall += 10;
                    }
                    else
                    {
                        //Call Is inactive
                        TimerRequestWaiter.Enabled = false;
                        TimerRequestWaiter.Stop();
                        TimerRequestWaiter.Close();

                        RunOnUiThread(OnCallTime_Running_Out);
                    }
                }
                else if (callResultGeneration == "declined")
                {
                    TimerRequestWaiter.Enabled = false;
                    TimerRequestWaiter.Stop();
                    TimerRequestWaiter.Close();

                    RunOnUiThread(OnCall_Declined_From_User);

                    var ckd = GlobalContext?.LastCallsTab?.MAdapter?.MCallUser?.FirstOrDefault(a => a.Id == CallId); // id >> Call_Id
                    if (ckd == null)
                    {
                        Classes.CallUser cv = new Classes.CallUser
                        {
                            Id        = CallId,
                            UserId    = UserId,
                            Avatar    = Avatar,
                            Name      = Name,
                            FromId    = FromId,
                            Active    = Active,
                            Time      = "Declined call",
                            Status    = Status,
                            RoomName  = RoomName,
                            Type      = CallType,
                            TypeIcon  = "Declined",
                            TypeColor = "#FF8000"
                        };

                        GlobalContext?.LastCallsTab?.MAdapter?.Insert(cv);

                        SqLiteDatabase dbDatabase = new SqLiteDatabase();
                        dbDatabase.Insert_CallUser(cv);
                    }
                }
                else if (callResultGeneration == "no_answer")
                {
                    //Call Is inactive
                    TimerRequestWaiter.Enabled = false;
                    TimerRequestWaiter.Stop();
                    TimerRequestWaiter.Close();

                    RunOnUiThread(OnCallTime_Running_Out);
                }
            }
            catch (Exception exception)
            {
                Methods.DisplayReportResultTrack(exception);
            }
        }
示例#41
0
        private void HandleEndRecord(ApiRequest request)
        {
            if (Recorder.RecordingState != RecordingState.Recording)
            {
                //usually, this is a result of us getting the "end" before we actually started, because it was too quick
                if (TestForTooShortAndSendFailIfSo(request))
                {
                    _startRecordingTimer.Enabled = false;                    //we don't want it firing in a few milliseconds from now
                    return;
                }
                if (RecordingDevice == null && Recorder.RecordingState == RecordingState.NotYetStarted)
                {
                    // We've already complained about no recording device, no need to complain about not recording.
                    request.PostSucceeded();
                    return;
                }

                //but this would handle it if there was some other reason
                request.Failed("Got endRecording, but was not recording");
                return;
            }

            Exception exceptionCaught = null;

            try
            {
                // We never want this thread blocked, but we want to block HandleAudioFileRequest()
                // until Recorder_Stopped() succeeds.
                _completingRecording.Reset();
                Debug.WriteLine("Stop recording");
                Recorder.Stopped += Recorder_Stopped;
                //note, this doesn't actually stop... more like... starts the stopping. It does mark the time
                //we requested to stop. A few seconds later (2, looking at the library code today), it will
                //actually close the file and raise the Stopped event
                Recorder.Stop();
            }
            catch (Exception ex)
            {
                // Swallow the exception for now. One reason (based on HearThis comment) is that the user
                // didn't hold the record button down long enough, we detect this below.
                exceptionCaught   = ex;
                Recorder.Stopped -= Recorder_Stopped;
                Debug.WriteLine("Error stopping recording: " + ex.Message);
            }
            if (TestForTooShortAndSendFailIfSo(request))
            {
                _completingRecording.Set();                 // not saving a recording, so don't block HandleAudioFileRequest
                return;
            }
            else if (exceptionCaught != null)
            {
                ResetRecorderOnError();
                _completingRecording.Set();                 // not saving a recording, so don't block HandleAudioFileRequest
                request.Failed("Stopping the recording caught an exception: " + exceptionCaught.Message);
            }
            else
            {
                // Report success now that we're sure we succeeded.
                request.PostSucceeded();
            }
        }
示例#42
0
 /// <summary>
 /// Official Method Name: List of Campus Printer
 /// Description: This method returns a list of printer on campus
 /// Update Frequency: When updated by pull request
 /// All the above information is from the Official Documentation
 /// </summary>
 public ApiRequest <List <ListOfCampusPrinter> > ListOfCampusPrinter()
 {
     return(ApiRequest <List <ListOfCampusPrinter> > .CreateApiRequest("/resources/printers", _apiKey));
 }
示例#43
0
 /// <summary>
 /// Official Method Name: List of coop infosessions
 /// Description: This method returns a list of campus employer infosessions
 /// Update Frequency: When updated by pull request
 /// All the above information is from the Official Documentation
 /// </summary>
 public ApiRequest <List <ListOfCoopInfosessions> > ListOfCoopInfosessions()
 {
     return(ApiRequest <List <ListOfCoopInfosessions> > .CreateApiRequest("/resources/infosessions", _apiKey));
 }
 public IApiResponse Post(ApiRequest request)
 {
     return(new Ok(new { Status = 2, Message = "This is working.", User = request.User }));
 }
示例#45
0
        public async Task <ActionResult> List(PageInationInfo pagination, Condtions condtions, string view = "")
        {
            #region Pager

            //if (pagination == null) pagination = new PageInationInfo();
            //if (pager.HasValue) pagination.Index = pager.Value;
            //pagination.Index = Index;
            //pagination.Size = Size;
            //pagination.Total = Total;
            //int lastPage = pagination.Total / pagination.Size;
            //if ((pagination.Total % pagination.Size) != 0) lastPage += 1;
            //if (pager == "first") pagination.Index = 1;
            //if (pager == "prev" && pagination.Index > 1) pagination.Index -= 1;
            //if (pager == "next" && ((pagination.Index + 1) <= lastPage)) pagination.Index += 1;
            //if (pager == "last") pagination.Index = lastPage;
            //if (!string.IsNullOrEmpty(pager) && pager.StartsWith("page"))
            //{
            //    pagination.Index = Convert.ToInt32(pager.Replace("page", ""));
            //}

            #endregion
            {
                #region 取資料

                //var biz = new teresa.business.TestBiz.Master();
                var request = new ApiRequest
                {
                    pagination = pagination,
                    condtions  = condtions
                };
                var biz      = new ApiBiz();
                var response = await biz.Post <ApiResponse>("http://localhost/API/api/", "test", "load", request);

                //DataTable dt = biz.Load(ref pagination, Condtions: condtions);

                #region 註解
                //Linq
                //List<TestMasterInfo> model = new List<TestMasterInfo>();
                //if (dt != null && dt.Rows.Count > 0)
                //{
                //    model =
                //    dt.AsEnumerable()
                //    .Select(i => new TestMasterInfo
                //    {
                //        SID = i.Field<int>("SID"),
                //        ID = i.Field<string>("ID"),
                //        NO = i.Field<string>("NO"),
                //        Name = i.Field<string>("Name"),
                //        Address = i.Field<string>("Address"),
                //        Phone = i.Field<string>("Phone"),
                //        Age = i.Field<decimal?>("Age"),
                //        Birthday = i.Field<DateTime?>("Birthday"),
                //        CreateTime = i.Field<DateTime>("CreateTime"),
                //        UpdaueTime = i.Field<DateTime>("UpdaueTime")
                //    })
                //    .ToList();
                //}
                #endregion
                #endregion 註解尾

                #region ViewBag
                //ViewBag.Index = pagination.Index;
                //ViewBag.Size = pagination.Size;
                //ViewBag.Total = pagination.Total;
                //ViewBag.ConditonName = condtions.Name;
                ViewBag.condtions = response.condtions;
                ViewBag.Pager     = response.pagination;
                #endregion

                //return View(model);

                string path = "~/Views/Shared/Test/_List.cshtml";
                if (!string.IsNullOrEmpty(view))
                {
                    path = $"~/Views/Shared/Test/_List_{view}.cshtml";
                }

                return(PartialView(path, response.data));
            }
        }
示例#46
0
        /// <summary>
        /// Create a new application
        /// </summary>
        /// <param name="request">Application request</param>
        /// <param name="credentials">(Optional) Overridden credentials for only this request</param>
        /// <returns></returns>
        public static AppResponse Create(AppRequest request, Credentials credentials = null)
        {
            var response = VersionedApiRequest.DoRequest("POST", ApiRequest.GetBaseUriFor(typeof(ApplicationV2), "/v2/applications"), request, credentials);

            return(JsonConvert.DeserializeObject <AppResponse>(response.JsonResponse));
        }
示例#47
0
 public async Task AddApiRequestAsync(ApiRequest apiRequest)
 {
     _context.ApiRequests.Add(apiRequest);
     await _context.SaveChangesAsync();
 }
示例#48
0
        /// <summary>
        /// Get Http response from third party API.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="client"></param>
        /// <param name="apiRequest"></param>
        /// <returns></returns>
        private async Task <HttpResponseMessage> GetHttpResponseAsync(HttpClient client, ApiRequest apiRequest)
        {
            Enum.TryParse(apiRequest.Method.ToUpper(), out HttpVerbs methodUpper);
            switch (methodUpper)
            {
            default:
                return(await client.GetAsync(apiRequest.Url));

            case HttpVerbs.POST:
            case HttpVerbs.PUT:
                var request = new StringContent(apiRequest.Body, Encoding.UTF8, apiRequest.ContentType);
                if (methodUpper == HttpVerbs.POST)
                {
                    return(await client.PostAsync(apiRequest.Url, request));
                }

                return(await client.PutAsync(apiRequest.Url, request));

            case HttpVerbs.DELETE:
                return(await client.DeleteAsync(apiRequest.Url));
            }
        }
示例#49
0
 protected void SetAccessTokenQueryParams(ApiRequest request, string authorizationCode, string redirectUri)
 {
     request.Query.Add("grant_type", "authorization_code");
     request.Query.Add("code", authorizationCode);
     request.Query.Add("redirect_uri", redirectUri);
 }
        public async Task <string> SignUp(string nickName, string email, string password)
        {
            if (Configuration == null)
            {
                throw new GameServiceException("You Must Configuration First").LogException(
                          typeof(LoginOrSignUpProvider),
                          DebugLocation.Internal, "SignUp");
            }

            if (!await NetworkUtil.IsConnected())
            {
                throw new GameServiceException("Network Unreachable").LogException(typeof(LoginOrSignUpProvider),
                                                                                   DebugLocation.Internal, "SignUp");
            }

            if (string.IsNullOrEmpty(nickName))
            {
                throw new GameServiceException("NickName Cant Be EmptyOrNull").LogException(
                          typeof(LoginOrSignUpProvider),
                          DebugLocation.Internal, "SignUp");
            }

            if (string.IsNullOrEmpty(email))
            {
                throw new GameServiceException("Email Cant Be EmptyOrNull").LogException(typeof(LoginOrSignUpProvider),
                                                                                         DebugLocation.Internal, "SignUp");
            }

            if (string.IsNullOrEmpty(password))
            {
                throw new GameServiceException("Password Cant Be EmptyOrNull").LogException(
                          typeof(LoginOrSignUpProvider),
                          DebugLocation.Internal, "SignUp");
            }

            if (GameService.IsAuthenticated() || _doingLogin)
            {
                throw new GameServiceException("You Must Logout For Re-Login").LogException(
                          typeof(LoginOrSignUpProvider),
                          DebugLocation.Internal, "SignUp");
            }

            _doingLogin = true;

            try
            {
                var login = await ApiRequest.SignUp(nickName, email, password);

                GameService.UserToken = login.Token;
                var auth = await ApiRequest.Authorize();

                GameService.CommandInfo         = auth.CommandInfo;
                GameService.PlayToken           = auth.Token;
                GameService.CurrentInternalGame = auth.Game;
                GameService.IsAvailable         = true;
                GameService.IsGuest             = false;
            }
            finally
            {
                _doingLogin = false;
            }

            GameService.GSLive.Init();

            return(GameService.UserToken);
        }
示例#51
0
        public JObject SaveOrUpdateCall(string callId, string from = null, string to             = null, string answeredBy = null,
                                        string dialDuration        = null, string recordUrl      = null,
                                        string recordDuration      = null, VoipCallStatus?status = null,
                                        string contactId           = null, decimal?price = null)
        {
            try
            {
                var request = new ApiRequest(string.Format("crm/voip/call/{0}", callId), Cookie)
                {
                    Method       = HttpMethod.Post,
                    ResponseType = ResponseType.Json
                };

                if (!string.IsNullOrEmpty(from))
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "from", Value = from
                    });
                }

                if (!string.IsNullOrEmpty(to))
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "to", Value = to
                    });
                }

                if (status != null)
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "status", Value = status.Value
                    });
                }

                if (!string.IsNullOrEmpty(dialDuration))
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "dialDuration", Value = dialDuration
                    });
                }

                if (!string.IsNullOrEmpty(recordUrl))
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "recordUrl", Value = recordUrl
                    });
                }

                if (!string.IsNullOrEmpty(recordDuration))
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "recordDuration", Value = recordDuration
                    });
                }

                if (!string.IsNullOrEmpty(answeredBy))
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "answeredBy", Value = answeredBy
                    });
                }

                if (!string.IsNullOrEmpty(contactId))
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "contactId", Value = contactId
                    });
                }

                if (price.HasValue)
                {
                    request.Parameters.Add(new RequestParameter {
                        Name = "price", Value = price.Value.ToString(CultureInfo.InvariantCulture)
                    });
                }

                return(JObject.Parse(ApiClient.GetResponse(request).Response));
            }
            catch (ApiErrorException e)
            {
                Log.ErrorFormat("SaveOrUpdateCall: StackTrace:{0}, Message: {1}", e.ErrorStackTrace, e.ErrorMessage);
                throw;
            }
        }
示例#52
0
        public ActionResult List()
        {
            var data = ApiRequest.Get <List <BookingLibrary.UI.Models.LogItemViewModel> >($"{_apiGatewayUrl}/api/commandLogs");

            return(View(data));
        }
示例#53
0
 public static void Initialize(ControllerContext currentContext)
 {
     apiRequest  = new ApiRequest <AreaModel>(currentContext);
     userRequest = new ApiRequest <UserLookupModel>(currentContext);
 }
示例#54
0
 public Command(Client client, ApiRequest apiRequest) : base(client.Credentials, apiRequest)
 {
     this.requiredFields = new List <string> {
         "mocean-api-key", "mocean-api-secret", "mocean-command"
     };
 }
示例#55
0
 /// <summary>
 /// Search for messages that have been rejected by Nexmo. Messages rejected by carrier do not appear.
 /// </summary>
 /// <param name="request">Search request with numbers</param>
 /// <param name="creds">(Optional) Overridden credentials for only this request</param>
 /// <returns></returns>
 public static Messages <MessageBase> GetRejections(SearchRequest request, Credentials creds = null)
 {
     return(ApiRequest.DoGetRequestWithQueryParameters <Messages <MessageBase> >(ApiRequest.GetBaseUriFor(typeof(Search), "/search/rejections"), ApiRequest.AuthType.Query, request, creds));
 }
示例#56
0
 public SendCode(Client client, ApiRequest apiRequest) : base(client.Credentials, apiRequest)
 {
     this.requiredFields = new List <string> {
         "mocean-api-key", "mocean-api-secret", "mocean-to", "mocean-brand"
     };
 }
示例#57
0
 /// <summary>
 /// Official Method Name: List of student tutors available
 /// Description: This method returns a list of all the tutors available to help for a course for a given term
 /// Update Frequency: As the data updates by SSO
 /// All the above information is from the Official Documentation
 /// </summary>
 public ApiRequest <List <ListOfStudentTutorsAvailable> > ListOfStudentTutorsAvailable()
 {
     return(ApiRequest <List <ListOfStudentTutorsAvailable> > .CreateApiRequest("/resources/tutors", _apiKey));
 }
示例#58
0
        public void HandleStartRecording(ApiRequest request)
        {
            // Precondition: HandleStartRecording shouldn't run until the previous HandleEndRecord() is completely done with PathToRecordableAudioForCurrentSegment
            //   Unfortunately this is not as easy to ensure on the code side due to HandleStartRecord() not being able to be moved off the UI thread, and deadlock potential
            //   I found it too difficult to actually violate this precondition from the user side.
            //   Therefore, I just assume this to be true.

            if (Recording)
            {
                request.Failed("Already recording");
                return;
            }

            string segmentId = request.RequiredParam("id");

            PathToRecordableAudioForCurrentSegment = GetPathToRecordableAudioForSegment(segmentId);             // Careful! Overwrites the previous value of the member variable.
            PathToTemporaryWav = Path.GetTempFileName();

            if (Recorder.RecordingState == RecordingState.RequestedStop)
            {
                request.Failed(LocalizationManager.GetString("EditTab.Toolbox.TalkingBook.BadState",
                                                             "Bloom recording is in an unusual state, possibly caused by unplugging a microphone. You will need to restart.", "This is very low priority for translation."));
            }

            // If someone unplugged the microphone we were planning to use switch to another.
            // This also triggers selecting the first one initially.
            if (!RecordingDevice.Devices.Contains(RecordingDevice))
            {
                RecordingDevice = RecordingDevice.Devices.FirstOrDefault();
            }
            if (RecordingDevice == null)
            {
                ReportNoMicrophone();
                request.Failed("No Microphone");
                return;
            }

            if (Recording)
            {
                request.Failed("Already Recording");
                return;
            }

            if (!PrepareBackupFile(PathToRecordableAudioForCurrentSegment, ref _backupPathForRecordableAudio, request))
            {
                return;
            }

            // There are two possible scenarios when starting to record.
            //  1. We have a recordable file and corresponding publishable file.
            //     In that case, we need to make sure to restore the publishable file if we restore the recordable one so they stay in sync.
            //  2. We have an publishable file with no corresponding recordable file.
            //     In that case, we need to restore it if there is any problem creating a new recordable file.
            if (!PrepareBackupFile(GetPathToPublishableAudioForSegment(segmentId), ref _backupPathForPublishableAudio, request))
            {
                return;
            }

            _startRecording = DateTime.Now;
            _startRecordingTimer.Start();
            request.ReplyWithText("starting record soon");
        }
示例#59
0
 /// <summary>
 /// Official Method Name: List of geese nests
 /// Description: This method returns a list of geese nests during their spring mating season
 /// Update Frequency: When updated by pull request
 /// All the above information is from the Official Documentation
 /// </summary>
 public ApiRequest <List <ListOfGeeseNests> > ListOfGeeseNests()
 {
     return(ApiRequest <List <ListOfGeeseNests> > .CreateApiRequest("/resources/goosewatch", _apiKey));
 }
示例#60
0
        public void HandleForgetChangesInSelectedBook(ApiRequest request)
        {
            try
            {
                if (!_tcManager.CheckConnection())
                {
                    request.Failed();
                    return;
                }

                // Enhance: do we need progress here?
                var bookName = Path.GetFileName(_bookSelection.CurrentSelection.FolderPath);
                // Todo before 5.1: forgetting changes might involve undoing a rename.
                // If so, ForgetChanges will return a list of folders affected (up to 3).
                // We need to notify the new collection tab to update its book list
                // and also possibly update the current selection, and in case we undid
                // things in the book, we should update the preview.
                var    modifiedBookFolders = _tcManager.CurrentCollection.ForgetChangesCheckin(bookName);
                string updatedBookFolder   = null;
                var    finalBookName       = bookName;
                if (modifiedBookFolders.Count > 0)
                {
                    updatedBookFolder = modifiedBookFolders[0];
                    finalBookName     = Path.GetFileName(updatedBookFolder);
                }

                if (finalBookName != bookName)
                {
                    _bookSelection.CurrentSelection.Storage.RestoreBookName(finalBookName);
                }

                // We've restored an old meta.json, things might be different...book titles for one.
                // This needs to come AFTER RestoreBookName, which fixes the book's FolderPath
                // so it knows where to load the restored meta.json from. But BEFORE
                // UpdateLabelOfBookInEditableCollection, which wants to use the restored BookInfo
                // to get a name (and fix the one in the Model).
                _bookSelection.CurrentSelection.UpdateBookInfoFromDisk();
                // We need to do this as early as possible so that as notifications start to
                // go to the UI and it starts to request things from our server the answers are
                // up to date.
                _bookSelection.CurrentSelection.ReloadFromDisk(updatedBookFolder);

                if (finalBookName != bookName)
                {
                    _collectionModel.UpdateLabelOfBookInEditableCollection(_bookSelection.CurrentSelection);
                }
                BookHistory.SetPendingCheckinMessage(_bookSelection.CurrentSelection, "");
                UpdateUiForBook(reloadFromDisk: false, renamedTo: updatedBookFolder);
                // We need to do this after updating the rest of the UI, so the button we're
                // looking for has been adjusted.
                _tcManager.CurrentCollection.UpdateBookStatus(finalBookName, true);
                request.PostSucceeded();
            }
            catch (Exception ex)
            {
                var msgId      = "TeamCollection.ErrorForgettingChanges";
                var msgEnglish = "Error forgetting changes for {0}: {1}";
                var log        = _tcManager?.CurrentCollection?.MessageLog;
                // Pushing an error into the log will show the Reload Collection button. It's not obvious this
                // is useful here, since we don't know exactly what went wrong. However, it at least gives the user
                // the option to try it.
                if (log != null)
                {
                    log.WriteMessage(MessageAndMilestoneType.Error, msgId, msgEnglish, _bookSelection?.CurrentSelection?.FolderPath, ex.Message);
                }
                Logger.WriteError(String.Format(msgEnglish, _bookSelection?.CurrentSelection?.FolderPath, ex.Message), ex);
                request.Failed("forget changes failed");
            }
        }