Connecting Windows 8 App with Skydrive and Uploading File issue in c# - c#

async private void uploadtosky_Click(object sender, RoutedEventArgs e)
{
try
{
LiveAuthClient auth = new LiveAuthClient();
LiveLoginResult log = await auth.LoginAsync(new List<string> { "wl-basic", "wl.skydrive", "wl.signin" });
if (log.Status == LiveConnectSessionStatus.Connected)
{
LiveConnectClient uploadcl = new LiveConnectClient(auth.Session);
LiveOperationResult up = await uploadcl.BackgroundUploadAsync("me/skydrive", heading.Text, samplefile, OverwriteOption.Overwrite);
}
}
catch
{
MessageDialog msg = new MessageDialog("Oops ! something went wrong while trying to connect");
msg.ShowAsync();
}
}
When I execute the snippet the messagebox showing Oops ! something went wrong while trying to connect. My computer is connected to the internet and on clicking the button for uploading, I get a sign in page to live account in the Windows 8 app. However I guess it can't login to the account and so the exception occurs. Any idea to overcome this problem?

How big is your file? Is it larger than 300MB? I remember that large files have some problems with uploading.

found the answer finally . Actually there is a need to replace auth.Session as log.Session ( in the line LiveConnectClient uploadcl = new LiveConnectClient(auth.Session); ) and add a scope called wl.skydrive_update in LiveLoginResult log = await auth.LoginAsync(new List<string> { "wl-basic", "wl.skydrive", "wl.signin" });
Thats it !

Related

I am making a quiz game for my alevel software systems developement and my code is fine but I cant run my code

There is nothing wrong in the syntax of my code but whenever I try to run it keeps saying "The process cannot access the file because it is being used by another process". The only way I am running my application is my ending my application from the task manager. Please help me by explaining why this is happening and how to fix it.
private void btnLogin_Click(object sender, EventArgs e)
{
if (File.Exists("users.txt"))
{
string[] users = File.ReadAllLines("users.txt");
bool userFound = false;
foreach (string user in users)
{
string[] splitDetails = user.Split('~');
string username = splitDetails[1];
string password = splitDetails[2];
if ((txtBoxUsername.Text == username) && (txtBoxPassword.Text == password))
{
userFound = true;
break;
}
}
if (userFound)
{
Hide();
HomeForm home = new HomeForm();
home.Show();
}
else
{
MessageBox.Show("User details are incorrect",
"Incorrect details entered");
}
}
else
{
MessageBox.Show("No users have been registered", "No users");
}
}
private void btnRegister_Click(object sender, EventArgs e)
{
Hide();
RegisterForm registerForm = new RegisterForm();
registerForm.Show();
}
This application is for my a level software systems development coursework and I am coding it in c#. I have only been learning c# for the past 5 months so I am still a beginner. I have already tried to find the answer to my problem in stack overflow and other websites.
I am expecting my application to launch when I press run, but instead I get a dialog box saying:
Error Unable to copy file "obj\Debug\SSD AS2 coursework.exe" to "bin\Debug\SSD AS2 coursework.exe". The process cannot access the file 'bin\Debug\SSD AS2 coursework.exe' because it is being used by another process.
SSD AS2 coursework
Check if you are closing all windows of your application when finalizing the app.
You must use Application.Exit() in any events that are going to finalize your application.
You can read more on the Documentation
It seems like the file you are trying to open is being used by another process try to close your text editor or another program writing to that file.
it is still possible to overcome the issue by using FileShare.ReadWrite and use the file from multiple processes, example on the following code:
FileStream fileStream = new FileStream("c:\users.txt", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
StreamReader fileReader = new StreamReader(fileStream);
while (!fileReader.EndOfStream)
{
string user = fileReader.ReadLine();
string[] splitDetails = user.Split('~');
// the rest of the user logic in here...
}
fileReader.Close();
fileStream.Close();

Windows Phone 8 file are not persisted across app restart

I'm writing my first Windows Phone 8 app, and I'm just trying something simple. Read / Write file. Here's my two methods:
public static async Task<Week> Load()
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
try
{
StorageFile mealsFile = await folder.GetFileAsync("file.txt");
if (mealsFile != null)
{
using (var stream = await mealsFile.OpenAsync(FileAccessMode.Read))
{
var serializer = new DataContractSerializer(typeof(List<MyTypeHere>));
var w = (List<MyTypeHere>)serializer.ReadObject(stream.AsStreamForRead());
if (w != null)
MyWeek.WeekList = new ObservableCollection<MyTypeHere>(w);
}
}
}
catch(FileNotFoundException fEx)
{
MyWeek = new Week();
}
return MyWeek;
}
public static async Task<bool> Save()
{
try
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile mealsFile = await folder.CreateFileAsync("file.txt", CreationCollisionOption.ReplaceExisting);
using (var stream = await mealsFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var sw = stream.GetOutputStreamAt(0))
{
var serializer = new DataContractSerializer(typeof(List<MyTypeHere>));
serializer.WriteObject(sw.AsStreamForWrite(), MyWeek.WeekList.ToList());
await sw.FlushAsync();
}
}
MyWeek = null;
return true;
}
catch(Exception ex)
{
return false;
}
}
I'm calling the Save (with breakpoint it works fiine), then call Load (with breakpoint) which load the file, the file exists and it populate my object graph.
When I close the app and restart it, the catch of the FileNotFoundException is caught. Why?
From what I can see the Local Folder is supposed to be persisting the file. What I'm missing that obviously should be obvious...
Thanks
Edit:
I'm using the Windows Phone emulator, and when I close it and hit F5 on Visual Studio, the file is not there anymore.
Apparently by closing the emulator, the files in Local Storage are lost, thanks to #cdndevs via Twitter. I was closing the emulator each time I was stopping debugging instead of letting the emulator simply "stay" there between restart.
By stopping debugging and restarting the app without closing the emulator, the files are there. Well, not super intuitive I must admit, or it might just be me. Hope that help other people like me ;).

