public PrintSCPService(System.IO.Stream stream, Dicom.Log.Logger log) : base(stream, log) { var pi = stream.GetType().GetProperty("Socket", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (pi != null) { var endPoint = ((System.Net.Sockets.Socket)pi.GetValue(stream, null)).RemoteEndPoint as System.Net.IPEndPoint; CallingIP = endPoint.Address.ToString(); } else { CallingIP = "127, 0, 0, 1"; } }
public PrintService(System.IO.Stream stream, Dicom.Log.Logger log) : base(stream, log) { var pi = stream.GetType().GetProperty("Socket", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (pi != null) { var endPoint = ((System.Net.Sockets.Socket)pi.GetValue(stream, null)).RemoteEndPoint as System.Net.IPEndPoint; RemoteIP = endPoint.Address; } else { RemoteIP = new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }); } }
public static async Task UploadDocumentAsync(string webUrl, string bearerToken, System.IO.Stream document, string folderServerRelativeUrl, string fileName) { try { const string SharePointUploadRestApi = "{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/add(url='{2}',overwrite=true)"; string SharePointUploadUrl = string.Format(SharePointUploadRestApi, webUrl, folderServerRelativeUrl, fileName); using (var handler = new HttpClientHandler()) { using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("Accept", "application/json;odata=nometadata"); client.DefaultRequestHeaders.Add("binaryStringRequestBody", "true"); client.MaxResponseContentBufferSize = 2147483647; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); //Creating Content var destination = new System.IO.MemoryStream(); if (document.GetType() != typeof(System.IO.MemoryStream)) { document.CopyTo(destination); } else { destination = document as System.IO.MemoryStream; } ByteArrayContent content = new ByteArrayContent(destination?.ToArray()); //Perform post HttpResponseMessage response = await client.PostAsync(SharePointUploadUrl, content).ConfigureAwait(false); //Ensure 200 (Ok) response.EnsureSuccessStatusCode(); } } } catch (Exception ex) { throw new ApplicationException($"Error uploading document {fileName} call on folder {folderServerRelativeUrl}. {ex.Message}", ex); } finally { document?.Dispose(); } }
public void Put(string remotename, System.IO.Stream stream) { TempFile tmp = null; // A bit dirty, but we need the underlying stream to compute the hash without any interference var measure = stream; while (measure is OverrideableStream) { measure = typeof(OverrideableStream).GetField("m_basestream", System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(measure) as System.IO.Stream; } if (measure == null) { throw new Exception(string.Format("Unable to unwrap stream from: {0}", stream.GetType())); } string sha1; if (measure.CanSeek) { // Record the stream position var p = measure.Position; // Compute the hash using (var hashalg = Duplicati.Library.Utility.HashAlgorithmHelper.Create("sha1")) sha1 = Library.Utility.Utility.ByteArrayAsHexString(hashalg.ComputeHash(measure)); // Reset the stream position measure.Position = p; } else { // No seeking possible, use a temp file tmp = new TempFile(); using (var sr = System.IO.File.OpenWrite(tmp)) using (var hc = new HashCalculatingStream(measure, "sha1")) { Library.Utility.Utility.CopyStream(hc, sr); sha1 = hc.GetFinalHashString(); } stream = System.IO.File.OpenRead(tmp); } if (m_filecache == null) { List(); } try { var fileinfo = m_helper.GetJSONData <UploadFileResponse>( UploadUrlData.UploadUrl, req => { req.Method = "POST"; req.Headers["Authorization"] = UploadUrlData.AuthorizationToken; req.Headers["X-Bz-Content-Sha1"] = sha1; req.Headers["X-Bz-File-Name"] = m_urlencodedprefix + Utility.Uri.UrlPathEncode(remotename); req.ContentType = "application/octet-stream"; req.ContentLength = stream.Length; }, req => { using (var rs = req.GetRequestStream()) Utility.Utility.CopyStream(stream, rs); } ); // Delete old versions if (m_filecache.ContainsKey(remotename)) { Delete(remotename); } m_filecache[remotename] = new List <FileEntity>(); m_filecache[remotename].Add(new FileEntity() { FileID = fileinfo.FileID, FileName = fileinfo.FileName, Action = "upload", Size = fileinfo.ContentLength, UploadTimestamp = (long)(DateTime.UtcNow - Utility.Utility.EPOCH).TotalMilliseconds }); } catch (Exception ex) { m_filecache = null; var code = (int)B2AuthHelper.GetExceptionStatusCode(ex); if (code >= 500 && code <= 599) { m_uploadUrl = null; } throw; } finally { try { if (tmp != null) { tmp.Dispose(); } } catch { } } }
public async Task PutAsync(string remotename, System.IO.Stream stream, CancellationToken cancelToken) { // Some challenges with uploading to Jottacloud: // - Jottacloud supports use of a custom header where we can tell the server the MD5 hash of the file // we are uploading, and then it will verify the content of our request against it. But the HTTP // status code we get back indicates success even if there is a mismatch, so we must dig into the // XML response to see if we were able to correctly upload the new content or not. Another issue // is that if the stream is not seek-able we have a challenge pre-calculating MD5 hash on it before // writing it out on the HTTP request stream. And even if the stream is seek-able it may be throttled. // One way to avoid using the throttled stream for calculating the MD5 is to try to get the // underlying stream from the "m_basestream" field, with fall-back to a temporary file. // - We can instead chose to upload the data without setting the MD5 hash header. The server will // calculate the MD5 on its side and return it in the response back to use. We can then compare it // with the MD5 hash of the stream (using a MD5CalculatingStream), and if there is a mismatch we can // request the server to remove the file again and throw an exception. But there is a requirement that // we specify the file size in a custom header. And if the stream is not seek-able we are not able // to use stream.Length, so we are back at square one. Duplicati.Library.Utility.TempFile tmpFile = null; var baseStream = stream; while (baseStream is Duplicati.Library.Utility.OverrideableStream) { baseStream = typeof(Duplicati.Library.Utility.OverrideableStream).GetField("m_basestream", System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(baseStream) as System.IO.Stream; } if (baseStream == null) { throw new Exception(string.Format("Unable to unwrap stream from: {0}", stream.GetType())); } string md5Hash; if (baseStream.CanSeek) { var originalPosition = baseStream.Position; using (var md5 = System.Security.Cryptography.MD5.Create()) md5Hash = Library.Utility.Utility.ByteArrayAsHexString(md5.ComputeHash(baseStream)); baseStream.Position = originalPosition; } else { // No seeking possible, use a temp file tmpFile = new Duplicati.Library.Utility.TempFile(); using (var os = System.IO.File.OpenWrite(tmpFile)) using (var md5 = new Utility.MD5CalculatingStream(baseStream)) { await Utility.Utility.CopyStreamAsync(md5, os, true, cancelToken, m_copybuffer); md5Hash = md5.GetFinalHashString(); } stream = System.IO.File.OpenRead(tmpFile); } try { // Create request, with query parameter, and a few custom headers. // NB: If we wanted to we could send the same POST request as below but without the file contents // and with "cphash=[md5Hash]" as the only query parameter. Then we will get an HTTP 200 (OK) response // if an identical file already exists, and we can skip uploading the new file. We will get // HTTP 404 (Not Found) if file does not exists or it exists with a different hash, in which // case we must send a new request to upload the new content. var fileSize = stream.Length; var req = CreateRequest(System.Net.WebRequestMethods.Http.Post, remotename, "umode=nomultipart", true); req.Headers.Add("JMd5", md5Hash); // Not required, but it will make the server verify the content and mark the file as corrupt if there is a mismatch. req.Headers.Add("JSize", fileSize.ToString()); // Required, and used to mark file as incomplete if we upload something be the total size of the original file! // File time stamp headers: Since we are working with a stream here we do not know the local file's timestamps, // and then we can just omit the JCreated and JModified and let the server automatically set the current time. //req.Headers.Add("JCreated", timeCreated); //req.Headers.Add("JModified", timeModified); req.ContentType = "application/octet-stream"; req.ContentLength = fileSize; // Write post data request var areq = new Utility.AsyncHttpRequest(req); using (var rs = areq.GetRequestStream()) await Utility.Utility.CopyStreamAsync(stream, rs, true, cancelToken, m_copybuffer); // Send request, and check response using (var resp = (System.Net.HttpWebResponse)areq.GetResponse()) { if (resp.StatusCode != System.Net.HttpStatusCode.Created) { throw new System.Net.WebException(Strings.Jottacloud.FileUploadError, null, System.Net.WebExceptionStatus.ProtocolError, resp); } // Request seems to be successful, but we must verify the response XML content to be sure that the file // was correctly uploaded: The server will verify the JSize header and mark the file as incomplete if // there was mismatch, and it will verify the JMd5 header and mark the file as corrupt if there was a hash // mismatch. The returned XML contains a file element, and if upload was error free it contains a single // child element "currentRevision", which has a "state" child element with the string "COMPLETED". // If there was a problem we should have a "latestRevision" child element, and this will have state with // value "INCOMPLETE" or "CORRUPT". If the file was new or had no previous complete versions the latestRevision // will be the only child, but if not there may also be a "currentRevision" representing the previous // complete version - and then we need to detect the case where our upload failed but there was an existing // complete version! using (var rs = areq.GetResponseStream()) { var doc = new System.Xml.XmlDocument(); try { doc.Load(rs); } catch (System.Xml.XmlException) { throw new System.Net.WebException(Strings.Jottacloud.FileUploadError, System.Net.WebExceptionStatus.ProtocolError); } bool uploadCompletedSuccessfully = false; var xFile = doc["file"]; if (xFile != null) { var xRevState = xFile.SelectSingleNode("latestRevision"); if (xRevState == null) { xRevState = xFile.SelectSingleNode("currentRevision/state"); if (xRevState != null) { uploadCompletedSuccessfully = xRevState.InnerText == "COMPLETED"; // Success: There is no "latestRevision", only a "currentRevision" (and it specifies the file is complete, but I think it always will). } } } if (!uploadCompletedSuccessfully) // Report error (and we just let the incomplete/corrupt file revision stay on the server..) { throw new System.Net.WebException(Strings.Jottacloud.FileUploadError, System.Net.WebExceptionStatus.ProtocolError); } } } } finally { try { if (tmpFile != null) { tmpFile.Dispose(); } } catch { } } }
/// <summary> /// Transfer file data /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="uploadSessionId"></param> /// <param name="guid"></param> /// <param name="uploadOffset">Upload offset, bytes.</param> /// <param name="tusResumable">1.0.0</param> /// <param name="force">Upload a file even if it exists. (optional)</param> /// <param name="body"> (optional)</param> /// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param> /// <returns>Task of ApiResponse (InlineResponse400)</returns> public async System.Threading.Tasks.Task <ApiResponse <InlineResponse400> > TusUploadSessionUploadSessionIdUploadGuidPATCHWithHttpInfoAsync(string uploadSessionId, string guid, int uploadOffset, string tusResumable, bool?force = default(bool?), System.IO.Stream body = default(System.IO.Stream), CancellationToken cancellationToken = default(CancellationToken)) { // verify the required parameter 'uploadSessionId' is set if (uploadSessionId == null) { throw new ApiException(400, "Missing required parameter 'uploadSessionId' when calling TusApi->TusUploadSessionUploadSessionIdUploadGuidPATCH"); } // verify the required parameter 'guid' is set if (guid == null) { throw new ApiException(400, "Missing required parameter 'guid' when calling TusApi->TusUploadSessionUploadSessionIdUploadGuidPATCH"); } // verify the required parameter 'uploadOffset' is set if (uploadOffset == null) { throw new ApiException(400, "Missing required parameter 'uploadOffset' when calling TusApi->TusUploadSessionUploadSessionIdUploadGuidPATCH"); } // verify the required parameter 'tusResumable' is set if (tusResumable == null) { throw new ApiException(400, "Missing required parameter 'tusResumable' when calling TusApi->TusUploadSessionUploadSessionIdUploadGuidPATCH"); } var localVarPath = "/api/v1/tus/upload-session/{upload_session_id}/upload/{guid}/"; var localVarPathParams = new Dictionary <String, String>(); var localVarQueryParams = new List <KeyValuePair <String, String> >(); var localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary <String, String>(); var localVarFileParams = new Dictionary <String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/offset+octet-stream" }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) { localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); } if (uploadSessionId != null) { localVarPathParams.Add("upload_session_id", this.Configuration.ApiClient.ParameterToString(uploadSessionId)); // path parameter } if (guid != null) { localVarPathParams.Add("guid", this.Configuration.ApiClient.ParameterToString(guid)); // path parameter } if (force != null) { localVarHeaderParams.Add("force", this.Configuration.ApiClient.ParameterToString(force)); // header parameter } if (uploadOffset != null) { localVarHeaderParams.Add("Upload-Offset", this.Configuration.ApiClient.ParameterToString(uploadOffset)); // header parameter } if (tusResumable != null) { localVarHeaderParams.Add("Tus-Resumable", this.Configuration.ApiClient.ParameterToString(tusResumable)); // header parameter } if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = this.Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (AuthToken) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse)await this.Configuration.ApiClient.CallApiAsync(localVarPath, Method.PATCH, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType, cancellationToken); int localVarStatusCode = (int)localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("TusUploadSessionUploadSessionIdUploadGuidPATCH", localVarResponse); if (exception != null) { throw exception; } } return(new ApiResponse <InlineResponse400>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (InlineResponse400)this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse400)))); }
// // ReadImageStream // public static IntPtr ReadImageStream(System.IO.Stream stream, out int width, out int height, out int len, int forceWidth, int forceHeight, bool zoom) { var bitmap = LoadBitmap(stream); int[] pixels; if (forceWidth == -1 || forceHeight == -1) { pixels = GetPixels(bitmap, out width, out height, out len); } else { pixels = CropAndScale(bitmap, forceWidth, forceHeight, zoom, out width, out height, out len); } // keep a strong reference until FNA3D_Image_Free is called ImagePixels.set(pixels); return(System.Runtime.InteropServices.GCHandle.Alloc( pixels, System.Runtime.InteropServices.GCHandleType.Pinned) .AddrOfPinnedObject()); android.graphics.Bitmap LoadBitmap(System.IO.Stream stream) { if (stream is Microsoft.Xna.Framework.TitleContainer.TitleStream titleStream) { var bitmap = android.graphics.BitmapFactory .decodeStream(titleStream.JavaStream); if (bitmap == null || bitmap.getConfig() != android.graphics.Bitmap.Config.ARGB_8888) { string reason = (bitmap == null) ? "unspecified error" : $"unsupported config '{bitmap.getConfig()}'"; throw new BadImageFormatException( $"Load failed for bitmap image '{titleStream.Name}': {reason}"); } return(bitmap); } throw new ArgumentException(stream?.GetType()?.ToString()); } int[] CropAndScale(android.graphics.Bitmap bitmap, int newWidth, int newHeight, bool zoom, out int width, out int height, out int len) { int oldWidth = bitmap.getWidth(); int oldHeight = bitmap.getHeight(); bool scaleWidth = zoom ? (oldWidth < oldHeight) : (oldWidth > oldHeight); float scaleFactor = scaleWidth ? ((float)newWidth / (float)oldWidth) : ((float)newHeight / (float)oldHeight); if (zoom) { int x, y, w, h; if (scaleWidth) { x = 0; y = (int)(oldHeight / 2 - (newHeight / scaleFactor) / 2); w = oldWidth; h = (int)(newHeight / scaleFactor); } else { x = (int)(oldWidth / 2 - (newWidth / scaleFactor) / 2); y = 0; w = (int)(newWidth / scaleFactor); h = oldHeight; } bitmap = android.graphics.Bitmap.createBitmap(bitmap, x, y, w, h); } else { newWidth = (int)(oldWidth * scaleFactor); newHeight = (int)(oldHeight * scaleFactor); } return(GetPixels(android.graphics.Bitmap.createScaledBitmap( bitmap, newWidth, newHeight, false), out width, out height, out len)); } int[] GetPixels(android.graphics.Bitmap bitmap, out int width, out int height, out int len) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); var pixels = new int[w * h]; bitmap.copyPixelsToBuffer(java.nio.IntBuffer.wrap(pixels)); width = w; height = h; len = w * h * 4; return(pixels); } }