Azure server not letting me use a NuGet package - azure

I have a website hosted by Azure that includes a Web API which I'm using to develop an android app. I'm trying to upload a media file to the server where it's encoded by a media encoder and saved to a path. The encoder library is called "Media Toolkit" which I found here : https://www.nuget.org/packages/MediaToolkit/1.0.0.3
My server side code looks like this:
[HttpPost]
[Route("upload")]
public async Task<HttpResponseMessage> Upload(uploadFileModel model)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (ModelState.IsValid)
{
string thumbname = "";
string resizedthumbname = Guid.NewGuid() + "_yt.jpg";
string FfmpegPath = Encoding_Settings.FFMPEGPATH;
string tempFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/video"), model.fileName);
string pathToFiles = HttpContext.Current.Server.MapPath("~/video");
string pathToThumbs = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
string finalPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv");
string resizedthumb = Path.Combine(pathToThumbs, resizedthumbname);
var outputPathVid = new MediaFile { Filename = Path.Combine(finalPath, model.fileName) };
var inputPathVid = new MediaFile { Filename = Path.Combine(pathToFiles, model.fileName) };
int maxWidth = 380;
int maxHeight = 360;
var namewithoutext = Path.GetFileNameWithoutExtension(Path.Combine(pathToFiles, model.fileName));
thumbname = model.VideoThumbName;
string oldthumbpath = Path.Combine(pathToThumbs, thumbname);
var fileName = model.fileName;
try
{
File.WriteAllBytes(tempFilePath, model.data);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
using (var engine = new Engine())
{
engine.GetMetadata(inputPathVid);
// Saves the frame located on the 15th second of the video.
var outputPathThumb = new MediaFile { Filename = Path.Combine(pathToThumbs, thumbname + ".jpg") };
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0), CustomHeight = 360, CustomWidth = 380 };
engine.GetThumbnail(inputPathVid, outputPathThumb, options);
}
Image image = Image.FromFile(Path.Combine(pathToThumbs, thumbname + ".jpg"));
//var ratioX = (double)maxWidth / image.Width;
//var ratioY = (double)maxHeight / image.Height;
//var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(maxWidth);
var newHeight = (int)(maxHeight);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
bmp.Save(Path.Combine(pathToThumbs, thumbname + "_resized.jpg"));
//File.Delete(Path.Combine(pathToThumbs, thumbname));
using (var engine = new Engine())
{
var conversionOptions = new ConversionOptions
{
VideoSize = VideoSize.Hd720,
AudioSampleRate = AudioSampleRate.Hz44100,
VideoAspectRatio = VideoAspectRatio.Default
};
engine.GetMetadata(inputPathVid);
engine.Convert(inputPathVid, outputPathVid, conversionOptions);
}
File.Delete(tempFilePath);
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.Duration = inputPathVid.Metadata.Duration.ToString();
vd.Duration_Sec = Convert.ToInt32(inputPathVid.Metadata.Duration.Seconds.ToString());
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = thumbname + "_resized.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
//vd.ContentLength = f_contentlength;
vd.GalleryID = 0;
long videoid = VideoBLL.Process_Info(vd, false);
return result;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
When the debugger hits the line using (var engine = new Engine()) I get 500 internal server error thrown. I don't get this error testing it on the iis server. Since it works fine on my local server and not on the azure hosted server, I figured it had to do with the Azure service rather than an error in my code. If so is the case then how would I be able to get around this issue? I don't want to use azure blob storage as it would require a lot of changes to my code. Does anyone have any idea what might be the issue.
Any helpful suggestions are appreciated.

Server.MapPath works differently on Azure WebApps - change to:
string pathToFiles = HttpContext.Current.Server.MapPath("~//video");
Also, see this SO post for another approach.

Related

Add dimension between link and element