Windows Phone 8.1 app to share image - works fine on my phone with Visual Studio debugger attached, but crashes when run without the debugger

I'm trying to share an image through my app, everything works just fine when I run the app on my phone through visual studio, but when I try to run it from my phone, it crashes everytime I click the share button
private async void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
args.Request.Data.Properties.Title = "Let's Celebrate";
args.Request.Data.Properties.Description = "It's time to celebrate!";
DataRequestDeferral deferral = args.Request.GetDeferral();
try
{
var finalImg = await GenerateImage();
var folder = Package.Current.InstalledLocation;
const CreationCollisionOption option = CreationCollisionOption.ReplaceExisting;
var file = await folder.CreateFileAsync("letscelebrateshare.png", option);
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var pixelBuffer = await finalImg.GetPixelsAsync();
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)finalImg.PixelWidth,
(uint)finalImg.PixelHeight,
logicalDpi,
logicalDpi,
pixelBuffer.ToArray());
await encoder.FlushAsync();
StorageFile logoFile =
await Package.Current.InstalledLocation.GetFileAsync("letscelebrateshare.png");
List<IStorageItem> storageItems = new List<IStorageItem>();
storageItems.Add(logoFile);
args.Request.Data.SetStorageItems(storageItems);
}
}
finally
{
deferral.Complete();
}
}
private async void bla... [..]
{
Exception exc= null;
try
{
//All your stuff
}
catch(Exception ex)
{
exc = ex;
}
if(exc!=null)
await msg.ShowAsync();
}
Edit: Since I don't use WP in C#. I guess you could try this. Hope this helps ^^
I had the same issue while opening a file open picker. I found a weird solution. When I removed the navigation parameters in every pages and used static variables instead, worked fine for me. I guess this will help you
If the App is there crashing without debugger, try while debugging and the share targets are visible to "suspend and shutdown" ("Lifecycle Events" in visual studio). In most cases you app will then crash because it is suspended and serialize the data.

Windows 8 GetFileAsync method gives UnAuthorized error

The below code an attempt to try and get get an Mp3 file from the MusicLibrary
It gives me,
A first chance exception of type
'System.UnauthorizedAccessException'
occurred in AccessingPictures.exe
This is my code:
public async void getFile()
{
StorageFolder folder = KnownFolders.MusicLibrary;
try
{
sampleFile = await folder.GetFileAsync("Test1.mp3");
}
catch (FileNotFoundException e)
{
// If file doesn't exist, indicate users to use scenario 1
Debug.WriteLine(e);
}
}
private void btnRead_Click(object sender, RoutedEventArgs e)
{
getFile();
}
Wouldn't we able to access the media files?
I am able to do this using the file picker.
But it does not work while i try to access it directly.
Am i missing anything here ?
To retrieve Pictures from Camera Roll
Void GetCameraPhotos()
{
using (var library = new MediaLibrary())
{
PictureAlbumCollection allAlbums = library.RootPictureAlbum.Albums;
PictureAlbum cameraRoll = allAlbums.Where(album => album.Name == "Camera Roll").FirstOrDefault();
var CameraRollPictures = cameraRoll.Pictures
}
}
You cannot access the files unless it is in response to a user request. i.e. the user must tap a button or something and that tap logic ends up calling your code that accesses the file. If you want to get at the file afterwards, you'll need to copy it in the app's data folder.
I finally figured the issue. It was because i hadn't enabled the capabilities in the Manifest file.
It works like a charm now.
Thanks everyone.

LockScreen.SetImageFileAsync(...) causes UnauthorizedAccessException

I'm trying to set background image on lock screen in my WinRT app. But when this code is being executed i get an UnauthorizedAccessException with message:
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
The code was taken from MSDN and looks like OK.
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var imagePicker = new FileOpenPicker
{
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" },
};
var imageFile = await imagePicker.PickSingleFileAsync();
if (imageFile != null)
{
await LockScreen.SetImageFileAsync(imageFile);
}
}
The exception described below is thrown in this line of code:
await LockScreen.SetImageFileAsync(imageFile);
By the way, i've tried to install some applications which can change your background on lock screen, but all of them show error or just crash. Maybe something is wrong with my OS version?
Does anyone know how to solve this problem? Please help!
You need access to the Pictures Library.
Set it by opening your Package.appxmanifest, goto Capabilities and check Pictures Library.
I faced with exactly the same problem. The problem was that my OS wasn't activated. Check this thing on your computer's properties. Hope it helps.
I guess Its some kind of privilege problem may be admin .
Try a work around by applying this code
private async void Button_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient();
var bytes = await client.GetByteArrayAsync(new Uri("http://transfer-talk.com/wp-content/uploads/Kaka-Real-Madrid.jpg"));
StorageFile sf = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("test.jpg", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(sf, bytes);
//var imageFile = await imagePicker.PickSingleFileAsync();
//if (imageFile != null)
{
await LockScreen.SetImageFileAsync(sf);
}
}
it will download an Image and set . Not giving an exception in my case neither your code nor mine.
download this sample and try running and see if error exist lock screen sample
also try setting the stream rather using storage file.
await LockScreen.SetImageStreamAsync(await sf.OpenReadAsync());
try and let me know :)

Categories

Resources