///<summary>Returns the full URL according to the route/route id given.</summary> private static string GetApiUrl(ApiRoute route) { string apiUrl = Introspection.GetOverride(Introspection.IntrospectionEntity.PayConnectRestURL, "https://payconnect.dentalxchange.com/pay/rest/PayService"); #if DEBUG apiUrl = "https://prelive2.dentalxchange.com/pay/rest/PayService"; #endif switch (route) { case ApiRoute.Root: //Do nothing. This is to allow someone to quickly grab the URL without having to make a copy+paste reference. break; case ApiRoute.AccountToken: apiUrl += "/accountToken"; break; case ApiRoute.PaymentRequest: apiUrl += "/paymentRequest"; break; case ApiRoute.PaymentStatus: apiUrl += "/paymentStatus"; break; default: break; } return(apiUrl); }
public static void SwapItems(this ObservableCollection <ApiRoute> items, int indexA, int indexB) { ApiRoute tmp = items[indexA]; items[indexA] = items[indexB]; items[indexB] = tmp; }
public bool Authenticate(ApiRoute route) { var result = false; if (!route.PublicRoute && !String.IsNullOrWhiteSpace(route.PermissionList)) { if (!Request.IsAuthenticated) { // access denied. return(false); } if (User.Identity == null || String.IsNullOrWhiteSpace(User.Identity.Name)) { // access denied. return(false); } List <string> allowedRoles = route.PermissionList.Split(',').ToList(); foreach (var role in allowedRoles) { if (User.IsInRole(role)) { result = true; break; } } } else { result = true; // route is public, or no permissions specified. } return(result); }
private List <string> GetMethodParameters(Type type, ApiRoute attribute) { var list = new List <string>(); var methods = type.GetMethods().Where(i => i.GetCustomAttributes(false).OfType <ApiRoute>() != null); var found = false; foreach (var method in methods) { var attr = method.CustomAttributes.First(); var value = attr.NamedArguments.FirstOrDefault(i => i.TypedValue.Value.ToString() == attribute.Path).TypedValue.Value; if (value == null) { continue; } if (value.ToString() != attribute.Path) { continue; } found = true; var parameters = method.GetParameters(); foreach (var p in parameters) { list.Add(p.Name); } } if (!found) { throw new Exception("Method cannot be found"); } return(list); }
public static void SetGlobalFlurlClient(this TestServer server) { var client = server.CreateClient(); ApiRoute.SetBase(client.BaseAddress.AbsoluteUri); FlurlHttp.Configure(settings => settings.HttpClientFactory = new TestHttpClientFactory(new FlurlClient(client))); }
///<summary>Returns the full URL according to the route/route id given.</summary> private static string GetApiUrl(ApiRoute route, string routeId = "") { #if DEBUG string apiUrl = "https://sandbox-api.paysimple.com/v4"; #else string apiUrl = "https://api.paysimple.com/v4"; #endif switch (route) { case ApiRoute.Root: //Do nothing. This is to allow someone to quickly grab the URL without having to make a copy+paste reference. break; case ApiRoute.Token: apiUrl += "/checkouttoken"; break; case ApiRoute.Customer: apiUrl += "/customer"; break; case ApiRoute.AccountCreditCard: apiUrl += "/account/creditcard"; break; case ApiRoute.Payment: apiUrl += "/payment"; break; case ApiRoute.PaymentReversed: apiUrl += "/payment/" + routeId + "/reverse"; break; case ApiRoute.PaymentVoided: apiUrl += "/payment/" + routeId + "/void"; break; case ApiRoute.CustomerToken: apiUrl += "/customer/" + routeId + "/token"; break; default: break; } return(apiUrl); }
public ApiRoute GetRouteByPath(string path) { var result = new ApiRoute(); DataSet ds = GetRouteByPathDS(path); if (ds != null && ds.Tables != null && ds.Tables.Count == 2 && ds.Tables[0].Rows.Count > 0 && ds.Tables[1].Rows.Count > 0) { DataRow routeRow = ds.Tables[0].Rows[0]; result = ConvertRowToRoute(routeRow); result.parameters = new List <ProcedureParameter>(); foreach (DataRow row in ds.Tables[1].Rows) { ProcedureParameter param = ConvertRowToProcedureParameter(row); result.parameters.Add(param); } } return(result); }
private ApiRoute ConvertRowToRoute(DataRow dr) { ApiRoute r = new ApiRoute(); r.RouteID = Convert.ToInt32(dr["RouteID"]); r.AppName = dr["AppName"].ToString(); r.RoutePath = dr["RoutePath"].ToString(); r.RouteCommand = dr["RouteCommand"].ToString(); r.AllowNoParameters = Convert.ToBoolean(dr["AllowNoParameters"]); r.PublicRoute = Convert.ToBoolean(dr["PublicRoute"]); r.PermissionList = dr["PermissionList"] == DBNull.Value ? "" : dr["PermissionList"].ToString(); r.CreateDt = Convert.ToDateTime(dr["CreateDt"].ToString()); r.CreatedBy = dr["CreatedBy"].ToString(); r.ModifiedBy = dr["ModifiedBy"] == DBNull.Value ? "" : dr["ModifiedBy"].ToString(); r.ModifiedDt = dr["ModifiedDt"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dr["ModifiedDt"].ToString()); return(r); }
public TransitLine(ApiRoute route) { TransitMode = route.Mode; ShortName = route.ShortName; LongName = route.LongName; GtfsId = route.GtfsId; Stops = route.Patterns .FirstOrDefault() ?.Stops ?.Select(x => new TransitStop { Coords = BasicGeopositionExtensions.Create(0.0, x.Lon, x.Lat), Name = x.Name, Code = x.Code }); Points = route.Patterns .FirstOrDefault() ?.Geometry .Select(x => BasicGeopositionExtensions.Create(0.0, x.Lon, x.Lat)); }
///<summary>Returns the full URL according to the route given.</summary> private string GetApiUrl(ApiRoute route) { string apiUrl = Introspection.GetOverride(Introspection.IntrospectionEntity.PDMPURL, "https://www.ilpmp.org/rxhistorySumAdp/getReport"); if (ODBuild.IsDebug()) { apiUrl = "https://openid.logicoy.com/ilpdmp/test/getReport"; } switch (route) { case ApiRoute.Root: //Do nothing. This is to allow someone to quickly grab the URL without having to make a copy+paste reference. break; case ApiRoute.PrescriptionSummary: apiUrl += "/prescriptionSummary"; break; default: break; } return(apiUrl); }
public string ExecuteRoute(ApiRoute route) { DataSet ds = new DataSet(); using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlDataAdapter sda = new SqlDataAdapter(route.RouteCommand, conn)) { sda.SelectCommand.CommandType = CommandType.StoredProcedure; foreach (var p in route.parameters) { sda.SelectCommand.Parameters.Add(p.PARAMETER_NAME, SqlDbType.NVarChar); sda.SelectCommand.Parameters[p.PARAMETER_NAME].Value = p.VALUE; } conn.Open(); sda.Fill(ds); string json = DStoJSON(ds); return(json); } } }
///<summary>Throws exception if the response from the server returned an http code of 300 or greater.</summary> private static T Request <T>(ApiRoute route, HttpMethod method, string authHeader, string body, T responseType, string routeId = "") { using (WebClient client = new WebClient()) { client.Headers[HttpRequestHeader.Accept] = "application/json"; client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.Headers[HttpRequestHeader.Authorization] = authHeader; client.Encoding = UnicodeEncoding.UTF8; //Post with Authorization headers and a body comprised of a JSON serialized anonymous type. try { string res = ""; //Only GET and POST are supported currently. if (method == HttpMethod.Get) { res = client.DownloadString(GetApiUrl(route, routeId)); } else if (method == HttpMethod.Post) { res = client.UploadString(GetApiUrl(route, routeId), HttpMethod.Post.Method, body); } else if (method == HttpMethod.Put) { res = client.UploadString(GetApiUrl(route, routeId), HttpMethod.Put.Method, body); } else { throw new Exception("Unsupported HttpMethod type: " + method.Method); } #if DEBUG if ((typeof(T) == typeof(string))) //If user wants the entire json response as a string { return((T)Convert.ChangeType(res, typeof(T))); } #endif return(JsonConvert.DeserializeAnonymousType(res, responseType)); } catch (WebException wex) { string res = ""; using (var sr = new StreamReader(((HttpWebResponse)wex.Response).GetResponseStream())) { res = sr.ReadToEnd(); } if (string.IsNullOrWhiteSpace(res)) { //The response didn't contain a body. Through my limited testing, it only happens for 401 (Unauthorized) requests. if (wex.Response.GetType() == typeof(HttpWebResponse)) { HttpStatusCode statusCode = ((HttpWebResponse)wex.Response).StatusCode; if (statusCode == HttpStatusCode.Unauthorized) { throw new ODException(Lans.g("PaySimple", "Invalid PaySimple credentials. Check your Username and Key and try again.")); } } } else { HandleWebException(res); } string errorMsg = wex.Message + (string.IsNullOrWhiteSpace(res) ? "" : "\r\nRaw response:\r\n" + res); throw new Exception(errorMsg, wex); //If it got this far and haven't rethrown, simply throw the entire exception. } catch (Exception ex) { //WebClient returned an http status code >= 300 ex.DoNothing(); //For now, rethrow error and let whoever is expecting errors to handle them. //We may enhance this to care about codes at some point. throw; } } }
///<summary>Throws exception if the response from the server returned an http code of 300 or greater.</summary> private static T Request <T>(ApiRoute route, HttpMethod method, List <string> listHeaders, string body, T responseType, string queryStr = "") { using (WebClient client = new WebClient()) { client.Headers[HttpRequestHeader.ContentType] = "application/json"; listHeaders.ForEach(x => client.Headers.Add(x)); client.Encoding = UnicodeEncoding.UTF8; try { string res = ""; if (method == HttpMethod.Get) { res = client.DownloadString(GetApiUrl(route) + queryStr); } else if (method == HttpMethod.Post) { res = client.UploadString(GetApiUrl(route) + queryStr, HttpMethod.Post.Method, body); } else if (method == HttpMethod.Put) { res = client.UploadString(GetApiUrl(route) + queryStr, HttpMethod.Put.Method, body); } else { throw new Exception("Unsupported HttpMethod type: " + method.Method); } #if DEBUG if ((typeof(T) == typeof(string))) //If user wants the entire json response as a string { return((T)Convert.ChangeType(res, typeof(T))); } #endif return(JsonConvert.DeserializeAnonymousType(res, responseType)); } catch (WebException wex) { string res = ""; if (!(wex.Response is HttpWebResponse)) { throw new Exception("Could not connect to the PayConnect server:\r\n" + wex.Message, wex); } using (var sr = new StreamReader(((HttpWebResponse)wex.Response).GetResponseStream())) { res = sr.ReadToEnd(); } if (string.IsNullOrWhiteSpace(res)) { //The response didn't contain a body. Through my limited testing, it only happens for 401 (Unauthorized) requests. if (wex.Response.GetType() == typeof(HttpWebResponse)) { HttpStatusCode statusCode = ((HttpWebResponse)wex.Response).StatusCode; if (statusCode == HttpStatusCode.Unauthorized) { throw new ODException(Lans.g("PayConnect", "Invalid PayConnect credentials.")); } } } string errorMsg = wex.Message + (string.IsNullOrWhiteSpace(res) ? "" : "\r\nRaw response:\r\n" + res); throw new Exception(errorMsg, wex); //If we got this far and haven't rethrown, simply throw the entire exception. } catch (Exception ex) { //WebClient returned an http status code >= 300 ex.DoNothing(); //For now, rethrow error and let whoever is expecting errors to handle them. //We may enhance this to care about codes at some point. throw; } } }
static string HtmlToDescribeApiRoute(ApiRoute apiRoute) => LinkHtmlElementFromUrl(apiRoute.path) + " [ " + string.Join(", ", apiRoute.methods.Select(m => m.Key.ToUpperInvariant())) + " ]";
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='route'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task SetRouteAsync(this IDatabase operations, ApiRoute route, CancellationToken cancellationToken = default(CancellationToken)) { await operations.SetRouteWithHttpMessagesAsync(route, null, cancellationToken).ConfigureAwait(false); }
protected async Task SetApiRouteToHttpContext(ApiRoute apiRoute) { await _httpDataRepository.Add("ApiRoute", apiRoute); }
///<summary>Throws exception if the response from the server returned an http code of 300 or greater.</summary> private T Request <T>(ApiRoute route, HttpMethod method, string authHeader, string body, T responseType) { using (WebClient client = new WebClient()) { client.Headers[HttpRequestHeader.Accept] = "application/xml"; client.Headers[HttpRequestHeader.ContentType] = "application/xml"; client.Headers[HttpRequestHeader.Authorization] = authHeader; client.Encoding = UnicodeEncoding.UTF8; try { string res = ""; if (method == HttpMethod.Get) { res = client.DownloadString(GetApiUrl(route)); } else if (method == HttpMethod.Post) { res = client.UploadString(GetApiUrl(route), HttpMethod.Post.Method, body); } else if (method == HttpMethod.Put) { res = client.UploadString(GetApiUrl(route), HttpMethod.Put.Method, body); } else { throw new Exception("Unsupported HttpMethod type: " + method.Method); } if (ODBuild.IsDebug()) { if ((typeof(T) == typeof(string))) //If user wants the entire json response as a string { return((T)Convert.ChangeType(res, typeof(T))); } Console.WriteLine(res); } return(Deserialize <T>(res, responseType)); } catch (WebException wex) { string res = ""; using (var sr = new StreamReader(((HttpWebResponse)wex.Response).GetResponseStream())) { res = sr.ReadToEnd(); } if (string.IsNullOrWhiteSpace(res)) { //The response didn't contain a body. Through my limited testing, it only happens for 401 (Unauthorized) requests. if (wex.Response.GetType() == typeof(HttpWebResponse)) { HttpStatusCode statusCode = ((HttpWebResponse)wex.Response).StatusCode; if (statusCode == HttpStatusCode.Unauthorized) { throw new ODException(Lans.g("PDMP", "Invalid PDMP credentials.")); } } } string errorMsg = wex.Message + (string.IsNullOrWhiteSpace(res) ? "" : "\r\nRaw response:\r\n" + res); throw new Exception(errorMsg, wex); //If we got this far and haven't rethrown, simply throw the entire exception. } catch (Exception ex) { //WebClient returned an http status code >= 300 ex.DoNothing(); //For now, rethrow error and let whoever is expecting errors to handle them. //We may enhance this to care about codes at some point. throw; } } }
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='route'> /// </param> public static void SetRoute(this IDatabase operations, ApiRoute route) { Task.Factory.StartNew(s => ((IDatabase)s).SetRouteAsync(route), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); }