i am tried to find the link wall face,but when i use the reference to create a new dimension , i will get result about 'invaild number of references'. i cant trans link face to active face.
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIDocument uidoc = commandData.Application.ActiveUIDocument;
Document doc = uidoc.Document;
var rf1 = uidoc.Selection.PickObject(ObjectType.PointOnElement, "select");
var element1 = doc.GetElement(rf1);
var location = element1.Location as LocationPoint;
var point = location.Point;
var rf2 = uidoc.Selection.PickObject(ObjectType.LinkedElement, "select");
var linkElement = doc.GetElement(rf2) as RevitLinkInstance;
var linkDoc = linkElement.GetLinkDocument();
var linkWall = linkDoc.GetElement(rf2.LinkedElementId) as Wall;
var wallLocation = linkWall.Location as LocationCurve;
var curve = wallLocation.Curve;
var cRf = curve.Reference;
var solid = BIMTools.Geometry.GetSolid(linkWall);
Face face = null;
foreach (var solidFace in solid.Faces)
{
XYZ normal = ((Face)solidFace).ComputeNormal(new UV(0, 0));
if (normal.Y < 0)
{
face = solidFace as Face;
break;
}
}
var viewLevel = uidoc.ActiveView.GenLevel.Elevation;
var tPoint = new XYZ(point.X,(face as PlanarFace).Origin.Y, viewLevel);
point = new XYZ(point.X, point.Y, viewLevel);
var line = Line.CreateBound(point, tPoint);
var references = new ReferenceArray();
references.Append(rf1);
references.Append(face.Reference);
using (Transaction trans = new Transaction(doc,"create"))
{
trans.Start();
var dimension = doc.Create.NewDimension(uidoc.ActiveView, line, references);
trans.Commit();
}
return Result.Succeeded;
}
The Building Coder provides a whole list of articles on creating dimensioning.

I have free DocuSign Signature Appliance Developer Sandbox account.but can not perform signature operation using DssSign

