I have the following code where I'm trying to download 3 different files from the users SkyDrive Account.
I'm using the SkyDrive API for Windows Phone development.
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompletedVI);
client.DownloadAsync(fileIdVehicleItems);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompletedHI);
client.DownloadAsync(fileIdHistoryItems);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompletedRI);
client.DownloadAsync(fileIdRepairItems);
When I run this, the only method that gets called is the OnDownloadCompletedVI. All the files that are being downloaded are running through this method which is causing an error.
What am I doing incorrectly?
Update
I have the following method, but I have 2 other similar methods that do the exact same thing except it loads different objects (based off of the downloaded files).
The error I'm currently receiving:
An exception of type 'System.ArgumentException' occurred in
mscorlib.ni.dll but was not handled in user code
void OnDownloadCompletedVI(object sender, LiveDownloadCompletedEventArgs e)
{
if (e.Result != null)
{
using (var stream_vi = e.Result)
{
StreamReader SRVI = new StreamReader(stream_vi);
string contentVI = "";
contentVI = SRVI.ReadToEnd();
StringReader rdr_vi = new StringReader(contentVI);
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<vehicle>));
ObservableCollection<vehicle> importedVehicles = new ObservableCollection<vehicle>();
importedVehicles = (ObservableCollection<vehicle>)serializer.Deserialize(rdr_vi);
StorageHelper.Save<ObservableCollection<vehicle>>(App.vehicleData, importedVehicles);
}
//e.Result.Close();
}
else
{
infoTextBlock.Text = "Error downloading file: " + e.Error.ToString();
}
}
Actually all three methods should be called. Of course, if the first method is called and throws an exception the other two won't trigger.
What you can do is either create a new client for each call, or download them in order, so when the OnDownloadCompletedVI method is complete, remove the event handler for OnDownloadCompletedVI and add the one for OnDownloadCompletedHI and then trigger the client.DownloadAsync(fileIdHistoryItems); at the end of the method.
Related
I wrote a program using CSOM to upload documents to SharePoint and insert metadata to the properties. once a while(like every 3 months) the SharePoint server gets busy or we reset IIS or any other communication problem that it may have, we get "The operation has timed out" error on clientContext.ExecuteQuery(). To resolve the issue I wrote an extension method for ExecuteQuery to try every 10 seconds for 5 times to connect to the server and execute the query. My code works in the Dev and QA environment without any problem but in Prod, when it fails the first time with timeout error, in the second attempt, it only uploads the document but it doesn't update the properties and all the properties are empty in the library. It doesn't return any error as result of ExecteQuery() but It seems from the two requests in the batch witch are uploading the file and updating the properties, it just does uploading and I don't know what happens to the properties. It kinda removes that from the batch in the second attempt!
I used both upload methods docs.RootFolder.Files.Add and File.SaveBinaryDirect in different parts of my code but I copy just one of them here so you can see what I have in my code.
I appreciate your help.
public static void ExecuteSharePointQuery(ClientContext context)
{
int cnt = 0;
bool isExecute = false;
while (cnt < 5)
{
try
{
context.ExecuteQuery();
isExecute = true;
break;
}
catch (Exception ex)
{
cnt++;
Logger.Error(string.Format("Communication attempt with SharePoint failed. Attempt {0}", cnt));
Logger.Error(ex.Message);
Thread.Sleep(10000);
if (cnt == 5 && isExecute == false)
{
Logger.Error(string.Format("Couldn't execute the query in SharePoint."));
Logger.Error(ex.Message);
throw;
}
}
}
}
public static void UploadSPFileWithProperties(string siteURL, string listTitle, FieldMapper item)
{
Logger.Info(string.Format("Uploading to SharePoint: {0}", item.pdfPath));
using (ClientContext clientContext = new ClientContext(siteURL))
{
using (FileStream fs = new FileStream(item.pdfPath, FileMode.Open))
{
try
{
FileCreationInformation fileCreationInformation = new FileCreationInformation();
fileCreationInformation.ContentStream = fs;
fileCreationInformation.Url = Path.GetFileName(item.pdfPath);
fileCreationInformation.Overwrite = true;
List docs = clientContext.Web.Lists.GetByTitle(listTitle);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(fileCreationInformation);
uploadFile.CheckOut();
//Update the metadata
ListItem listItem = uploadFile.ListItemAllFields;
//Set field values on item
foreach (List<string> list in item.fieldMappings)
{
if (list[FieldMapper.SP_VALUE_INDEX] != null)
{
TrySet(ref listItem, list[FieldMapper.SP_FIELD_NAME_INDEX], (FieldType)Enum.Parse(typeof(FieldType), list[FieldMapper.SP_TYPE_INDEX]), list[FieldMapper.SP_VALUE_INDEX]);
}
}
listItem.Update();
uploadFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
SharePointUtilities.ExecuteSharePointQuery(clientContext);
}
catch (Exception ex)
{
}
}
}
}
There's too many possible reasons for me to really comment on a solution, especially considering it's only on the prod environment.
What I can say is that it's probably easiest to keep a reference to the last uploaded file. If your code fails then check if the last file has been uploaded correctly.
Side note: I'm not sure if this is relevant but if it's a large file you want to upload it in slices.
I am writing to a file, that is created for each date of the year, through code below. This code runs whenever, an unhandled exception occurs in an ASP.Net app. My problem is when many users are using the website, then this code could be hit due to several errors occurring at the same time, which could result in multiple requests to create or write to same file. What is the solution in this case so only one request executes the code related to writing to a file?
private void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
string errorGuid = Guid.NewGuid().ToString("D");
if (HttpContext.Current.Server.GetLastError() != null)
{
Exception err = HttpContext.Current.Server.GetLastError();
string header = String.Format("/*****\t\t{0}:{1}\t\t*****/", "Start", errorGuid);
string footer = String.Format("/*****\t\t{0}:{1}\t\t*****/", "End", errorGuid);
string errorText = String.Format("{0}{5}Exception DateTime: {1}{5}Reference #: {2}{5}Exception:{5}=========={5}{3}{5}{4}{5}", header, System.DateTime.Now, errorGuid, err.ToString(), footer, Environment.NewLine);
// '~/ErrorReports/Logs/ErrorLog.log' must exist, else we will get an error
using (System.IO.TextWriter write = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath("~/ErrorReports/Logs/ErrorLog_" + DateTime.Now.ToShortDateString() + ".log"), true, System.Text.Encoding.UTF8))
{
write.WriteLine(errorText);
write.Close();
}
}
}
1 - you can use the singleton pattern and create a class that will handle this file creation/append or
2 - use "lock"
3 - as suggested, use elmah
I'm trying to use the Google Docs GData API (.NET) to upload a file to my docs, but I keep getting errors thrown. I can't find any example that uses this method, so I'm not even sure that I am usign it correctly.
DocumentsService docService = new DocumentsService("MyDocsTest");
docService.setUserCredentials("w****", "*****");
DocumentsListQuery docQuery = new DocumentsListQuery();
DocumentsFeed docFeed = docService.Query(docQuery);
foreach (DocumentEntry entry in docFeed.Entries)
{
Console.WriteLine(entry.Title.Text);
}
Console.ReadKey();
Console.WriteLine();
if (File.Exists(#"testDoc.txt") == false)
{
File.WriteAllText(#"testDoc.txt", "test");
}
docService.UploadDocument(#"testDoc.txt", null); // Works Fine
docService.UploadFile(#"testDoc.txt", null, #"text/plain", false); // Throws Error
The above code will throw a GDataRequestException:
Execution of request failed: https://docs.google.com/feeds/default/private/full?convert=false
This is kind of aggrivating, seeing as this API could be so insanely helpful. Does anyone know what I am doing wrong?
After a lot of experimentation and research, I got it to work. Gonna leave this here for others in my predicament. I will leave in the using shorthands for reference.
// Start the service and set credentials
Docs.DocumentsService service = new Docs.DocumentsService("GoogleApiTest");
service.setUserCredentials("username", "password");
// Initialize the DocumentEntry
Docs.DocumentEntry newEntry = new Docs.DocumentEntry();
newEntry.Title = new Client.AtomTextConstruct(Client.AtomTextConstructElementType.Title, "Test Upload"); // Set the title
newEntry.Summary = new Client.AtomTextConstruct(Client.AtomTextConstructElementType.Summary ,"A summary goes here."); // Set the summary
newEntry.Authors.Add(new Client.AtomPerson(Client.AtomPersonType.Author, "A Person")); // Add a main author
newEntry.Contributors.Add(new Client.AtomPerson(Client.AtomPersonType.Contributor, "Another Person")); // Add a contributor
newEntry.MediaSource = new Client.MediaFileSource("testDoc.txt", "text/plain"); // The actual file to be uploading
// Create an authenticator
Client.ClientLoginAuthenticator authenticator = new Client.ClientLoginAuthenticator("GoogleApiTest", Client.ServiceNames.Documents, service.Credentials);
// Setup the uploader
Client.ResumableUpload.ResumableUploader uploader = new Client.ResumableUpload.ResumableUploader(512);
uploader.AsyncOperationProgress += (object sender, Client.AsyncOperationProgressEventArgs e) =>
{
Console.WriteLine(e.ProgressPercentage + "%"); // Progress updates
};
uploader.AsyncOperationCompleted += (object sender, Client.AsyncOperationCompletedEventArgs e) =>
{
Console.WriteLine("Upload Complete!"); // Progress Completion Notification
};
Uri uploadUri = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full?convert=false"); // "?convert=false" makes the doc be just a file
Client.AtomLink link = new Client.AtomLink(uploadUri.AbsoluteUri);
link.Rel = Client.ResumableUpload.ResumableUploader.CreateMediaRelation;
newEntry.Links.Add(link);
uploader.InsertAsync(authenticator, newEntry, new object()); // Finally upload the bloody thing
Can you check the ResponseString property of the GDataRequestException that is being thrown in order to get a detailed error message?
Capturing your requests with a tool like Fiddler will also help you a lot when trying to debug this kind of issues.
I'm having a little difficulty figuring out what the cause of this error is. I've added FilePicker capabilities in the Manifest, and it's not like I'm trying to do anything crazy; just trying to save to a sub folder within the Documents folder...
Error: "An unhandled exception of type
'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access is denied. (Exception from HRESULT:
0x80070005 (E_ACCESSDENIED))"
I have confirmed that my User Account is Admin and that it has Full Control over folders and files. But I'm not sure what else I can try.
public void NewBTN_Click(object sender, RoutedEventArgs e)
{
var mbox = new MessageDialog("Would you like to save changes before creating a new Note?", "Note+ Confirmation");
UICommand YesBTN = new UICommand("Yes", new UICommandInvokedHandler(OnYesBTN));
UICommand NoBTN = new UICommand("No", new UICommandInvokedHandler(OnNoBTN));
mbox.Commands.Add(YesBTN);
mbox.Commands.Add(NoBTN);
mbox.DefaultCommandIndex = 1;
mbox.ShowAsync().Start();
}
async void OnYesBTN(object command)
{
this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
{
// User clicked yes. Show File picker.
HasPickedFile = true;
}, this, null);
if (HasPickedFile)
{
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Cascading Stylesheet", new List<string>() { ".css" });
savePicker.FileTypeChoices.Add("Hypertext Markup Language", new List<string>() { ".html" });
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default extension if the user does not select a choice explicitly from the dropdown
savePicker.DefaultFileExtension = ".txt";
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Note";
StorageFile savedItem = await savePicker.PickSaveFileAsync();
if (null != savedItem)
{
// Application now has read/write access to the saved file
StorageFolder sFolder = await StorageFolder.GetFolderFromPathAsync(savedItem.Path);
try
{
StorageFile sFile = await sFolder.GetFileAsync(savedItem.FileName);
IRandomAccessStream writeStream = await sFile.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream oStream = writeStream.GetOutputStreamAt(0);
DataWriter dWriter = new DataWriter(oStream);
dWriter.WriteString(Note.Text);
await dWriter.StoreAsync();
oStream.FlushAsync().Start();
// Should've successfully written to the file that Windows FileSavePicker had created.
}
catch
{
var mbox = new MessageDialog("This file does not exist.", "Note+ Confirmation");
UICommand OkBTN = new UICommand("Ok", new UICommandInvokedHandler(OnOkBTN));
mbox.Commands.Add(OkBTN);
mbox.DefaultCommandIndex = 1;
mbox.ShowAsync().Start();
}
}
}
}
public void OnOkBTN(object command)
{
this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
{
// Do something here.
}, this, null);
}
public void OnNoBTN(object command)
{
this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
{
// Don't save changes. Just create a new blank Note.
Note.Text = String.Empty;
}, this, null);
}
How can I write to a file that was created by the FileSavePicker?
You don't need to call StorageFolder.GetFolderFromPathAsync(savedItem.Path) and sFolder.GetFileAsync(savedItem.FileName). You must remove these two lines because they throw exception.
You should use the StorageFile object which has been returned by method savePicker.PickSaveFileAsync(), because that object has all permissions. Then you can simply call savedItem.OpenAsync(FileAccessMode.ReadWrite).
You probably do not have "Document Library Access" enabled in the capabilities portion of the appxmanifest of your app. Without this capability, windows will restrict access to the file system. There are similar capabilities for music, video, and picture libraries.
You have already added "File Picker" to the declarations portion, which is probably not what you want. The "File Picker" declaration indicates that if some other application invokes the file picker, your app will be listed as a possible source of files.
I've also found that adding Video or Picture Libraries access capability in Manifest only takes effect after restarting Windows 10.
Maybe it is an issue with my computer, but I think it is worth to share.
var speechEngine = new SpVoiceClass();
SetVoice(speechEngine, job.Voice);
var fileMode = SpeechStreamFileMode.SSFMCreateForWrite;
var fileStream = new SpFileStream();
try
{
fileStream.Open(filePath, fileMode, false);
speechEngine.AudioOutputStream = fileStream;
speechEngine.Speak(job.Script, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak | SpeechVoiceSpeakFlags.SVSFDefault); //TODO: Change to XML
//Wait for 15 minutes only
speechEngine.WaitUntilDone((uint)new TimeSpan(0, 15, 0).TotalMilliseconds);
}
finally
{
fileStream.Close();
}
This exact code works in a WinForm app, but when I run it inside a webservice I get the following
System.Runtime.InteropServices.COMException was unhandled
Message="Exception from HRESULT: 0x80045003"
Source="Interop.SpeechLib"
ErrorCode=-2147201021
Does anyone have any ideas what might be causing this error? The error code means
SPERR_UNSUPPORTED_FORMAT
For completeness here is the SetVoice method
void SetVoice(SpVoiceClass speechEngine, string voiceName)
{
var voices = speechEngine.GetVoices(null, null);
for (int index = 0; index < voices.Count; index++)
{
var currentToken = (SpObjectToken)voices.Item(index);
if (currentToken.GetDescription(0) == voiceName)
{
speechEngine.SetVoice((ISpObjectToken)currentToken);
return;
}
}
throw new Exception("Voice not found: " + voiceName);
}
I have given full access to USERS on the folder C:\Temp where the file is to be written. Any help would be appreciated!
I don't think the System.Speech works in windows service. It looks like there is a dependency to Shell, which isn't available to services. Try interop with SAPI's C++ interfaces. Some class in System.Runtime.InteropServices may help on that.
Our naming convention requires us to use a non-standard file extension. This works fine in a Winforms app, but failed on our web server. Changing the file extension back to .wav solved this error for us.
Make sure you explicitly set the format on the SPFileStream object. ISpAudio::SetState (which gets called in a lower layer from speechEngine.Speak) will return SPERR_UNSUPPORTED_FORMAT if the format isn't supported.
I just got the webservice to spawn a console app to do the processing. PITA :-)