//private methods to execute the various sub-requests /// <summary> /// Send the Consignment Request document to TNT and receive an Accesscode as a response /// </summary> private async Task initialRequestAsync() { this.Status = Statusses.SendRequest; string errors = shipReq.Validate(ShipRequestSchemaUri); if (errors.Length > 0) { throw new InvalidOperationException("Schema validation error(s): \r\n" + errors); } HttpContent content = BuildWWWFormUrlEncoded(shipReq.xml); PostResults res = await PostAsync(content, expectXml : false); //Check that we received the access code and start the next request string answer = res.Content; if (answer.StartsWith("COMPLETE:") && answer.Length >= 17) { this.accessCode = answer.Substring(9); FireAccesscodeReceived(); //start next request await GetResult(); } else { FireShipRequestError(0, "No Accesscode Received, Response was: " + answer); } }
public IHttpActionResult CreateComment(FeedBackModel feedBackModel) { Comment feedBack = feedBackModel.ToFeedBack(); _command.AddComment(feedBack); var model = feedBack.ToFeedBackResponseModel(); return(PostResults.Created(this, model)); }
public async Task <IHttpActionResult> Register(RegisterUserModel model) { var user = model.ToUserEntity(); var result = await _securityContextCommand.RegisterUser(user, model.Password); if (!result.Succeeded) { return(new StatusCodeResult((HttpStatusCode)422, this)); } var response = user.ToUserModel(); return(PostResults.Created(this, response)); }
/// <summary> /// Fetch one of the 4 printable documents, as readonly, from the TNT server, apply an XSLT stylesheet, /// then send it to a printer (last point still TODO) /// </summary> /// <param name="type">One of the four document types</param> private async Task GetDocument(DocTypes type) { docStatus[type] = DocStatusses.Fetching; FireDocumentRequest(type); FormUrlEncodedContent content = new FormUrlEncodedContent(new Dictionary <string, string>() { { "xml_in", "GET_" + type.ToString().ToUpper() + ":" + this.accessCode } }); PostResults resp = await PostAsync(content, expectXml : true); //Choose the stylsheet fitting to the doc type XslCompiledTransform xsl = new XslCompiledTransform(); switch (type) { case DocTypes.Label: xsl.Load(typeof(AddressLabelXsl)); break; case DocTypes.Manifest: xsl.Load(typeof(ManifestXsl)); break; case DocTypes.Connote: xsl.Load(typeof(ConsignmentNoteXsl)); break; case DocTypes.Invoice: xsl.Load(typeof(CommercialInvoiceXsl)); break; } //Transform the response, with the stylesheet, then layout and print TextWriter wri = new StringWriter(); XsltArgumentList args = new XsltArgumentList(); xsl.Transform(resp.Xml.docR, args, wri); bool loadingProblems = printQueue.AddPrintJob(wri.ToString()); //Load into browser, then print if (loadingProblems) { FireDocumentLoadError(0, "One of the HTML documents to be printed did not load into the .NET browser properly."); } docStatus[type] = DocStatusses.Fetched; FireDocumentReceived(type); await GetNextExpectedDocument(); //the recursive call will end after max 4 iterations (the docTypes). }
public IHttpActionResult CreateComment(string comment) { int userId; if (!User.TryGetUserId(out userId)) { return(Unauthorized()); } User user = _query.Users.GetUserById(userId); if (user == null) { return(NotFound()); } Comment feedBack = user.CreateFeedBack(comment); _command.AddComment(feedBack); var model = feedBack.ToFeedBackResponseModel(); return(PostResults.Created(this, model)); }
public bool doHandshake( Uri uri, String username, String password ) { // initiate the handshake by GET on SSO url Uri activeUri = uri; if (String.IsNullOrWhiteSpace(username) || String.IsNullOrWhiteSpace(username)) { performGet(activeUri, true); // Try to get an authentication cookie using network credentials } String response = performGet(activeUri, false).body; //Fix = what if null or no data? do { if (response == null) { Trace.TraceError("No response returned during SSO handshake. There should have been one."); break; } // look for a form that will provide the next URL in the handshake sequence, which will also provide fields (such // as the SAML request from the SP and the SAML response from the IdP) that need to be forwarded on to the next URL FormInfo formInfo = getFirstFormInfo(response); if (formInfo == null) { Trace.TraceError("No form detected during SSO handshake. There should have been one.\r\n\r\n{0}", response); break; // no form detected, so this is the end of the handshake } // determine the form fields to post to the next URL; special handling takes place in the case of the password // form where we step in and provide the user's name / password to the SP List <PostParam> postParams; if (formInfo.isPasswordForm()) { postParams = formInfo.getPasswordPostParams(username, password); } else if (formInfo.isSamlForm()) { postParams = formInfo.getSamlPostParams(); } else { Trace.TraceError("Unknown form encountered during handshake"); break; } // invoke the next step in the handshake activeUri = formInfo.getAbsoluteUri(activeUri); PostResults postResults = performPost(activeUri, postParams); if (postResults.statusCode != HttpStatusCode.OK) { Trace.TraceError("Unexpected status code from POST: " + postResults.statusCode.ToString()); break; } response = postResults.body; } while ((jsessionidCookie = getJsessionidCookie()) == null); return(jsessionidCookie != null); }
private PostResults performPost( Uri uri, List <PostParam> postParams ) { var results = new PostResults(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.AllowAutoRedirect = true; request.CookieContainer = cookieContainer; request.Method = "POST"; //request.Referer = ""; request.ContentType = "application/x-www-form-urlencoded"; StringBuilder sb = new StringBuilder(); StringBuilder postParamString = new StringBuilder(); foreach (PostParam param in postParams) { postParamString.AppendFormat("{0} = {1}\r\n", param.name, param.showInLog?param.value:"Not shown"); sb.AppendFormat("{0}{1}={2}", sb.Length == 0?"":"&", param.name, HttpUtility.UrlEncode(param.value)); } byte[] buffer = Encoding.Default.GetBytes(sb.ToString()); using (Stream dataStream = request.GetRequestStream()) { dataStream.Write(buffer, 0, buffer.Length); } String requestHeaders = request.Headers.ToString(); String responseHeaders = ""; String cookiesBefore = makeDisplayableCookieString(); String cookiesAfter = ""; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { //System.Windows.Forms.MessageBox.Show("Good POST request"); results.statusCode = response.StatusCode; //results.redirectLocation = response.GetResponseHeader("Location"); responseHeaders = response.Headers.ToString(); cookiesAfter = makeDisplayableCookieString(); using (Stream dataStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(dataStream)) { results.body = reader.ReadToEnd(); } } } } finally { Trace.TraceInformation("SSO Post ({0}):\r\n{1}\r\nRequest Headers:\r\n{2}Cookies Before:\r\n{3}\r\nPost Params(Unencoded):\r\n{4}Response Headers:\r\n{5}Cookies After:\r\n{6}\r\nResponse Data\r\n{7}", results.statusCode == null?"None":results.statusCode.ToString(), uri, requestHeaders, cookiesBefore, postParamString, responseHeaders, cookiesAfter, results.body); } return(results); }
private PostResults performPost( Uri uri, List<PostParam> postParams ) { var results = new PostResults(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.AllowAutoRedirect = true; request.CookieContainer = cookieContainer; request.Method = "POST"; //request.Referer = ""; request.ContentType = "application/x-www-form-urlencoded"; StringBuilder sb = new StringBuilder(); StringBuilder postParamString = new StringBuilder(); foreach (PostParam param in postParams) { postParamString.AppendFormat("{0} = {1}\r\n",param.name,param.showInLog?param.value:"Not shown"); sb.AppendFormat("{0}{1}={2}",sb.Length==0?"":"&",param.name,HttpUtility.UrlEncode(param.value)); } byte[] buffer = Encoding.Default.GetBytes(sb.ToString()); using (Stream dataStream = request.GetRequestStream()) { dataStream.Write(buffer, 0, buffer.Length); } String requestHeaders = request.Headers.ToString(); String responseHeaders = ""; String cookiesBefore = makeDisplayableCookieString(); String cookiesAfter = ""; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { //System.Windows.Forms.MessageBox.Show("Good POST request"); results.statusCode = response.StatusCode; //results.redirectLocation = response.GetResponseHeader("Location"); responseHeaders = response.Headers.ToString(); cookiesAfter = makeDisplayableCookieString(); using (Stream dataStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(dataStream)) { results.body = reader.ReadToEnd(); } } } } finally { Trace.TraceInformation("SSO Post ({0}):\r\n{1}\r\nRequest Headers:\r\n{2}Cookies Before:\r\n{3}\r\nPost Params(Unencoded):\r\n{4}Response Headers:\r\n{5}Cookies After:\r\n{6}\r\nResponse Data\r\n{7}", results.statusCode==null?"None":results.statusCode.ToString(), uri, requestHeaders, cookiesBefore, postParamString, responseHeaders, cookiesAfter, results.body); } return results; }
/// <summary> /// Use the Accesscode to get the TNTResult document that will show us if the consignments were booked /// </summary> private async Task GetResult() { this.Status = Statusses.GetResult; FormUrlEncodedContent content = new FormUrlEncodedContent(new Dictionary <string, string>() { { "xml_in", "GET_RESULT:" + this.accessCode } //application/x-www-form-urlencoded like it's meant to be... no xml really! }); PostResults resp = await PostAsync(content, expectXml : true); //this time the result is xml and we go analyse it TNTResult.IndexBy indexBy = (this.shipReq.reqestType == TNTShipRequest.RequestTypes.Full) ? TNTResult.IndexBy.CONREF : TNTResult.IndexBy.CONNUMBER; this.shipRes = new TNTResult(resp.Xml, indexBy); if (shipRes.OK && !shipRes.hasAnyError) { if (shipReq.reqestType == TNTShipRequest.RequestTypes.Full && shipRes.hasShip) { foreach (var c in shipRes) //iterate the consignments { if (shipRes.Success) //consignment booked? { FireConsignmentSuccess(shipRes.ConRef, shipRes.ConNumber); } else { FireConsignmentNoSuccess(shipRes.ConRef); } } } else { if (shipReq.reqestType == TNTShipRequest.RequestTypes.PrintOnly && !shipRes.hasShip) { //good! just proceed } else //surely wrong { if (shipReq.reqestType == TNTShipRequest.RequestTypes.Full && !shipRes.hasShip) { FireShipResultError(0, "Error in result document: full request, but SHIP element not found in result."); } else { FireShipResultError(0, "Error in result document: request was 'printonly' and still SHIP is present."); } return; //no follow up after these errors } } //Path of (at least partial) success: which docs do we need to get from te server? if (shipRes.IsLabelCreated) { this.docStatus[DocTypes.Label] = DocStatusses.OnTNTServer; } if (shipRes.IsManifestCreated) { this.docStatus[DocTypes.Manifest] = DocStatusses.OnTNTServer; } if (shipRes.IsConnoteCreated) { this.docStatus[DocTypes.Connote] = DocStatusses.OnTNTServer; } if (shipRes.IsInvoiceCreated) { this.docStatus[DocTypes.Invoice] = DocStatusses.OnTNTServer; } //event FireResultReceived(docStatus[DocTypes.Label], docStatus[DocTypes.Manifest], docStatus[DocTypes.Connote], docStatus[DocTypes.Invoice] ); //start follow up requests! this.Status = Statusses.GetDocs; await GetNextExpectedDocument(); } else { FireShipResultError(0, "Error in result document: " + shipRes.GetFirstErrorDescr()); } }