本文整理汇总了C#中ResponseStream类的典型用法代码示例。如果您正苦于以下问题:C# ResponseStream类的具体用法?C# ResponseStream怎么用?C# ResponseStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ResponseStream类属于命名空间,在下文中一共展示了ResponseStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Write
public static void Write(this NetworkStream stream, ResponseStream data)
{
byte[] buffer = new byte[10000];
try
{
while (!data.End && stream.CanWrite)
{
var len = data.GetChunk(buffer);
stream.Write(buffer, 0, len);
}
stream.Flush();
}
catch (Exception ex)
{
ConsoleUtils.WriteLn(ex);
}
}
示例2: Response
public Response(CancellationToken clientToken, Action flush)
{
_clientToken = clientToken;
_stream = new ResponseStream();
_flush = flush;
}
示例3: setResponseStream
public override void setResponseStream (ResponseStream __p1) {
_facesContex.setResponseStream (__p1);
}
示例4: RequestState
internal RequestState(HttpRequestMessage request, PathString pathBase)
{
_request = request;
_responseTcs = new TaskCompletionSource<HttpResponseMessage>();
_requestAbortedSource = new CancellationTokenSource();
_pipelineFinished = false;
if (request.RequestUri.IsDefaultPort)
{
request.Headers.Host = request.RequestUri.Host;
}
else
{
request.Headers.Host = request.RequestUri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped);
}
HttpContext = new DefaultHttpContext();
HttpContext.Features.Set<IHttpRequestFeature>(new RequestFeature());
_responseFeature = new ResponseFeature();
HttpContext.Features.Set<IHttpResponseFeature>(_responseFeature);
var serverRequest = HttpContext.Request;
serverRequest.Protocol = "HTTP/" + request.Version.ToString(2);
serverRequest.Scheme = request.RequestUri.Scheme;
serverRequest.Method = request.Method.ToString();
var fullPath = PathString.FromUriComponent(request.RequestUri);
PathString remainder;
if (fullPath.StartsWithSegments(pathBase, out remainder))
{
serverRequest.PathBase = pathBase;
serverRequest.Path = remainder;
}
else
{
serverRequest.PathBase = PathString.Empty;
serverRequest.Path = fullPath;
}
serverRequest.QueryString = QueryString.FromUriComponent(request.RequestUri);
foreach (var header in request.Headers)
{
serverRequest.Headers.Append(header.Key, header.Value.ToArray());
}
var requestContent = request.Content;
if (requestContent != null)
{
foreach (var header in request.Content.Headers)
{
serverRequest.Headers.Append(header.Key, header.Value.ToArray());
}
}
_responseStream = new ResponseStream(ReturnResponseMessage, AbortRequest);
HttpContext.Response.Body = _responseStream;
HttpContext.Response.StatusCode = 200;
HttpContext.RequestAborted = _requestAbortedSource.Token;
}
示例5: ConvertFile
private static string ConvertFile(string downloadUrl, string fromExt, Token token)
{
Global.Logger.Debug("GoogleDriveApp: convert file");
if (string.IsNullOrEmpty(downloadUrl))
{
Global.Logger.Error("GoogleDriveApp: downloadUrl is null");
throw new Exception("downloadUrl is null");
}
var request = WebRequest.Create(downloadUrl);
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + token);
try
{
using (var response = request.GetResponse())
using (var fileStream = new ResponseStream(response))
{
Global.Logger.Debug("GoogleDriveApp: GetExternalUri - " + downloadUrl);
var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
downloadUrl = DocumentServiceConnector.GetExternalUri(fileStream, response.ContentType, key);
}
}
catch (WebException e)
{
Global.Logger.Error("GoogleDriveApp: Error GetExternalUri", e);
request.Abort();
}
var toExt = FileUtility.GetInternalExtension(fromExt);
try
{
Global.Logger.Debug("GoogleDriveApp: GetConvertedUri- " + downloadUrl);
var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
DocumentServiceConnector.GetConvertedUri(downloadUrl, fromExt, toExt, key, false, out downloadUrl);
}
catch (Exception e)
{
Global.Logger.Error("GoogleDriveApp: Error GetConvertedUri", e);
}
return downloadUrl;
}
示例6: StreamFile
private static void StreamFile(HttpContext context)
{
try
{
var fileId = context.Request[FilesLinkUtility.FileId];
var auth = context.Request[FilesLinkUtility.AuthKey];
var userId = context.Request[CommonLinkUtility.ParamName_UserUserID];
Global.Logger.Debug("GoogleDriveApp: get file stream " + fileId);
int validateTimespan;
int.TryParse(WebConfigurationManager.AppSettings["files.stream-url-minute"], out validateTimespan);
if (validateTimespan <= 0) validateTimespan = 5;
var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId + userId, auth, TimeSpan.FromMinutes(validateTimespan));
if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
{
var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException);
Global.Logger.Error(string.Format("GoogleDriveApp: validate error {0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url), exc);
throw exc;
}
var token = Token.GetToken(AppAttr, userId);
var driveFile = GetDriveFile(fileId, token);
var jsonFile = JObject.Parse(driveFile);
var downloadUrl = jsonFile.Value<string>("downloadUrl");
var contentLength = jsonFile.Value<string>("fileSize");
if (string.IsNullOrEmpty(downloadUrl))
{
Global.Logger.Error("GoogleDriveApp: downloadUrl is null");
throw new Exception("downloadUrl is null");
}
Global.Logger.Debug("GoogleDriveApp: get file stream downloadUrl - " + downloadUrl);
var request = WebRequest.Create(downloadUrl);
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + token);
using (var response = request.GetResponse())
using (var stream = new ResponseStream(response))
{
stream.StreamCopyTo(context.Response.OutputStream);
Global.Logger.Debug("GoogleDriveApp: get file stream contentLength - " + contentLength);
context.Response.AddHeader("Content-Length", contentLength);
}
}
catch (Exception ex)
{
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Response.Write(ex.Message);
Global.Logger.Error("GoogleDriveApp: Error request " + context.Request.Url, ex);
}
try
{
context.Response.Flush();
context.Response.End();
}
catch (HttpException)
{
}
}
示例7: Close
internal void Close(bool force_close)
{
if (sock != null) {
Stream st = GetResponseStream ();
st.Close ();
o_stream = null;
}
if (sock != null) {
force_close |= !context.Request.KeepAlive;
if (!force_close)
force_close = (context.Response.Headers ["connection"] == "close");
/*
if (!force_close) {
// bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
// status_code == 413 || status_code == 414 || status_code == 500 ||
// status_code == 503);
force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
}
*/
if (!force_close && context.Request.FlushInput ()) {
if (chunked && context.Response.ForceCloseChunked == false) {
// Don't close. Keep working.
reuses++;
Unbind ();
Init ();
BeginReadRequest ();
return;
}
reuses++;
Unbind ();
Init ();
BeginReadRequest ();
return;
}
Socket s = sock;
sock = null;
try {
if (s != null)
s.Shutdown (SocketShutdown.Both);
} catch {
} finally {
if (s != null)
s.Close ();
}
Unbind ();
RemoveConnection ();
return;
}
}
示例8: GetResponseStream
public ResponseStream GetResponseStream()
{
// TODO: can we get this stream before reading the input?
if (o_stream == null) {
HttpListener listener = context.Listener;
bool ign = (listener == null) ? true : listener.IgnoreWriteExceptions;
o_stream = new ResponseStream (stream, context.Response, ign);
}
return o_stream;
}
示例9: StoringFileAfterError
private static void StoringFileAfterError(string fileId, string userId, string downloadUri)
{
try
{
var fileName = fileId + FileUtility.GetFileExtension(downloadUri);
var path = string.Format(@"save_crash\{0}\{1}_{2}",
DateTime.UtcNow.ToString("yyyy_MM_dd"),
userId,
fileName);
var store = Global.GetStore();
var req = (HttpWebRequest)WebRequest.Create(downloadUri);
using (var fileStream = new ResponseStream(req.GetResponse()))
{
store.Save(FileConstant.StorageDomainTmp, path, fileStream);
}
Global.Logger.DebugFormat("DocService storing to {0}", path);
}
catch (Exception ex)
{
Global.Logger.Error("DocService Error on save file to temp store", ex);
}
}
示例10: PageLoad
private void PageLoad()
{
var editPossible = !RequestEmbedded && !IsMobile;
var isExtenral = false;
File file;
var fileUri = string.Empty;
if (!ItsTry)
{
try
{
if (string.IsNullOrEmpty(RequestFileUrl))
{
_fileNew = !string.IsNullOrEmpty(Request[UrlConstant.New]) && Request[UrlConstant.New] == "true";
var ver = string.IsNullOrEmpty(Request[CommonLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[CommonLinkUtility.Version]);
file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, _fileNew, editPossible, !RequestView, out _docParams);
_fileNew = file.Version == 1 && file.ConvertedType != null && _fileNew && file.CreateOn == file.ModifiedOn;
}
else
{
isExtenral = true;
fileUri = RequestFileUrl;
var fileTitle = Request[CommonLinkUtility.FileTitle];
if (string.IsNullOrEmpty(fileTitle))
fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
if (CoreContext.Configuration.Standalone)
{
try
{
var webRequest = WebRequest.Create(RequestFileUrl);
using (var response = webRequest.GetResponse())
using (var responseStream = new ResponseStream(response))
{
fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), "new");
}
}
catch (Exception error)
{
Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
}
}
file = new File
{
ID = fileUri.GetHashCode(),
Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
};
file = DocumentServiceHelper.GetParams(file, true, true, true, false, false, false, out _docParams);
_docParams.CanEdit = editPossible && !CoreContext.Configuration.Standalone;
_editByUrl = true;
_docParams.FileUri = fileUri;
}
}
catch (Exception ex)
{
_errorMessage = ex.Message;
return;
}
}
else
{
FileType tryType;
try
{
tryType = (FileType)Enum.Parse(typeof(FileType), Request[CommonLinkUtility.TryParam]);
}
catch
{
tryType = FileType.Document;
}
var fileTitle = "Demo";
fileTitle += FileUtility.InternalExtension[tryType];
var relativeUri = string.Format(CommonLinkUtility.FileHandlerPath + UrlConstant.ParamsDemo, tryType);
fileUri = new Uri(Request.Url, relativeUri).ToString();
file = new File
{
ID = Guid.NewGuid(),
Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
};
file = DocumentServiceHelper.GetParams(file, true, true, true, editPossible, editPossible, true, out _docParams);
_docParams.FileUri = fileUri;
_editByUrl = true;
}
if (_docParams.ModeWrite && FileConverter.MustConvert(file))
{
try
{
//.........这里部分代码省略.........
示例11: RequestState
internal RequestState(HttpRequestMessage request, CancellationToken cancellationToken)
{
_request = request;
_responseTcs = new TaskCompletionSource<HttpResponseMessage>();
_sendingHeaders = () => { };
if (request.RequestUri.IsDefaultPort)
{
request.Headers.Host = request.RequestUri.Host;
}
else
{
request.Headers.Host = request.RequestUri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped);
}
OwinContext = new OwinContext();
OwinContext.Set("owin.Version", "1.0");
IOwinRequest owinRequest = OwinContext.Request;
owinRequest.Protocol = "HTTP/" + request.Version.ToString(2);
owinRequest.Scheme = request.RequestUri.Scheme;
owinRequest.Method = request.Method.ToString();
owinRequest.Path = PathString.FromUriComponent(request.RequestUri);
owinRequest.PathBase = PathString.Empty;
owinRequest.QueryString = QueryString.FromUriComponent(request.RequestUri);
owinRequest.CallCancelled = cancellationToken;
owinRequest.Set<Action<Action<object>, object>>("server.OnSendingHeaders", (callback, state) =>
{
var prior = _sendingHeaders;
_sendingHeaders = () =>
{
prior();
callback(state);
};
});
foreach (var header in request.Headers)
{
owinRequest.Headers.AppendValues(header.Key, header.Value.ToArray());
}
HttpContent requestContent = request.Content;
if (requestContent != null)
{
foreach (var header in request.Content.Headers)
{
owinRequest.Headers.AppendValues(header.Key, header.Value.ToArray());
}
}
_responseStream = new ResponseStream(CompleteResponse);
OwinContext.Response.Body = _responseStream;
OwinContext.Response.StatusCode = 200;
}
示例12: CreateFileFromUri
private static File CreateFileFromUri(Folder folder, string fileUri, string fileTitle)
{
if (string.IsNullOrEmpty(fileTitle))
fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri));
var file = new File
{
Title = fileTitle,
FolderID = folder.ID
};
var req = (HttpWebRequest)WebRequest.Create(fileUri);
using (var fileDao = Global.DaoFactory.GetFileDao())
using (var fileStream = new ResponseStream(req.GetResponse()))
{
file.ContentLength = fileStream.Length;
return fileDao.SaveFile(file, fileStream);
}
}
示例13: SaveFile
public void SaveFile(string fileId, string downloadUrl)
{
Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId + " from - " + downloadUrl);
fileId = ThirdPartySelector.GetFileId(fileId);
var token = Token.GetToken(AppAttr);
var driveFile = GetDriveFile(fileId, token);
if (driveFile == null)
{
Global.Logger.Error("GoogleDriveApp: file is null");
throw new Exception("File not found");
}
var jsonFile = JObject.Parse(driveFile);
var curExt = GetCorrectExt(jsonFile);
var newExt = FileUtility.GetFileExtension(downloadUrl);
if (curExt != newExt)
{
try
{
Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + newExt + " to " + curExt + " - " + downloadUrl);
var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
DocumentServiceConnector.GetConvertedUri(downloadUrl, newExt, curExt, key, false, out downloadUrl);
}
catch (Exception e)
{
Global.Logger.Error("GoogleDriveApp: Error convert", e);
}
}
var downloadRequest = WebRequest.Create(downloadUrl);
using (var downloadResponse = downloadRequest.GetResponse())
using (var downloadStream = new ResponseStream(downloadResponse))
{
var request = (HttpWebRequest)WebRequest.Create(GoogleUrlUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId));
request.Method = "PUT";
request.Headers.Add("Authorization", "Bearer " + token);
request.ContentType = downloadResponse.ContentType;
request.ContentLength = downloadResponse.ContentLength;
const int bufferSize = 2048;
var buffer = new byte[bufferSize];
int readed;
while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0)
{
request.GetRequestStream().Write(buffer, 0, readed);
}
try
{
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
var result = stream != null ? new StreamReader(stream).ReadToEnd() : null;
Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result);
}
}
catch (WebException e)
{
Global.Logger.Error("GoogleDriveApp: Error save file stream", e);
request.Abort();
var httpResponse = (HttpWebResponse)e.Response;
if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
{
throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
}
throw;
}
}
}
示例14: CreateFile
private static string CreateFile(string contentUrl, string fileName, string folderId, Token token)
{
if (string.IsNullOrEmpty(contentUrl))
{
Global.Logger.Error("GoogleDriveApp: downloadUrl is null");
throw new Exception("downloadUrl is null");
}
Global.Logger.Debug("GoogleDriveApp: create from - " + contentUrl);
var request = WebRequest.Create(contentUrl);
using (var response = request.GetResponse())
using (var content = new ResponseStream(response))
{
return CreateFile(content, fileName, folderId, token);
}
}
示例15: StoringFileAfterError
private static void StoringFileAfterError(string fileId, string userId, string downloadUri)
{
try
{
var fileName = Global.ReplaceInvalidCharsAndTruncate(fileId + FileUtility.GetFileExtension(downloadUri));
var path = string.Format(@"save_crash\{0}\{1}_{2}",
DateTime.UtcNow.ToString("yyyy_MM_dd"),
userId,
fileName);
var store = Global.GetStore();
var req = (HttpWebRequest) WebRequest.Create(downloadUri);
// hack. http://ubuntuforums.org/showthread.php?t=1841740
if (WorkContext.IsMono)
{
ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
}
using (var fileStream = new ResponseStream(req.GetResponse()))
{
store.Save(FileConstant.StorageDomainTmp, path, fileStream);
}
Global.Logger.DebugFormat("DocService storing to {0}", path);
}
catch (Exception ex)
{
Global.Logger.Error("DocService Error on save file to temp store", ex);
}
}