public override IResponse receiveAnswer() { byte[] header = new byte[BinaryResponse.HEADER_LENTGH]; log.Info("recieving an answer..."); int n = port.Read(header, 0, BinaryResponse.HEADER_LENTGH); if (n != BinaryResponse.HEADER_LENTGH) { // maybe wait for a while? log.Info("error reading header from device!"); throw new InvalidDataException(); } BinaryResponse.OP op = (BinaryResponse.OP)BitConverter.ToInt32(header, 0); UInt32 dataLen = BitConverter.ToUInt32(header, 4); BinaryResponse answer = BinaryResponse.newDeviceAnswer(op); log.Info("got answer of type: " + op.ToString()); if (dataLen != 0) { byte[] data = new byte[dataLen]; n = port.Read(data, 0, (int)dataLen); if (n != dataLen) { log.Info("could not read all the data, maybe add a loop?!"); throw new NotImplementedException(); } answer.fromByteArray(header, data); } return(answer); }
public virtual BinaryResponse ExportStore(ApiCall call) { var site = call.WebSite; if (site == null) { return(null); } var storevalue = call.GetValue("stores"); var stores = storevalue.Split(',').ToList(); var exportfile = ImportExport.ExportInterSelected(site.SiteDb(), stores); var path = System.IO.Path.GetFullPath(exportfile); if (File.Exists(exportfile)) { var allbytes = System.IO.File.ReadAllBytes(path); BinaryResponse response = new BinaryResponse(); response.ContentType = "application/zip"; response.Headers.Add("Content-Disposition", $"attachment;filename={site.Name}.zip"); response.BinaryBytes = allbytes; return(response); } return(null); }
public async Task <byte[]> PostAsync(Stream inputStream) { var reader = new BinaryReader(inputStream); BinaryRequest request = BinaryRequest.Read(reader); var task = TryHandleAsync <GetManyRequest, GetManyResponse>(request, GetManyAsync) ?? TryHandleAsync <PostRequest, PostResponse>(request, PostAsync) ?? TryHandleAsync <InterruptRequest, InterruptResponse>(request, InterruptAsync) ?? TryHandleAsync <NotifyRequest, NotifyResponse>(request, NotifyAsync) ?? TryHandleAsync <WindowsPhoneSubscribeRequest, WindowsPhoneSubscribeResponse>(request, WindowsPhoneSubscribeAsync) ?? TryHandleAsync <WindowsPhoneUnsubscribeRequest, WindowsPhoneUnsubscribeResponse>(request, WindowsPhoneUnsubscribeAsync); if (task == null) { throw new CorrespondenceException(String.Format("Unknown request type {0}.", request)); } BinaryResponse response = await task; MemoryStream memory = new MemoryStream(); using (var writer = new BinaryWriter(memory)) { response.Write(writer); } return(memory.ToArray()); }
public BinaryResponse ProccessRequest(BinaryRequest request) { BinaryResponse response = new BinaryResponse(); response.originalString = request.stringToModify; string stringInProgress = request.stringToModify; byte[] btText; btText = System.Text.Encoding.UTF8.GetBytes(stringInProgress); Array.Reverse(btText); System.Collections.BitArray bit = new System.Collections.BitArray(btText); String responseString = ""; for (int i = bit.Length - 1; i >= 0; i--) { if (bit[i] == true) { //response.ModifiedString(1); responseString += "1"; } else { //response.ModifiedString(0); responseString += "0"; } } response.modifiedString = responseString; return(response); }
//attachment image. public BinaryResponse File(ApiCall call) { string filename = call.Command.Value; if (EmailForwardManager.RequireForward(call.Context)) { var method = nameof(EmailAttachmentApi.MsgFile) + "/" + filename; if (!string.IsNullOrEmpty(filename)) { method += "/" + filename; } var filebytes = EmailForwardManager.Post(this.ModelName, method, call.Context.User, null, null); var response = new BinaryResponse(); response.Headers.Add("Content-Disposition", $"filename={System.Web.HttpUtility.UrlEncode(filename)}"); response.BinaryBytes = filebytes; return(response); } var bytes = Kooboo.Mail.MultiPart.FileService.Get(call.Context.User, filename); if (bytes != null && bytes.Length > 0) { var response = new BinaryResponse(); response.ContentType = Kooboo.Lib.Compatible.CompatibleManager.Instance.Framework.GetMimeMapping(filename); response.Headers.Add("Content-Disposition", $"filename={System.Web.HttpUtility.UrlEncode(filename)}"); response.BinaryBytes = bytes; return(response); } return(null); }
public virtual BinaryResponse Export(ApiCall call) { var site = call.WebSite; if (site == null) { return(null); } var exportfile = ImportExport.ExportInter(site.SiteDb()); var path = System.IO.Path.GetFullPath(exportfile); string name = site.DisplayName; if (string.IsNullOrEmpty(name)) { name = site.Name; } name = Lib.Helper.StringHelper.ToValidFileName(name); if (File.Exists(exportfile)) { var allbytes = System.IO.File.ReadAllBytes(path); BinaryResponse response = new BinaryResponse(); response.ContentType = "application/zip"; response.Headers.Add("Content-Disposition", $"attachment;filename={name}.zip"); response.BinaryBytes = allbytes; return(response); } return(null); }
protected override bool ProcessResponse(BinaryResponse response) { base.ProcessResponse(response); if (!GuessResponseState(response, out this.state)) { return(false); } return(true); }
protected override bool ProcessResponse(BinaryResponse response) { var r = base.ProcessResponse(response); if (this.locator != null && !VBucketAwareOperationFactory.GuessResponseState(response, out this.state)) { return(false); } return(r); }
public static T WithResponse <T>(this T self, BinaryResponse response, string failMessage = null) where T : IOperationResult { var success = response.StatusCode == 0; self.StatusCode = response.StatusCode; self.Success = success; self.Message = success ? null : response.GetStatusMessage() ?? failMessage; self.Cas = response.CAS; return(self); }
protected override IOperationResult ProcessResponse(BinaryResponse response) { base.ProcessResponse(response); var result = new BinaryOperationResult(); if (!GuessResponseState(response, out this.state)) { var message = ResultHelper.ProcessResponseData(response.Data, "Failed to process response"); return(result.Fail(message)); } return(result.Pass()); }
protected override IOperationResult ProcessResponse(BinaryResponse response) { var r = response.StatusCode == 0; var result = new BinaryOperationResult(); if (this.locator != null && !VBucketAwareOperationFactory.GuessResponseState(response, out this.state)) { return(result.Fail("Process response failed")); } return(result.PassOrFail(r, "Processing response failed")); }
protected override bool ReadResponse(PooledSocket socket) { var response = new BinaryResponse(); if (response.Read(socket)) { this.Result = DecodeResult(response.Data); return(true); } return(false); }
protected override IOperationResult ProcessResponse(BinaryResponse response) { var r = base.ProcessResponse(response); var result = new BinaryOperationResult(); if (this.locator != null && !VBucketAwareOperationFactory.GuessResponseState(response, out this.state)) { return(result.Fail("Failed to process response")); } return(r); }
public static BinaryOperationResult FromResponse(BinaryResponse response, string failMessage = null) { var success = response.StatusCode == 0; var retval = new BinaryOperationResult { StatusCode = response.StatusCode, Success = success, Message = success ? null : response.GetStatusMessage() ?? failMessage, Cas = response.CAS }; return(retval); }
// formate. msgfile/{messageid}/filename. public BinaryResponse MsgFile(ApiCall call) { string filename = null; int messageid = 0; var para = call.Command.Parameters; if (para.Count() == 2) { messageid = Convert.ToInt32(para[0]); filename = System.Web.HttpUtility.UrlDecode(para[1]); } else { messageid = Convert.ToInt32(call.Command.Value); } var maildb = Kooboo.Mail.Factory.DBFactory.UserMailDb(call.Context.User); var content = maildb.Messages.GetContent(messageid); if (!string.IsNullOrEmpty(content)) { if (!string.IsNullOrEmpty(filename)) { var bytes = Kooboo.Mail.Utility.MessageUtility.GetFileBinary(content, filename); if (bytes != null && bytes.Length > 0) { var response = new BinaryResponse(); response.ContentType = Kooboo.Lib.Compatible.CompatibleManager.Instance.Framework.GetMimeMapping(filename); response.Headers.Add("Content-Disposition", $"filename={System.Web.HttpUtility.UrlEncode(filename)}"); response.BinaryBytes = bytes; return(response); } } else { var bytes = Mail.Utility.MessageUtility.GenerateAllAttachmentZip(content); var response = new BinaryResponse(); response.ContentType = "application/zip"; response.Headers.Add("Content-Disposition", $"filename=attachment.zip"); response.BinaryBytes = bytes; return(response); } } return(null); }
internal static bool GuessResponseState(BinaryResponse response, out OperationState state) { switch (response.StatusCode) { case 0: state = OperationState.Success; return(true); case 7: state = OperationState.InvalidVBucket; break; default: state = OperationState.Failure; break; } return(false); }
public void RenderBinary(RenderContext context, BinaryResponse resposne) { if (resposne == null) { return; } context.Response.ContentType = resposne.ContentType; context.Response.StatusCode = 200; foreach (var item in resposne.Headers) { string value = string.Join("", item.Value); context.Response.Headers.Add(item.Key, value); } context.Response.Body = resposne.BinaryBytes; }
protected override IOperationResult ReadResponse(PooledSocket socket) { var response = new BinaryResponse(); var result = new BinaryOperationResult(); if (response.Read(socket)) { this.Result = DecodeResult(response.Data); result.Pass(); return(result); } result.Fail("Processing of response failed"); return(result); }
//attachment image. public BinaryResponse File(ApiCall call) { string filename = call.Command.Value; var bytes = Kooboo.Mail.MultiPart.FileService.Get(call.Context.User, filename); if (bytes != null && bytes.Length > 0) { var response = new BinaryResponse(); response.ContentType = Kooboo.Lib.Compatible.CompatibleManager.Instance.Framework.GetMimeMapping(filename); response.Headers.Add("Content-Disposition", $"filename={System.Web.HttpUtility.UrlEncode(filename)}"); response.BinaryBytes = bytes; return(response); } return(null); }
internal BinaryResponse ReadBinaryResponse() { BinaryResponse response = new BinaryResponse(); response.Read(stream); switch (response.ResponseCode) { case ErrorCode.InvalidArguments: case ErrorCode.InvalidIncrTarget: case ErrorCode.OutOfMemory: case ErrorCode.ValueTooLarge: throw new MemcachedClientException("Server returned: " + response.ValueAsString); default: return(response); } }
protected override bool ProcessResponse(BinaryResponse response) { base.ProcessResponse(response); var r = response.StatusCode == 0; this.state = r ? OperationState.Success : OperationState.Failure; if (!r) { if (response.GetStatusMessage() == NotMyVBucket) { this.state = OperationState.InvalidVBucket; } } return(r); }
public BinaryResponse DownloadBatch(Guid id, ApiCall call) { var site = call.WebSite; var path = Web.Cache.TempDownloadZip.GetPath(id); if (path != null && File.Exists(path)) { var allbytes = System.IO.File.ReadAllBytes(path); BinaryResponse response = new BinaryResponse(); response.ContentType = "application/zip"; response.Headers.Add("Content-Disposition", $"attachment;filename={site.Name}_part.zip"); response.BinaryBytes = allbytes; return(response); } return(null); }
protected override IOperationResult ProcessResponse(BinaryResponse response) { var status = response.StatusCode; var result = new BinaryOperationResult(); this.StatusCode = status; if (status == 0) { this.Cas = response.CAS; return(result.Pass()); } this.Cas = 0; var message = ResultHelper.ProcessResponseData(response.Data); return(result.Fail(message)); }
protected override bool ReadResponseAsync(PooledSocket socket, Action <bool> next) { var response = new BinaryResponse(); bool ioPending; var retval = response.ReadAsync(socket, (readSuccess) => { if (readSuccess) { this.DecodeResult(response.Data); } next(readSuccess); }, out ioPending); if (!ioPending && retval) { this.Result = this.DecodeResult(response.Data); } return(retval); }
public override IResponse receiveAnswer() { try { byte[] header = new byte[BinaryResponse.HEADER_LENTGH]; log.Info("recieving an answer..."); int n = socket.Receive(header, BinaryResponse.HEADER_LENTGH, System.Net.Sockets.SocketFlags.None); if (n != BinaryResponse.HEADER_LENTGH) { // maybe wait for a while? log.Error("error reading header from device!"); throw new InvalidDataException(); } BinaryResponse.OP op = (BinaryResponse.OP)BitConverter.ToInt32(header, 0); UInt32 dataLen = BitConverter.ToUInt32(header, 4); BinaryResponse answer = BinaryResponse.newDeviceAnswer(op); if (answer == null) { throw new ArgumentNullException("error in response parsing, is the OPCODE missing? {" + op.ToString() + "}"); } log.Info("got answer of type: " + op.ToString()); n = 0; byte[] data = new byte[dataLen]; log.Info("data len: " + dataLen.ToString()); while (dataLen - n > 0) { n += socket.Receive(data, n, (int)(dataLen - n), System.Net.Sockets.SocketFlags.Partial); log.Info("read " + n.ToString()); } answer.fromByteArray(header, data); return(answer); } catch (Exception ex) { throw ex; } }
public void Process(ISemanticProcessor proc, IMembrane membrane, BinaryResponse resp) { resp.Context.Response.ContentLength64 = resp.BinaryData.Length; resp.Context.Response.Write(resp.BinaryData, resp.ContentType); }
internal async Task <BinaryResponse> UrlGetToBinaryWithProgress(string request, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) { if (string.IsNullOrEmpty(request) || (maxTries == 0)) { return(null); } BinaryResponse result = null; for (byte i = 0; i < maxTries; i++) { const byte printPercentage = 10; const byte maxBatches = 99 / printPercentage; await using StreamResponse response = await UrlGetToStream(request, referer, requestOptions | ERequestOptions.ReturnClientErrors, 1).ConfigureAwait(false); if (response?.StatusCode.IsClientErrorCode() == true) { if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { result = new BinaryResponse(response); } break; } if (response?.Content == null) { continue; } #if !NETFRAMEWORK await #endif using MemoryStream ms = new MemoryStream((int)response.Length); try { byte batch = 0; uint readThisBatch = 0; byte[] buffer = new byte[8192]; // This is HttpClient's buffer, using more doesn't make sense while (response.Content.CanRead) { int read = await response.Content.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (read == 0) { break; } await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false); if ((response.Length == 0) || (batch >= maxBatches)) { continue; } readThisBatch += (uint)read; if (readThisBatch < response.Length / printPercentage) { continue; } readThisBatch -= response.Length / printPercentage; } } catch (Exception) { return(null); } return(new BinaryResponse(response, ms.ToArray())); } if (maxTries > 1) { } return(result); }
public override IResponse receiveAnswer(CancellationToken ct) { Queue dataQ = new Queue(); Byte [] b = new byte[1]; log.Info("recieving an answer..."); int n = 0; bool fullMessage = false; port.ReadTimeout = 1000; while (!fullMessage) { /* check the cancellation token */ ct.ThrowIfCancellationRequested(); try { n = port.Read(b, 0, 1); } catch (TimeoutException) { /* this is ok, continue to next iteration */ continue; } if (n > 0) { if (b[0] == CHAR_FLAG) { if (dataQ.Count > 1) /* op + crc */ { fullMessage = true; } else { dataQ.Clear(); } } else { dataQ.Enqueue(b[0]); } } } byte[] data = new byte[dataQ.Count]; Array.Copy(dataQ.ToArray(), data, dataQ.Count); log.Info("got: " + BitConverter.ToString(data).Replace("-", " ")); byte[] strippedData = restore_received_data(data); if (strippedData == null) { log.Error("error in recieved bitstream!"); throw new RFC1662Exception(); } BinaryResponse.OP op = (BinaryResponse.OP)strippedData[0]; BinaryResponse answer = BinaryResponse.newDeviceAnswer(op); if (answer == null) { throw new UnknownOPException(); } log.Info("got answer of type: " + op.ToString("X")); answer.fromByteArray(strippedData); return(answer); }