public Response PostDictionary(string scope, string application, DatabaseDictionary dictionary) { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.ContentType = "application/xml"; return(_NHibernateProvider.PostDictionary(scope, application, dictionary)); }
private static void SetNancyResponseToOutgoingWebResponse(OutgoingWebResponseContext webResponse, Response nancyResponse) { SetHttpResponseHeaders(webResponse, nancyResponse); webResponse.ContentType = nancyResponse.ContentType; webResponse.StatusCode = (System.Net.HttpStatusCode)nancyResponse.StatusCode; }
private void SetCacheHeaders(OutgoingWebResponseContext response) { response.ContentType = "image/png"; response.Headers[HttpResponseHeader.CacheControl] = "public"; response.LastModified = new DateTime(1900, 1, 1); response.Headers[HttpResponseHeader.Expires] = (DateTime.Now + Settings.ClientCacheMaxAge).ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"); }
public List <wsCustomer> GetAllCustomers() { try { NorthwindDataContext dc = new NorthwindDataContext(); List <wsCustomer> results = new List <wsCustomer>(); foreach (Customer cust in dc.Customers) { results.Add(new wsCustomer() { CustomerID = cust.CustomerID, CompanyName = cust.CompanyName, City = cust.City }); } return(results); } catch (Exception ex) { // Return any exception messages back to the Response header OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.StatusCode = System.Net.HttpStatusCode.InternalServerError; response.StatusDescription = ex.Message.Replace("\r\n", ""); return(null); } }
public List <wsCustomerOrderHistory> GetCustomerOrderHistory(string customerID) { try { List <wsCustomerOrderHistory> results = new List <wsCustomerOrderHistory>(); NorthwindDataContext dc = new NorthwindDataContext(); foreach (CustOrderHistResult oneOrder in dc.CustOrderHist(customerID)) { results.Add(new wsCustomerOrderHistory() { ProductName = oneOrder.ProductName, Total = oneOrder.Total ?? 0 }); } return(results); } catch (Exception ex) { // Return any exception messages back to the Response header OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.StatusCode = System.Net.HttpStatusCode.InternalServerError; response.StatusDescription = ex.Message.Replace("\r\n", ""); return(null); } }
public System.IO.Stream AxlPost(System.IO.Stream data) { try { if (_serverConfig == null || _serverConfig.Instances.Length == 0) { return(WriteException("ServiceType not initialized!")); } string user, pwd; var request = Request(out user, out pwd); NameValueCollection queryString = KeysToLower(request.UriTemplateMatch.QueryParameters); //DateTime td = DateTime.Now; //Console.WriteLine("Start AXL Request " + td.ToLongTimeString() + "." + td.Millisecond + " (" + queryString["servicename"] + ")"); string input = (data != null ? new StreamReader(data).ReadToEnd() : String.Empty); OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; if (queryString["cmd"] != null) { context.ContentType = "text/plain; charset=UTF-8"; switch (queryString["cmd"].ToLower()) { case "ping": //return new MemoryStream(Encoding.UTF8.GetBytes("IMS v4.0.1\n")); return(new MemoryStream(Encoding.UTF8.GetBytes("IMS v10.0.0\n"))); case "getversion": //return new MemoryStream(Encoding.UTF8.GetBytes("Version:4.0.1\nBuild_Number:630.1700\n")); return(new MemoryStream(Encoding.UTF8.GetBytes("Version=10.0.0\nBuild_Number=183.2159\n"))); } } if (queryString["servicename"] == null) { return(WriteException("Parameter SERVICENAME is requiered!")); } context.ContentType = "text/xml; charset=UTF-8"; int instanceNr = GetRandom(_serverConfig.Instances.Length /*MapServerConfig.ServerCount*/); MapServerConfig.ServerConfig.InstanceConfig config = _serverConfig.Instances[instanceNr]; InstanceConnection connection = new InstanceConnection("localhost:" + config.Port); string response = connection.Send( Functions.OgcOnlineResource(_serverConfig), queryString["servicename"], input, "BB294D9C-A184-4129-9555-398AA70284BC", user, pwd).Trim(); //Console.WriteLine("Finished AXL Request: " + (DateTime.Now - td).TotalMilliseconds + "ms (" + queryString["servicename"] + ")"); return(new MemoryStream(Encoding.UTF8.GetBytes(response))); } catch (UnauthorizedAccessException) { return(WriteUnauthorized()); } }
public void Save(string appName, Stream fileContent) { try { if (WebOperationContext.Current == null) { throw new InvalidOperationException("WebOperationContext is null."); } m_Request = WebOperationContext.Current.IncomingRequest; m_Response = WebOperationContext.Current.OutgoingResponse; var file = CreateFileResource(fileContent, appName); if (!FileIsValid(file)) { throw new WebFaultException(HttpStatusCode.BadRequest); } SaveFile(file); SetStatusAsCreated(file); } catch (Exception ex) { if (ex.GetType() == typeof(WebFaultException)) { throw; } if (ex.GetType().IsGenericType&& ex.GetType().GetGenericTypeDefinition() == typeof(WebFaultException <>)) { throw; } throw new WebFaultException <string>("An unexpected error occurred.", HttpStatusCode.InternalServerError); } }
/// <summary> /// Sets the status of an outgoing response as 200/Ok. /// It is recommended that optional parameters be filled. /// </summary> /// <param name="context">The response context.</param> /// <param name="description">The response description.</param> /// <param name="contentLength">The length of the content being transported with the response.</param> /// <param name="contentType">The content type of the data being transported with the response.</param> public static void SetAsOk(this OutgoingWebResponseContext context, string description = "", long contentLength = 0, string contentType = "application/x-empty") { context.ContentLength = contentLength; context.ContentType = contentType; context.StatusDescription = description; context.StatusCode = (HttpStatusCode)200; }
public ResponseUserData Login(UserLoginData data) //Response class for retriving data { try { secureToken = GetJwt(data.Username, data.Password); var response = new ResponseUserData { Token = secureToken, Authenticated = true, FirstName = "Test", UserName = data.Username }; return(response); } catch (Exception ex) { // Return any exception messages back to the Response header OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.StatusCode = System.Net.HttpStatusCode.InternalServerError; response.StatusDescription = ex.Message.Replace("\r\n", ""); return(null); } }
private void ExceptionHandler(Exception ex, string format = "json") { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; if (ex is FileNotFoundException) { context.StatusCode = HttpStatusCode.NotFound; } else if (ex is UnauthorizedAccessException) { context.StatusCode = HttpStatusCode.Unauthorized; } else if (ex is WebFaultException) { context.StatusCode = HttpStatusCode.OK; Response response = new Response(); response.StatusCode = ((WebFaultException)ex).StatusCode; response.DateTimeStamp = DateTime.Now; response.StatusText = Convert.ToString(((WebFaultException)ex).Data["StatusText"]); response.Messages = new Messages() { ((WebFaultException)ex).Message, response.StatusText }; FormatOutgoingMessage <Response>(response, format, false); return; } else { context.StatusCode = HttpStatusCode.InternalServerError; } HttpContext.Current.Response.ContentType = "text/html"; HttpContext.Current.Response.Write(ex.ToString()); }
/// <summary> /// Sets the status of an <see cref="OutgoingWebResponseContext"/> to HTTP 302/Redirect (or however defined). /// </summary> /// <param name="context">The context this change applies to.</param> /// <param name="newLocation">The new location / the location to redirect to.</param> /// <param name="statusCode">The status code for the redirect - default: 302 - Found/Redirect</param> /// <returns></returns> public static OutgoingWebResponseContext SetStatusAsRedirect(this OutgoingWebResponseContext context, Uri newLocation, HttpStatusCode statusCode = (HttpStatusCode)302) { context.Location = newLocation.AbsoluteUri; context.StatusCode = statusCode; context.StatusDescription = $"{ (int)statusCode } redirect to { newLocation.AbsoluteUri }"; return(context); }
public DataObject GetSchemaObjectSchema(string scope, string application, string objectName) { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.ContentType = "application/xml"; return(_NHibernateProvider.GetSchemaObjectSchema(scope, application, objectName)); }
public DataRelationships GetRelationships() { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.ContentType = "application/xml"; return(_NHibernateProvider.GetRelationships()); }
public Response Generate(string scope, string application) { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.ContentType = "application/xml"; return(_NHibernateProvider.Generate(scope, application)); }
public Stream GetStagedInputFile(string name, string inputName) { OutgoingWebResponseContext ctx = WebOperationContext.Current.OutgoingResponse; var e = DataMarshal.GetStagedInputFile(name, inputName); if (e == null) { var detail = new ErrorDetail( ErrorDetail.Codes.DATAFORMAT_ERROR, String.Format("simulation \"{0}\" input \"{1}\" does not exist", name, inputName) ); throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.NotFound); } if (e.Content == null) { return(new MemoryStream()); } ctx.ContentType = "text/plain"; if (e.InputFileType != null && e.InputFileType.Type != null) { ctx.ContentType = e.InputFileType.Type; } ctx.StatusCode = System.Net.HttpStatusCode.OK; return(new MemoryStream(e.Content)); }
public VersionInfo GetVersion() { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.ContentType = "application/xml"; return(_adapterProvider.GetVersion()); }
protected static void SetNoCache() { OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.Headers.Add("Cache-Control", "no-cache"); response.Headers.Add("Pragma", "no-cache"); }
public void GetRequestStatus(string id) { RequestStatus status = null; try { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; status = _adapterProvider.GetRequestStatus(id); if (status.State == State.NotFound) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; } } catch (Exception ex) { status = new RequestStatus() { State = State.Error, Message = ex.Message }; } _adapterProvider.FormatOutgoingMessage <RequestStatus>(status, "xml", true); }
public Stream GET() { IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest; FormatServerResponse.AsyncDisplayMessage("GET request served to User agent " + request.UserAgent); string output = "<HTML>" + "<HEAD>" + "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />" + "<TITLE>" + "AS2 EDI Trading Partner Simulator" + "</TITLE>" + "</HEAD>" + "<BODY>" + "<H1>AS2 EDI Trading Partner Simulator</H1>" + "<P>" + "This tool simulates TP commuincation over AS2 Protocol and generates Sync and Async MDNs as response." + "</P> " + "<H3>Copyright © 2012 Intel Corporation. All rights reserved</H3>" + "<H4>Internal Use Only - Do Not Distribute</H4>" + "</BODY>" + "</HTML>"; MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(output)); OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.ContentType = "text/html"; return(stream); }
internal static void SuppressReplyEntityBody(Message message) { WebOperationContext currentContext = WebOperationContext.Current; if (currentContext != null) { OutgoingWebResponseContext responseContext = currentContext.OutgoingResponse; if (responseContext != null) { responseContext.SuppressEntityBody = true; } } else { object untypedProp; message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out untypedProp); HttpResponseMessageProperty prop = untypedProp as HttpResponseMessageProperty; if (prop == null) { prop = new HttpResponseMessageProperty(); message.Properties[HttpResponseMessageProperty.Name] = prop; } prop.SuppressEntityBody = true; } }
public List <wsTestDbItem> GetAllTestDbItems() { try { narfdaddy2DataContext dc = new narfdaddy2DataContext(); List <wsTestDbItem> results = new List <wsTestDbItem>(); foreach (ListBuilder1 item in dc.ListBuilder1s) { results.Add(new wsTestDbItem() { sCat = item.sCat, sSubcat = item.sSubcat, sItem = item.sItem, sDialog = item.sDialog }); } return(results); } catch (Exception ex) { // Return any exception messages back to the Response header OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.StatusCode = System.Net.HttpStatusCode.InternalServerError; response.StatusDescription = ex.Message.Replace("\r\n", ""); return(null); } }
public NetHttpServiceRespone(OutgoingWebResponseContext response, out Stream stream) { stream = new MemoryStream(); this.stream = stream; this.writer = new StreamWriter(stream); this.response = response; }
public List <wsOrder> GetOrdersForCustomer(string customerID) { try { NorthwindDataContext dc = new NorthwindDataContext(); List <wsOrder> results = new List <wsOrder>(); System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("en-US"); foreach (Order order in dc.Orders.Where(s => s.CustomerID == customerID)) { results.Add(new wsOrder() { OrderID = order.OrderID, ShipAddress = order.ShipAddress, ShipCity = order.ShipCity, ShipName = order.ShipName, }); } return(results); } catch (Exception ex) { // Return any exception messages back to the Response header OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.StatusCode = System.Net.HttpStatusCode.InternalServerError; response.StatusDescription = ex.Message.Replace("\r\n", ""); return(null); } }
public SPAJHTML_Form GetHtmlFile(string fileName) { try { byte[] file; string base64 = ""; Database myDB = new Database("ConnStringProd"); string pathForSQLFiles = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine("SQLFiles", "SelectValidSPAJHtmlFileByFileName.txt")); string query = File.ReadAllText(pathForSQLFiles); var selectResult = myDB.Query <SPAJHTML_Form>(query, new { FileName = fileName }).SingleOrDefault(); string pathForHTMLFiles = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine("HTMLFiles", selectResult.FolderName, fileName)); //using (var stream = new FileStream("D:\\" + selectResult.FolderName + "\\" + fileName + "", FileMode.Open, FileAccess.Read)) //{ // using (var reader = new BinaryReader(stream)) // { // file = reader.ReadBytes((int)stream.Length); // } //} using (var stream = new FileStream(pathForHTMLFiles, FileMode.Open, FileAccess.Read)) { using (var reader = new BinaryReader(stream)) { file = reader.ReadBytes((int)stream.Length); } } base64 = Convert.ToBase64String(file); string pathForSQLFiles2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine("SQLFiles", "UpdateSPAJHTMLFile.txt")); string query2 = File.ReadAllText(pathForSQLFiles2); myDB.Update <SPAJHTML_Form>(query2, new { Base64File = base64, Filename = fileName }); return(new SPAJHTML_Form() { FolderName = selectResult.FolderName, FileName = fileName, Base64File = base64 }); } catch (Exception ex) { // Return any exception messages back to the Response header OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.StatusCode = System.Net.HttpStatusCode.InternalServerError; response.StatusDescription = ex.Message.Replace("\r\n", ""); return(null); throw; } }
private string SerializeResponse(Resource fhirResource, string responseType, SummaryType st) { string rv = string.Empty; OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; if (responseType == "json") { FhirJsonSerializer fjs = new FhirJsonSerializer(); rv = fjs.SerializeToString(fhirResource, st); //rv = FhirSerializer.SerializeResourceToJson(fhirResource,st); //context.ContentType = "application/json"; context.ContentType = "application/fhir+json;charset=UTF-8"; // when IANA registered context.Format = WebMessageFormat.Json; } else { FhirXmlSerializer fxs = new FhirXmlSerializer(); rv = fxs.SerializeToString(fhirResource, st); //rv = FhirSerializer.SerializeResourceToXml(fhirResource,st); //context.ContentType = "application/xml"; context.ContentType = "application/fhir+xml;charset=UTF-8"; // when IANA registered context.Format = WebMessageFormat.Xml; } return(rv); }
public void AddStreamVitalSing(int checkupId, int vitalType, Stream fileStream) { try { var vitalCategory = m_model.VitalTypes.Single(P => P.Id == vitalType); String fileName = CreateRelataedDirectories(checkupId.ToString(), vitalCategory.Id.ToString(), vitalType.ToString()); FileStream fileToupload = new FileStream(fileName, FileMode.Create); byte[] bytearray = new byte[10000]; int bytesRead, totalBytesRead = 0; do { bytesRead = fileStream.Read(bytearray, 0, bytearray.Length); totalBytesRead += bytesRead; } while (bytesRead > 0); fileToupload.Write(bytearray, 0, bytearray.Length); fileToupload.Close(); fileToupload.Dispose(); } catch (Exception ex) { OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.StatusCode = System.Net.HttpStatusCode.NotFound; response.StatusDescription = ex.Message; } }
public List <HiMessageFile> HiMessages(string HpiFacilityId) { List <HiMessageFile> hiMessageList = new List <HiMessageFile>(); try { if (AuthenticateUser(WebOperationContext.Current.IncomingRequest)) { if (this.userID != HpiFacilityId) { throw new Exception("Invalid Request Parameter"); } ServiceInterface appSi = new ServiceInterface(); hiMessageList = appSi.GetHiMessages(HpiFacilityId); } else { OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.StatusCode = HttpStatusCode.Unauthorized; } } catch (Exception ex) { throw new Exception("Web Service Error: " + ex.Message); } return(hiMessageList); }
private void ExceptionHandler(Exception ex) { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; string statusText = string.Empty; if (ex is FileNotFoundException) { context.StatusCode = HttpStatusCode.NotFound; } else if (ex is UnauthorizedAccessException) { context.StatusCode = HttpStatusCode.Unauthorized; } else { context.StatusCode = HttpStatusCode.InternalServerError; if (ex is WebFaultException && ex.Data != null) { foreach (DictionaryEntry entry in ex.Data) { statusText += ex.Data[entry.Key].ToString(); } } } if (string.IsNullOrEmpty(statusText)) { statusText = ex.Source + ": " + ex.ToString(); } HttpContext.Current.Response.ContentType = "text/html"; HttpContext.Current.Response.Write(statusText); }
/// <summary> /// The before send reply. /// </summary> /// <param name="reply"> /// The reply. /// </param> /// <param name="correlationState"> /// The correlation state. /// </param> public void BeforeSendReply(ref Message reply, object correlationState) { if (reply.Properties.ContainsKey("httpResponse")) { var httpResponse = reply.Properties["httpResponse"] as HttpResponseMessageProperty; if (httpResponse != null) { foreach (var item in this.requiredHeaders) { if (!httpResponse.Headers.HasKey(item.Key)) { httpResponse.Headers.Add(item.Key, item.Value); } } return; } } WebOperationContext currentContext = WebOperationContext.Current; if (currentContext != null) { OutgoingWebResponseContext response = currentContext.OutgoingResponse; foreach (var item in this.requiredHeaders) { if (!response.Headers.HasKey(item.Key)) { response.Headers.Add(item.Key, item.Value); } } } }
private static void CopyHttpResponseMessageToOutgoingResponse(HttpResponseMessage response, OutgoingWebResponseContext outgoingResponse) { outgoingResponse.StatusCode = response.StatusCode; outgoingResponse.StatusDescription = response.ReasonPhrase; if (response.Content == null) { outgoingResponse.SuppressEntityBody = true; } foreach (var kvp in response.Headers) { foreach (var value in kvp.Value) { outgoingResponse.Headers.Add(kvp.Key, value); } } if (response.Content != null) { foreach (var kvp in response.Content.Headers) { foreach (var value in kvp.Value) { outgoingResponse.Headers.Add(kvp.Key, value); } } } }
/// <summary> /// Submits this response to a WCF response context. Only available when no response body is included. /// </summary> /// <param name="responseContext">The response context to apply the response to.</param> /// <param name="responseMessage">The response message.</param> private void Respond(OutgoingWebResponseContext responseContext, HttpResponseMessage responseMessage) { responseContext.StatusCode = responseMessage.StatusCode; responseContext.SuppressEntityBody = true; foreach (var header in responseMessage.Headers) { responseContext.Headers[header.Key] = header.Value.First(); } }