I have a free DocuSign Signature Appliance Developer Sandbox account.I want to use "https://prime.cosigntrial.com:8080/SAPIWS/dss.asmx" and wan to use DssSign service method to create and attach signature to pdf.But it reutrn "urn:oasis:names:tc:dss:1.0:resultmajor:ResponderError".Please help how can I get username and password to create a new signature programmatically and assign to a pdf using DocuSign API
I already download the code samples found Git "docusign-signature-appliance-api-recipes-master" but can not sucess.
//Sign PDF file
public bool SignPDFFile(
string FileToSign,
string UserName,
string Password,
int X,
int Y,
int Width,
int Height,
int Page,
bool isVisible)
{
//Create Request object contains signature parameters
RequestBaseType Req = new RequestBaseType();
Req.OptionalInputs = new RequestBaseTypeOptionalInputs();
//Here Operation Type is set: Verify/Create Signature Field/Sign/etc
Req.OptionalInputs.SignatureType = SignatureTypeFieldCreateSign;
//Configure Create and Sign operation parameters:
Req.OptionalInputs.ClaimedIdentity = new ClaimedIdentity();
Req.OptionalInputs.ClaimedIdentity.Name = new NameIdentifierType();
Req.OptionalInputs.ClaimedIdentity.Name.Value = UserName; //User Name
Req.OptionalInputs.ClaimedIdentity.Name.NameQualifier = " "; //Domain (relevant for Active Directory environment only)
Req.OptionalInputs.ClaimedIdentity.SupportingInfo = new CoSignAuthDataType();
Req.OptionalInputs.ClaimedIdentity.SupportingInfo.LogonPassword = Password; //User Password
Req.OptionalInputs.SAPISigFieldSettings = new SAPISigFieldSettingsType();
Req.OptionalInputs.SAPISigFieldSettings.X = X; //Signature Field X coordinate
Req.OptionalInputs.SAPISigFieldSettings.XSpecified = true;
Req.OptionalInputs.SAPISigFieldSettings.Y = Y; //Signature Field Y coordinate
Req.OptionalInputs.SAPISigFieldSettings.YSpecified = true;
Req.OptionalInputs.SAPISigFieldSettings.Page = Page; //Page number the signature field will appear on
Req.OptionalInputs.SAPISigFieldSettings.PageSpecified = true;
Req.OptionalInputs.SAPISigFieldSettings.Width = Width; //Signature Field width
Req.OptionalInputs.SAPISigFieldSettings.WidthSpecified = true;
Req.OptionalInputs.SAPISigFieldSettings.Height = Height; //Signature Field Height
Req.OptionalInputs.SAPISigFieldSettings.HeightSpecified = true;
Req.OptionalInputs.SAPISigFieldSettings.Invisible = !isVisible; //Specifies whether the signature will be visible or not
Req.OptionalInputs.SAPISigFieldSettings.InvisibleSpecified = true;
// Set configuration parameters /////////////////////////////////////////////////////////
int numConfigurationParams = 6;
Req.OptionalInputs.ConfigurationValues = new ConfValueType[numConfigurationParams];
for (int i = 0; i < numConfigurationParams; i++)
{
Req.OptionalInputs.ConfigurationValues[i] = new ConfValueType();
}
// Add reason
Req.OptionalInputs.ConfigurationValues[0].ConfValueID = ConfIDEnum.Reason;
Req.OptionalInputs.ConfigurationValues[0].Item = "I am the author of this document";
// Add TSA:
/*
Req.OptionalInputs.ConfigurationValues[1].ConfValueID = ConfIDEnum.UseTimestamp;
Req.OptionalInputs.ConfigurationValues[1].Item = 1;
Req.OptionalInputs.ConfigurationValues[2].ConfValueID = ConfIDEnum.TimestampURL;
Req.OptionalInputs.ConfigurationValues[2].Item = "http://www.ca-soft.com/request.aspx";
Req.OptionalInputs.ConfigurationValues[3].ConfValueID = ConfIDEnum.TimestampAdditionalBytes;
Req.OptionalInputs.ConfigurationValues[3].Item = 4000;
Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.TimestampUser;
Req.OptionalInputs.ConfigurationValues[4].Item = "";
Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.TimestampPWD;
Req.OptionalInputs.ConfigurationValues[5].Item = "";
// OCSP (NOTE: Server must contain comodo CA in order to use the following OCSP URL)
Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.UseOCSP;
Req.OptionalInputs.ConfigurationValues[4].Item = 1;
Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.OCSPURL;
Req.OptionalInputs.ConfigurationValues[5].Item = "ocsp.comodoca.com";
*/
// End setting configuration parameters ////////////////////////////////////////////////
//Set Session ID
Req.RequestID = Guid.NewGuid().ToString();
//Prepare the Data to be signed
DocumentType doc1 = new DocumentType();
DocumentTypeBase64Data b64data = new DocumentTypeBase64Data();
Req.InputDocuments = new RequestBaseTypeInputDocuments();
Req.InputDocuments.Items = new object[1];
b64data.MimeType = "application/pdf"; //Can also be: application/msword, image/tiff, pplication/octet-string (ocsp/tsa are supported in PDF only)
Req.OptionalInputs.ReturnPDFTailOnlySpecified = true;
Req.OptionalInputs.ReturnPDFTailOnly = true;
b64data.Value = ReadFile(FileToSign, true); //Read the file to the Bytes Array
doc1.Item = b64data;
Req.InputDocuments.Items[0] = doc1;
//Call sign service
ResponseBaseType Resp = null;
try
{
// Create the Web Service client object
DSS service = new DSS();
service.Url = "https://prime.cosigntrial.com:8080/SAPIWS/dss.asmx"; //This url is constant and shouldn't be changed
// service.Url = "https://prime-dsa-devctr.docusign.net:8080/sapiws/dss.asmx"; //This url is constant and shouldn't be changed
SignRequest sreq = new SignRequest();
sreq.InputDocuments = Req.InputDocuments;
sreq.OptionalInputs = Req.OptionalInputs;
//Perform Signature operation
Resp = service.DssSign(sreq);
if (Resp.Result.ResultMajor != Success )
{
MessageBox.Show("Error: " + Resp.Result.ResultMajor + " " +
Resp.Result.ResultMinor + " " +
Resp.Result.ResultMessage.Value, "Error");
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
if (ex is WebException)
{
WebException we = ex as WebException;
WebResponse webResponse = we.Response;
if (webResponse != null)
MessageBox.Show(we.Response.ToString(), "Web Response");
}
return false;
}
//Handle Reply
DssSignResult sResp = (DssSignResult) Resp;
//object sig = sResp.SignatureObject.Item;
//SignatureObjectTypeBase64Signature sig = (SignatureObjectTypeBase64Signature) sResp.SignatureObject.Item;
DssSignResultSignatureObjectBase64Signature sig = (DssSignResultSignatureObjectBase64Signature)sResp.SignatureObject.Item;
byte[] signature = sig.Value;
return PDFAttachSignature(FileToSign, signature, true); //Attach Signature to the PDF file
}
display error urn:oasis:names:tc:dss:1.0:resultmajor:ResponderError

PDF Digital Signing Disable CRL

I am writing a sample pdf signer using itextsharp.dll n the digital signature is on a usb device.
it's working nicely only problem is that some times the signing gets completely stops for hours together.
I have found that the signing process goes to digital issuer site to get CRL to embed in the signed document increasing it's size from 100kb to 1300kb+ and also signs document very slow due to getting CRL from issuer site.
but if I disable internet the file gets signed very fast and size increase is just 5-10kb.
So my question precisely is how can I instruct the signing process not to go online to get CRL n simply sign the document fast with less size increase in original document.
public void Sign(ICollection<X509Certificate> chain, X509Certificate2 pk,
String digestAlgorithm, CryptoStandard subfilter,
String reason, String location,
int estimatedSize)
{
IList<ICrlClient> crlList = new List<ICrlClient>();
crlList.Add(new CrlClientOnline(chain));
// Creating the reader and the stamper
PdfReader reader = null;
PdfStamper stamper = null;
FileStream os = null;
//int noofpdfs = 0;
var watch = Stopwatch.StartNew();
try
{
string[] srcfiles;
if (lblSplitedFilePath.Text.Equals("Split By Page Directory"))
srcfiles = Directory.GetFiles(tbsrcpath.Text, "*.pdf");
else
if (tbsrcpath.Text.ToUpper().Contains(#"\SPLIT"))
srcfiles = Directory.GetFiles(tbsrcpath.Text, "*.pdf");
else
srcfiles = Directory.GetFiles(tbsrcpath.Text + #"\split\", "*.pdf");
//int noofpdfs = srcfilePaths.Count();
for (int i = 0; i < srcfiles.Count(); i++)
{
// Get FileName
lblOutputFile.Text = tbtgtpath.Text + #"\" + Path.GetFileName(srcfiles[i]);
lblOutputFile.Refresh();
os = new FileStream(lblOutputFile.Text, FileMode.Create);
reader = new PdfReader(srcfiles[i]);
iTextSharp.text.Rectangle pdfbox = reader.GetPageSize(1);
stamper = PdfStamper.CreateSignature(reader, os, '\0');
// Creating the appearance
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
if (!string.IsNullOrWhiteSpace(tbContact.Text))
{
appearance.ReasonCaption = "Contact:";
appearance.Reason = tbContact.Text;// reason;
}
appearance.Location = location;
//Adding Image to Sign
if (cbAddImageSign.Checked)
{
var image = iTextSharp.text.Image.GetInstance(tbSignImage.Text);
appearance.Acro6Layers = true;
appearance.SignatureGraphic = image;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
}
int llx, lly, urx, ury;
int.TryParse(Tbllx.Text, out llx);
int.TryParse(tblly.Text, out lly);
int.TryParse(tburx.Text, out urx);
int.TryParse(tbury.Text, out ury);
pdfSigning.Properties.Settings.Default.llx = llx;
pdfSigning.Properties.Settings.Default.lly = lly;
pdfSigning.Properties.Settings.Default.urx = urx;
pdfSigning.Properties.Settings.Default.ury = ury;
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(llx, lly, urx, ury), 1, "sig");
//Add Water mark
if (!lblWaterMarkImagePath.Text.Equals("Pdf Water Mark Image Path"))
{
var wmimage = iTextSharp.text.Image.GetInstance(lblWaterMarkImagePath.Text);
wmimage.SetAbsolutePosition(0, 0);
wmimage.ScaleToFit(100, 100);
for (var j = 0; j < reader.NumberOfPages; j++)
{
var content = stamper.GetUnderContent(j + 1);
content.AddImage(wmimage);
}
}
//appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
// Creating the signature
try
{
IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
MakeSignature.SignDetached(appearance, pks, chain, crlList, null, null, estimatedSize,
subfilter);
}
catch (CryptographicException ex)
{
MessageBox.Show(ex.ToString());
}
//noofpdfs++;
if (cbPrintOnSign.Checked)
{
switch (tbPrintMethod.Text)
{
case "2":
SendFileToPrinter(lblOutputFile.Text, printpdf2printer);
break;
default:
SendToPrinter(lblOutputFile.Text);
break;
}
}
if (cbDeletePdfPostSign.Checked)
{
File.Delete(srcfiles[i]);
}
dgvPrintFiles.Rows.Add(srcfiles[i].ToString());
}
lblOutputFile.Text += #" Siging Over:Signed " + srcfiles.Count().ToString() + " Files";
}
finally
{
if (reader != null)
reader.Close();
if (stamper != null)
stamper.Close();
if (os != null)
os.Close();
}
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
MessageBox.Show("Signing Time:" + elapsedMs / 1000 + " Second");
}

Is there any google API which could save gmail message attachments to google drive?

How can I save gmail message attachments to google drive. Is there any such google API?
To add details, here is the main page of what Google APIs you can use. As Gaurav mentioned, you can use Drive and Gmail API. Here is a snippet using Apps Script:
// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['jpg', 'tif', 'png', 'gif', 'bmp', 'svg'];
//Name of the folder in google drive i which files will be put
var folderName = 'GmailToDrive';
//Name of the label which will be applied after processing the mail message
var labelName = 'GmailToDrive';
function GmailToDrive(){
//build query to search emails
var query = '';
//filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+formattedDate+
for(var i in fileTypesToExtract){
query += (query == '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
}
query = 'in:inbox has:nouserlabels ' + query;
var threads = GmailApp.search(query);
var label = getGmailLabel_(labelName);
var parentFolder;
if(threads.length > 0){
parentFolder = getFolder_(folderName);
}
for(var i in threads){
var mesgs = threads[i].getMessages();
for(var j in mesgs){
//get attachments
var attachments = mesgs[j].getAttachments();
for(var k in attachments){
var attachment = attachments[k];
var isImageType = checkIfImage_(attachment);
if(!isImageType) continue;
var attachmentBlob = attachment.copyBlob();
var file = DocsList.createFile(attachmentBlob);
file.addToFolder(parentFolder);
}
}
threads[i].addLabel(label);
}
}
//This function will get the parent folder in Google drive
function getFolder_(folderName){
var folder;
try {folder = DocsList.getFolder(folderName)}
catch(e){ folder = DocsList.createFolder(folderName);}
return folder;
}
//getDate n days back
// n must be integer
function getDateNDaysBack_(n){
n = parseInt(n);
var today = new Date();
var dateNDaysBack = new Date(today.valueOf() - n*24*60*60*1000);
return dateNDaysBack;
}
function getGmailLabel_(name){
var label = GmailApp.getUserLabelByName(name);
if(label == null){
label = GmailApp.createLabel(name);
}
return label;
}
//this function will check for filextension type.
// and return boolean
function checkIfImage_(attachment){
var fileName = attachment.getName();
var temp = fileName.split('.');
var fileExtension = temp[temp.length-1].toLowerCase();
if(fileTypesToExtract.indexOf(fileExtension) != -1) return true;
else return false;
}
Hope this helps.

How to show a progress bar while uploading data to azure blob in Windows store app

I have followed the following post to do the upload in chunks to blob
How to track progress of async file upload to azure storage
But this is not working in windows store app or windows 8.1 app as there is no support for MemoryStream in win 8.1 app.
Anyhow I have modified the code in the above thread and come up with something like the following
CloudBlobClient myBlobClient = storageAccount.CreateCloudBlobClient();
var filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add("*");
var file = await filePicker.PickSingleFileAsync();
string output = string.Empty;
var fileName = file.Name;
myBlobClient.SingleBlobUploadThresholdInBytes = 1024 * 1024;
CloudBlobContainer container = myBlobClient.GetContainerReference("files");
//container.CreateIfNotExists();
CloudBlockBlob myBlob = container.GetBlockBlobReference(fileName);
var blockSize = 256 * 1024;
myBlob.StreamWriteSizeInBytes = blockSize;
var fileProp = await file.GetBasicPropertiesAsync();
var bytesToUpload = fileProp.Size;
var fileSize = bytesToUpload;
if (bytesToUpload < Convert.ToUInt64(blockSize))
{
CancellationToken ca = new CancellationToken();
var ado = myBlob.UploadFromFileAsync(file).AsTask();
await
//Console.WriteLine(ado.Status); //Does Not Help Much
ado.ContinueWith(t =>
{
//Console.WriteLine("Status = " + t.Status);
//Console.WriteLine("It is over"); //this is working OK
});
}
else
{
List<string> blockIds = new List<string>();
int index = 1;
ulong startPosition = 0;
ulong bytesUploaded = 0;
do
{
var bytesToRead = Math.Min(Convert.ToUInt64(blockSize), bytesToUpload);
var blobContents = new byte[bytesToRead];
using (Stream fs = await file.OpenStreamForWriteAsync())
{
fs.Position = Convert.ToInt64(startPosition);
fs.Read(blobContents, 0, (int)bytesToRead);
//var iStream = fs.AsInputStream();
ManualResetEvent mre = new ManualResetEvent(false);
var blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(index.ToString("d6")));
//Console.WriteLine("Now uploading block # " + index.ToString("d6"));
blockIds.Add(blockId);
var ado = myBlob.PutBlockAsync(blockId, fs.AsRandomAccessStream(), null).AsTask();
await ado.ContinueWith(t =>
{
bytesUploaded += bytesToRead;
bytesToUpload -= bytesToRead;
startPosition += bytesToRead;
index++;
double percentComplete = (double)bytesUploaded / (double)fileSize;
output += (percentComplete * 100).ToString() + ",";
// AppModel.TasksFormObj.SetProgress(percentComplete * 100);
// Console.WriteLine("Percent complete = " + percentComplete.ToString("P"));
mre.Set();
});
mre.WaitOne();
}
}
while (bytesToUpload > 0);
//Console.WriteLine("Now committing block list");
var pbl = myBlob.PutBlockListAsync(blockIds).AsTask();
pbl.ContinueWith(t =>
{
//Console.WriteLine("Blob uploaded completely.");
});
}
}
The above code will save the file in blob and the progress is also fine but the saved file in blob is always in 0 bytes . After debugging I found there was an error thrown after var ado = myBlob.PutBlockAsync(blockId, fs.AsRandomAccessStream(), null).AsTask(); for the last blob transfer as
<?xml version="1.0" encoding="utf-16"?>
<!--An exception has occurred. For more information please deserialize this message via RequestResult.TranslateFromExceptionMessage.-->
<RequestResult>
<HTTPStatusCode>400</HTTPStatusCode>
<HttpStatusMessage>The value for one of the HTTP headers is not in the correct format.</HttpStatusMessage>
<TargetLocation>Primary</TargetLocation>
<ServiceRequestID>13633308-0001-0031-060b-7249ea000000</ServiceRequestID>
<ContentMd5 />
<Etag />
<RequestDate>Sun, 28 Feb 2016 10:31:44 GMT</RequestDate>
<StartTime>Sun, 28 Feb 2016 09:31:43 GMT</StartTime>
<EndTime>Sun, 28 Feb 2016 09:31:44 GMT</EndTime>
<Error>
<Code>InvalidHeaderValue</Code>
<Message>The value for one of the HTTP headers is not in the correct format.
RequestId:13633308-0001-0031-060b-7249ea000000
Time:2016-02-28T09:34:18.3545085Z</Message>
<HeaderName>Content-Length</HeaderName>
<HeaderValue>0</HeaderValue>
</Error>
<ExceptionInfo>
<Type>StorageException</Type>
<HResult>-2147467259</HResult>
<Message>The value for one of the HTTP headers is not in the correct format.</Message>
<Source>Microsoft.WindowsAzure.Storage</Source>
<StackTrace> at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.<ExecuteAsyncInternal>d__c`1.MoveNext()</StackTrace>
</ExceptionInfo>
</RequestResult>
Then on the last commit the error thrown after myBlob.PutBlockListAsync(blockIds) as The specified block list is invalid
So please someone help me to to figure out where I am doing wrong or what is the possible solution to make it work 100%.
Use AsTask() like this.
CancellationTokenSource _cts;
_cts = new CancellationTokenSource();//<--In Constructor
var progress = new Progress<double>(TranscodeProgress);
await var ado = myBlob.UploadFromFileAsync(file).AsTask(_cts.Token, progress);

Resources