public async Task UploadFile(string name,IStorageFile storageFile) { var s3Client = new AmazonS3Client(credentials, RegionEndpoint.USEast1); var transferUtilityConfig = new TransferUtilityConfig { ConcurrentServiceRequests = 5, MinSizeBeforePartUpload = 20 * MB_SIZE, }; try { using (var transferUtility = new TransferUtility(s3Client, transferUtilityConfig)) { var uploadRequest = new TransferUtilityUploadRequest { BucketName = ExistingBucketName, Key = name, StorageFile = storageFile, // Set size of each part for multipart upload to 10 MB PartSize = 10 * MB_SIZE }; uploadRequest.UploadProgressEvent += OnUploadProgressEvent; await transferUtility.UploadAsync(uploadRequest); } } catch (AmazonServiceException ex) { // oResponse.OK = false; // oResponse.Message = "Network Error when connecting to AWS: " + ex.Message; } }
public static async Task<string> Hash(IStorageFile file) { string res = string.Empty; using(var streamReader = await file.OpenAsync(FileAccessMode.Read)) { var alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); var algHash = alg.CreateHash(); using(BinaryReader reader = new BinaryReader(streamReader.AsStream(), Encoding.UTF8)) { byte[] chunk; chunk = reader.ReadBytes(CHUNK_SIZE); while(chunk.Length > 0) { algHash.Append(CryptographicBuffer.CreateFromByteArray(chunk)); chunk = reader.ReadBytes(CHUNK_SIZE); } } res = CryptographicBuffer.EncodeToHexString(algHash.GetValueAndReset()); return res; } }
async Task LoadDrawing(ICanvasResourceCreator resourceCreator) { var svgDocument = await XmlDocument.LoadFromFileAsync(wantedSvgFile, new XmlLoadSettings() { ProhibitDtd = false }); svgDrawing = await SvgDrawing.LoadAsync(resourceCreator, svgDocument); loadedSvgFile = wantedSvgFile; canvas.Invalidate(); }
private static async Task<Uri> GenerateThumbnail(IStorageFile file) { using (var fileStream = await file.OpenReadAsync()) { // decode the file using the built-in image decoder var decoder = await BitmapDecoder.CreateAsync(fileStream); // create the output file for the thumbnail var thumbFile = await ApplicationData.Current.LocalFolder.CreateFileAsync( string.Format("thumbnail{0}", file.FileType), CreationCollisionOption.GenerateUniqueName); // create a stream for the output file using (var outputStream = await thumbFile.OpenAsync(FileAccessMode.ReadWrite)) { // create an encoder from the existing decoder and set the scaled height // and width var encoder = await BitmapEncoder.CreateForTranscodingAsync( outputStream, decoder); encoder.BitmapTransform.ScaledHeight = 100; encoder.BitmapTransform.ScaledWidth = 100; await encoder.FlushAsync(); } // create the URL var storageUrl = string.Format(URI_LOCAL, thumbFile.Name); // return it return new Uri(storageUrl, UriKind.Absolute); } }
async public void NewExcuseAsync() { CurrentExcuse = new Excuse(); excuseFile = null; OnPropertyChanged("CurrentExcuse"); await UpdateFileDateAsync(); }
public GameRouletteModelLogic(IStorageFolder folder, IStorage storage, IStorageFile file, IImage image) { _folder = folder; _storage = storage; _file = file; _image = image; }
public YandexGetFileProgressEventArgs(IStorageFile file, byte[] buffer, int bytesRead, long totalBytesDowloaded) { File = file; Buffer = buffer; BytesRead = bytesRead; TotalBytesDowloaded = totalBytesDowloaded; }
public async static Task<PwDatabase> LoadDatabase(IStorageFile database, string password, string keyPath) { var userKeys = new List<IUserKey>(); var hasher = new SHA256HasherRT(); if (!string.IsNullOrEmpty(password)) { userKeys.Add(await KcpPassword.Create(password, hasher)); } if (!string.IsNullOrEmpty(keyPath)) { var keyfile = await Helpers.Helpers.GetKeyFile(keyPath); userKeys.Add(await KcpKeyFile.Create(new WinRTFile(keyfile), hasher)); } var readerFactory = new KdbReaderFactory( new WinRTCrypto(), new MultiThreadedBouncyCastleCrypto(), new SHA256HasherRT(), new GZipFactoryRT()); var file = await FileIO.ReadBufferAsync(database); MemoryStream kdbDataReader = new MemoryStream(file.AsBytes()); return await readerFactory.LoadAsync(kdbDataReader, userKeys); }
protected override async Task WriteTextToFileCore(IStorageFile file, string contents) { using (var sw = new StreamWriter(file.Path, true)) { await sw.WriteLineAsync(contents); } }
public static async Task SaveToFile( this WriteableBitmap writeableBitmap, IStorageFile outputFile, Guid encoderId) { try { Stream stream = writeableBitmap.PixelBuffer.AsStream(); byte[] pixels = new byte[(uint)stream.Length]; await stream.ReadAsync(pixels, 0, pixels.Length); using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96, 96, pixels); await encoder.FlushAsync(); using (var outputStream = writeStream.GetOutputStreamAt(0)) { await outputStream.FlushAsync(); } } } catch (Exception ex) { string s = ex.ToString(); } }
internal async static Task WriteBytesAsync(IStorageFile storageFile, byte[] bytes) { using (Stream stream = await storageFile.OpenStreamForWriteAsync()) { await stream.WriteAsync(bytes, 0, bytes.Length); } }
private static async Task<UploadOperation> CreateUploadOperationForCreateImage( IStorageFile file, string token, BackgroundUploader uploader) { const string boundary = "imgboundary"; List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>(); BackgroundTransferContentPart metadataPart = new BackgroundTransferContentPart("token"); metadataPart.SetText(token); //metadataPart.SetText("iamatoken"); parts.Add(metadataPart); BackgroundTransferContentPart imagePart = new BackgroundTransferContentPart("photo", file.Name); imagePart.SetFile(file); imagePart.SetHeader("Content-Type", file.ContentType); parts.Add(imagePart); return await uploader.CreateUploadAsync( new Uri(HttpFotosSapoPtUploadpostHtmlUri), parts, "form-data", boundary); }
public static async Task Log(string message) { if (file == null) file = await ApplicationData.Current.LocalFolder.CreateFileAsync("VidyanoLog-" + Guid.NewGuid().ToString() + ".txt", CreationCollisionOption.ReplaceExisting); await FileIO.AppendTextAsync(file, message + Environment.NewLine); }
private static async Task<UploadOperation> CreateUploadOperationForCreateVideo( IStorageFile file, string token, BackgroundUploader uploader) { const string boundary = "videoboundary"; List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>(); BackgroundTransferContentPart metadataPart = new BackgroundTransferContentPart("token"); metadataPart.SetText(token); //metadataPart.SetText("iamatoken"); parts.Add(metadataPart); BackgroundTransferContentPart videoPart = new BackgroundTransferContentPart("content_file", file.Name); videoPart.SetFile(file); videoPart.SetHeader("Content-Type", file.ContentType); parts.Add(videoPart); return await uploader.CreateUploadAsync( new Uri(AddVideoPostUri), parts, "form-data", boundary); }
public async Task<bool> OpenSpider( IStorageFile ISF ) { try { SpiderBook SBook = await SpiderBook.ImportFile( await ISF.ReadString(), true ); List<LocalBook> NData; if( Data != null ) { NData = new List<LocalBook>( Data.Cast<LocalBook>() ); if ( NData.Any( x => x.aid == SBook.aid ) ) { Logger.Log( ID, "Already in collection, updating the data", LogType.DEBUG ); NData.Remove( NData.First( x => x.aid == SBook.aid ) ); } } else { NData = new List<LocalBook>(); } NData.Add( SBook ); Data = NData; NotifyChanged( "SearchSet" ); return SBook.CanProcess || SBook.ProcessSuccess; } catch( Exception ex ) { Logger.Log( ID, ex.Message, LogType.ERROR ); } return false; }
/// <summary> /// download a file /// </summary> /// <param name="fileUrl">fileUrl</param> /// <param name="destinationFile">file's destination</param> /// <param name="downloadProgress">a action that can show the download progress</param> /// <param name="priority">background transfer priority </param> /// <param name="requestUnconstrainedDownload"></param> /// <returns></returns> public static async Task DownLoadSingleFileAsync(string fileUrl, IStorageFile destinationFile, Action<DownloadOperation> downloadProgress =null , BackgroundTransferPriority priority = BackgroundTransferPriority.Default, bool requestUnconstrainedDownload = false) { Uri source; if (!Uri.TryCreate(fileUrl, UriKind.Absolute, out source)) { // Logger.Info("File Url:" + fileUrl + "is not valid URIs"); Debug.WriteLine("File Url:" + fileUrl + "is not valid URIs"); return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); download.Priority = priority; Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", source.AbsoluteUri, destinationFile.Name, priority, download.Guid)); if (!requestUnconstrainedDownload) { // Attach progress and completion handlers. await HandleDownloadAsync(download, true, downloadProgress); return; } }
/// <summary> /// Starts the app associated with the specified file. /// </summary> /// <param name="file">The file.</param> /// <returns>The launch operation.</returns> /// <remarks> /// <list type="table"> /// <listheader><term>Platform</term><description>Version supported</description></listheader> /// <item><term>iOS</term><description>iOS 9.0 and later</description></item> /// <item><term>Windows UWP</term><description>Windows 10</description></item> /// <item><term>Windows Store</term><description>Windows 8.1 or later</description></item> /// <item><term>Windows Phone Store</term><description>Windows Phone 8.1 or later</description></item> /// <item><term>Windows Phone Silverlight</term><description>Windows Phone 8.0 or later</description></item> /// <item><term>Windows (Desktop Apps)</term><description>Windows Vista or later</description></item></list></remarks> public static Task<bool> LaunchFileAsync(IStorageFile file) { #if __IOS__ return Task.Run<bool>(() => { bool success = false; UIKit.UIApplication.SharedApplication.InvokeOnMainThread(() => { UIDocumentInteractionController c = UIDocumentInteractionController.FromUrl(global::Foundation.NSUrl.FromFilename(file.Path)); c.ViewControllerForPreview = ViewControllerForPreview; success = c.PresentPreview(true); }); return success; }); #elif __MAC__ return Task.Run<bool>(() => { bool success = NSWorkspace.SharedWorkspace.OpenFile(file.Path); return success; }); #elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE return Windows.System.Launcher.LaunchFileAsync((Windows.Storage.StorageFile)((StorageFile)file)).AsTask(); #elif WIN32 return Task.FromResult<bool>(Launch(file.Path, null)); #else throw new PlatformNotSupportedException(); #endif }
/// <summary> /// Creates a new TailoredDownloadOperation instance. /// </summary> public CreateBackgroundDownloadOperation( LiveConnectClient client, Uri url, IStorageFile outputFile) : base(client, url, ApiMethod.Download, null, null) { this.OutputFile = outputFile; }
public static async Task<FlacMediaSourceAdapter> CreateAsync(IStorageFile file) { var fileStream = await file.OpenAsync(FileAccessMode.Read); var adapter = new FlacMediaSourceAdapter(); adapter.Initialize(fileStream); return adapter; }
internal async static Task WriteTextAsync(IStorageFile storageFile, string text) { using (Stream stream = await storageFile.OpenStreamForWriteAsync()) { byte[] content = Encoding.UTF8.GetBytes(text); await stream.WriteAsync(content, 0, content.Length); } }
public IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> StartDownloadAsync(Uri uri, IStorageFile storageFile) { return AsyncInfo.Run<DownloadOperation, DownloadOperation>((token, progress) => Task.Run<DownloadOperation>(() => { return (DownloadOperation)null; }, token)); }
public EmailAttachment(IStorageFile file) { if (file == null) throw new ArgumentNullException("file"); FileName = file.Name; Content = RandomAccessStreamReference.CreateFromFile(file); }
public Task UploadFromAsync(IStorageFile sourceFile, CancellationToken cancellationToken = default(CancellationToken)) { var request = new Amazon.S3.Transfer.TransferUtilityUploadRequest(); request.BucketName = this.linker.s3.bucket; request.Key = this.linker.s3.key; request.StorageFile = sourceFile; return GetTransferUtility().UploadAsync(request, cancellationToken); }
public void SetLocalLyrics(TrackInfo track, IStorageFile storageFile) { try { StorageApplicationPermissions.FutureAccessList.Add(storageFile); _provider.SetLocalLyricsPath(track, storageFile.Path); } catch { } }
public static async Task SaveToFile(this ZipArchiveEntry entry, IStorageFile file) { Stream newFileStream = await file.OpenStreamForWriteAsync(); Stream fileData = entry.Open(); var data = new byte[entry.Length]; await fileData.ReadAsync(data, 0, data.Length); newFileStream.Write(data, 0, data.Length); await newFileStream.FlushAsync(); }
private bool ValidateFile(IStorageFile file) { if (file.GetExtension() != ".exe") { return false; } var lowerCaseFileName = file.GetFileName().ToLowerInvariant(); return !blacklist.Any(e => lowerCaseFileName.Contains(e)); }
public async void Save_as(IStorageFile file, Excuse excuseToWrite) { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) using(Stream outputStream = stream.AsStreamForWrite()) { DataContractSerializer serializer = new DataContractSerializer(typeof(Excuse)); serializer.WriteObject(outputStream, excuseToWrite); } OnPropertyChanged("excuseToWrite"); }
public static async Task<BindableStorageFile> Create(IStorageFile file) { BindableStorageFile bsf = new BindableStorageFile(); bsf._backingFile = file; var props = await bsf._backingFile.GetBasicPropertiesAsync(); bsf._fileSize = GetHumanReadableSize(props.Size); return bsf; }
private async Task SaveFileToStorageAsync() { string fileToken = NavigationContext.QueryString["fileToken"]; string fileName = SharedStorageAccessManager.GetSharedFileName(fileToken); _storedFile = await SharedStorageAccessManager .CopySharedFileAsync(_filesFolder, fileName, NameCollisionOption.ReplaceExisting, fileToken); }
public static async Task<byte[]> ReadFromFile(IStorageFile file) { var stream = await file.OpenAsync(FileAccessMode.Read); var reader = new DataReader(stream.GetInputStreamAt(0)); var streamSize = (uint) stream.Size; await reader.LoadAsync(streamSize); var buffer = new byte[streamSize]; reader.ReadBytes(buffer); return buffer; }
public static EpubResolver GetResolverBibi(IStorageFile file) => new EpubResolver(file, "/bibi-bookshelf/book.epub", "^/bibi/", "ms-appx:///res/bibi/bibi/", "/bibi/index.html?book=book.epub");
public async Task ReadFile(String path, IStorageFile fiel) { try { MindNode newMasterNode = new MindNode(0, 0, 0, 0, 0, false); string fullText = await Windows.Storage.FileIO.ReadTextAsync(fiel, Windows.Storage.Streams.UnicodeEncoding.Utf8); System.Xml.Linq.XDocument xmlFile = null; try { xmlFile = System.Xml.Linq.XDocument.Parse(fullText); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("No valid XML File falling back to text parser!"); } if (xmlFile == null) { IList <String> text = await Windows.Storage.FileIO.ReadLinesAsync(fiel, Windows.Storage.Streams.UnicodeEncoding.Utf8); String[] FileLines = text.ToArray(); MindNode selectedNode = null; Stack <MindNode> Selnodes = new Stack <MindNode>(); Stack <int> connIds = new Stack <int>(); Stack <Color> conncolors = new Stack <Color>(); Stack <String> connnames = new Stack <String>(); for (int i = 0; i < FileLines.Length; i++) { String[] atts = FileLines[i].Split(':', '/'); switch (atts[0]) { case "ID": selectedNode = newMasterNode.GetExistingNode(int.Parse(atts[1])); break; case "TextPos": if (selectedNode != null) { selectedNode.textpos.X = int.Parse(atts[1]); selectedNode.textpos.Y = int.Parse(atts[2]); } break; case "TextFormat": if (selectedNode != null) { CanvasTextFormat newFormat = new CanvasTextFormat(); newFormat.FontSize = int.Parse(atts[1]); newFormat.FontFamily = atts[2]; if (atts[3].Equals("Italic")) { newFormat.FontStyle = Windows.UI.Text.FontStyle.Italic; } else { newFormat.FontStyle = Windows.UI.Text.FontStyle.Normal; } if (atts[4].Equals("Bold")) { newFormat.FontWeight = FontWeights.Bold; } else { newFormat.FontWeight = FontWeights.Normal; } selectedNode.SetTextStyle(newFormat); selectedNode.TextColor = GetColorFromHexString(atts[5]); } break; case "Name": if (selectedNode != null) { selectedNode.SetText(atts[1]); } break; case "NodeStyle": if (selectedNode != null) { selectedNode.NodeDrawingStyle = DrawingStyle.ELLIPSE; if ((atts[1]).Equals(DrawingStyle.BUTTON.ToString())) { selectedNode.NodeDrawingStyle = DrawingStyle.BUTTON; } if ((atts[1]).Equals(DrawingStyle.CIRCLE.ToString())) { selectedNode.NodeDrawingStyle = DrawingStyle.CIRCLE; } if ((atts[1]).Equals(DrawingStyle.ELLIPSEEDGE.ToString())) { selectedNode.NodeDrawingStyle = DrawingStyle.ELLIPSEEDGE; } if ((atts[1]).Equals(DrawingStyle.RECTANGLE.ToString())) { selectedNode.NodeDrawingStyle = DrawingStyle.RECTANGLE; } } break; case "Color": if (selectedNode != null) { selectedNode.TextColor = GetColorFromHexString(atts[1]); selectedNode.BorderColor = GetColorFromHexString(atts[2]); selectedNode.NodeColor = GetColorFromHexString(atts[3]); } break; case "Bounds": if (selectedNode != null) { selectedNode.width = int.Parse(atts[3]); selectedNode.height = int.Parse(atts[4]); selectedNode.SetPosition(int.Parse(atts[1]), int.Parse(atts[2]), false); } break; case "Scaled": if (selectedNode != null) { selectedNode.SetScaled(true); } break; case "ConnNodes": for (int c = 1; c < atts.Length; c++) { if (atts[c].Length >= 1) { Selnodes.Push(selectedNode); connIds.Push(int.Parse(atts[c])); } } break; case "ConnColors": for (int c = 1; c < atts.Length; c++) { if (atts[c].Length >= 1) { conncolors.Push(GetColorFromHexString(atts[c])); } } break; case "ConnNames": for (int c = 1; c < atts.Length; c++) { if (atts[c].Length >= 1) { connnames.Push(atts[c]); } } break; case "Childs": for (int c = 1; c < atts.Length; c++) { if (atts[c].Length >= 1) { MindNode newNode = newMasterNode.GetExistingNode(int.Parse(atts[c])); if (newNode == null) { newNode = new MindNode(int.Parse(atts[c]), 0, 0, 0, 0, false); } selectedNode.AddChild(newNode, true); } } break; } } MindNode m; String connText; Color ncolor; while (Selnodes.Count > 0) { m = newMasterNode.GetExistingNode(connIds.Pop()); connText = connnames.Pop(); ncolor = conncolors.Pop(); MindNode selectednode = Selnodes.Pop(); selectednode.AddConnection(m, ncolor, connText); } } GlobalNodeHandler.masterNode = newMasterNode; if (xmlFile != null) { GlobalNodeHandler.masterNode.FromRepresentation(xmlFile); } GlobalNodeHandler.masterNode.UpdateAllWidths(); } catch { } }
internal SearchResult(IStorageFile file, CoreDispatcher dispatcher) : base(dispatcher) { File = file; }
/// <summary> /// 从文件加载媒体,如之前有加载媒体,则会将其关闭。 /// </summary> /// <param name="mediaFile"></param> /// <returns></returns> public async Task LoadFileAsync(IStorageFile mediaFile) { await CalculateFrameRateFromFileAsync(mediaFile).ConfigureAwait(false); Source = MediaSource.CreateFromStorageFile(mediaFile); }
public IAsyncAction CopyAndReplaceAsync(IStorageFile fileToReplace) { throw new NotImplementedException(); }
public AfpResultCode Process(IAfpSession session, DsiHeader dsiHeader, AfpStream requestStream, AfpStream responseStream) { byte flag = requestStream.ReadUInt8(); ushort volumeId = requestStream.ReadUInt16(); uint directoryId = requestStream.ReadUInt32(); bool resourceFork = (flag == 0x80); if (resourceFork) { Log.Add(this, EntryType.Error, "Session '{0}' attempted to open resource fork, failing...", session); return(AfpResultCode.FPMiscErr); } AfpFileDirectoryBitmap bitmap = requestStream.ReadEnum <AfpFileDirectoryBitmap>(); AfpAccessModes accessMode = requestStream.ReadEnum <AfpAccessModes>(); AfpPathType pathType = requestStream.ReadEnum <AfpPathType>(); string path = null; switch (pathType) { case AfpPathType.kFPLongName: case AfpPathType.kFPShortName: path = requestStream.ReadPascalString(); break; case AfpPathType.kFPUTF8Name: path = requestStream.ReadUTF8StringWithHint(); break; } IAfpVolume volume = session.GetVolume(volumeId); if (volume == null) { throw new StorageItemNotFoundException(); } IStorageContainer container = null; if (directoryId == 2) { container = volume.StorageProvider; } else { container = (volume.GetNode(directoryId) as IStorageContainer); } if (container == null) { throw new StorageItemNotFoundException(); } IStorageFile file = (container.Content(path) as IStorageFile); if (file == null) { throw new StorageItemNotFoundException(); } IAfpFork info = session.OpenFork(file, accessMode); if (info == null) { throw new StorageItemNotFoundException(); } responseStream.WriteEnum <AfpFileDirectoryBitmap>(bitmap); responseStream.WriteInt16(info.Identifier); responseStream.WriteStorageFileInfo(volume, file, bitmap); return(AfpResultCode.FPNoErr); }
private ApplicationDataContainer appSetting = ApplicationData.Current.LocalSettings; //本地存储 public async void Run(IBackgroundTaskInstance taskInstance) { if (bool.Parse(appSetting.Values["isUseingBackgroundTask"].ToString())) { Debug.WriteLine("开始吐司通知后台任务"); var vault = new Windows.Security.Credentials.PasswordVault(); var credentialList = vault.FindAllByResource(resourceName); credentialList[0].RetrievePassword(); stuNum = credentialList[0].UserName; idNum = credentialList[0].Password; try { string letterstatus = ""; BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); //获取 BackgroundTaskDeferral 对象,表示后台任务延期 List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >(); paramList.Add(new KeyValuePair <string, string>("stuNum", stuNum)); paramList.Add(new KeyValuePair <string, string>("idNum", idNum)); paramList.Add(new KeyValuePair <string, string>("page", "0")); paramList.Add(new KeyValuePair <string, string>("size", "15")); letterstatus = await NetWork.getHttpWebRequest("cyxbsMobile/index.php/Home/Article/aboutme", paramList); Debug.WriteLine("letterstatus" + letterstatus); if (letterstatus != "") { string aboutme = ""; IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; try { IStorageFile storageFileRE = await applicationFolder.GetFileAsync("aboutme.txt"); IRandomAccessStream accessStream = await storageFileRE.OpenReadAsync(); using (StreamReader streamReader = new StreamReader(accessStream.AsStreamForRead((int)accessStream.Size))) { aboutme = streamReader.ReadToEnd(); } Debug.WriteLine("aboutme:" + aboutme); if (aboutme != letterstatus) { JObject obj = JObject.Parse(letterstatus); if (Int32.Parse(obj["status"].ToString()) == 200) { JArray jArray = (JArray)JsonConvert.DeserializeObject(obj["data"].ToString()); if (jArray[0]["type"].ToString() == "praise") { Utils.Toast(jArray[0]["nickname"].ToString() + "赞了你~~\n你可能还有有新的消息,快来看看吧"); } else if (jArray[0]["type"].ToString() == "remark") { Utils.actionsToast(jArray[0]["nickname"].ToString() + " 评论了 " + "\"" + jArray[0]["article_content"].ToString() + "\"", "\"" + jArray[0]["content"].ToString() + "\"", jArray[0]["article_id"].ToString() + "+" + jArray[0]["stunum"] + "+" + jArray[0]["nickname"]); //if (jArray[0]["content"].ToString().Length > 20) //{ // Utils.Toast(jArray[0]["nickname"].ToString() + "评论了你~\n" + "\"" + jArray[0]["content"].ToString().Substring(0, 20) + "\"" + "\n你可能还有有新的消息,快来看看吧"); //} //else //{ // Utils.Toast(jArray[0]["nickname"].ToString() + "评论了你~\n" + "\"" + jArray[0]["content"].ToString() + "\"" + "\n你可能还有有新的消息,快来看看吧"); //} } else { Utils.Toast("你可能有新的消息,快来看看吧"); } } IStorageFile storageFileWR = await applicationFolder.CreateFileAsync("aboutme.txt", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(storageFileWR, letterstatus); } } catch (FileNotFoundException) { IStorageFile storageFileWR = await applicationFolder.CreateFileAsync("aboutme.txt", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(storageFileWR, letterstatus); } } deferral.Complete(); //所有的异步调用完成之后,释放延期,表示后台任务的完成 Debug.WriteLine("吐司通知后台任务结束"); } catch (Exception) { Debug.WriteLine("吐司通知后台任务异常"); } } }
public async void Run(IBackgroundTaskInstance taskInstance) { appSetting = ApplicationData.Current.LocalSettings; //本地存储 BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; var files = await applicationFolder.GetFilesAsync(); int[] kk; foreach (StorageFile file in files) { tileId = file.Name.ToString(); if (appSetting.Values.ContainsKey(tileId) == false) { appSetting.Values[tileId] = false; } string text = ""; IStorageFile storageFileRE = await applicationFolder.GetFileAsync(file.Name.ToString()); IRandomAccessStream accessStream = await storageFileRE.OpenReadAsync(); using (StreamReader streamReader = new StreamReader(accessStream.AsStreamForRead((int)accessStream.Size))) { text = streamReader.ReadToEnd(); } kk = DateTimeDiff.dateTimeDiff.toResult(text.Substring(text.IndexOf("!@#$%^&*") + 8), DateTime.Now.Date.ToString(), DateTimeDiff.diffResultFormat.dd); Debug.WriteLine(kk[0].ToString()); string EventFileRemarks = text.Substring(0, text.IndexOf("!@#$%^&*")); string EventFileTitle = file.Name.ToString(); string EventFileDateRemain = kk[0].ToString(); string EventFileDate = text.Substring(text.IndexOf("!@#$%^&*") + 8); //当日发送toast if (kk[0] == 0 && !(bool)appSetting.Values[tileId]) { XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText02); XmlNodeList elements = toastXml.GetElementsByTagName("text"); elements[0].AppendChild(toastXml.CreateTextNode(tileId)); elements[1].AppendChild(toastXml.CreateTextNode("今日完成")); ToastNotification toast = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier().Show(toast); appSetting.Values[tileId] = true; } //更新磁贴 try { XmlDocument wideTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150BlockAndText01); XmlNodeList wideTileTextAttributes = wideTileXml.GetElementsByTagName("text"); wideTileTextAttributes[0].AppendChild(wideTileXml.CreateTextNode(EventFileDateRemain)); wideTileTextAttributes[2].AppendChild(wideTileXml.CreateTextNode(tileId)); if (DateTime.Now.Date < DateTime.Parse(EventFileDate)) { wideTileTextAttributes[1].AppendChild(wideTileXml.CreateTextNode("剩余")); } else { wideTileTextAttributes[1].AppendChild(wideTileXml.CreateTextNode("已过")); } if (EventFileRemarks != "") { wideTileTextAttributes[3].AppendChild(wideTileXml.CreateTextNode(EventFileRemarks)); } else { wideTileTextAttributes[3].AppendChild(wideTileXml.CreateTextNode("无备注")); } XmlDocument squareTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text01); XmlNodeList squareTileXmlAttributes = squareTileXml.GetElementsByTagName("text"); squareTileXmlAttributes[0].AppendChild(squareTileXml.CreateTextNode(tileId)); squareTileXmlAttributes[1].AppendChild(squareTileXml.CreateTextNode(EventFileRemarks)); if (DateTime.Now.Date < DateTime.Parse(EventFileDate)) { squareTileXmlAttributes[2].AppendChild(squareTileXml.CreateTextNode("剩余 " + EventFileDateRemain + " 天")); } else { squareTileXmlAttributes[2].AppendChild(squareTileXml.CreateTextNode("已过 " + EventFileDateRemain + " 天")); } var TileUpdater = TileUpdateManager.CreateTileUpdaterForSecondaryTile(tileId); ScheduledTileNotification wideSchedule = new ScheduledTileNotification(wideTileXml, DateTimeOffset.Now.AddSeconds(5)); ScheduledTileNotification squareSchedule = new ScheduledTileNotification(squareTileXml, DateTimeOffset.Now.AddSeconds(5)); TileUpdater.Clear(); TileUpdater.EnableNotificationQueue(true); TileUpdater.AddToSchedule(squareSchedule); TileUpdater.AddToSchedule(wideSchedule); } catch (Exception) { } } deferral.Complete(); }
public async Task CopyAndReplaceAsync(IStorageFile fileToReplace) { }
/// <summary> /// Download a file to disk. /// </summary> /// <param name="path">relative or absolute uri to the file to be downloaded.</param> /// <param name="outputFile">the file object that the downloaded content is written to.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public Task <LiveDownloadOperationResult> BackgroundDownloadAsync(string path, IStorageFile outputFile) { return(this.BackgroundDownloadAsync(path, outputFile, new CancellationToken(false), null)); }
/// <summary> /// Creates background download operation. /// </summary> /// <param name="path"></param> /// <param name="outputFile"></param> /// <returns></returns> public Task <LiveDownloadOperation> CreateBackgroundDownloadAsync(string path, IStorageFile outputFile = null) { if (path == null) { throw new ArgumentNullException("path"); } var op = new CreateBackgroundDownloadOperation( this, this.GetResourceUri(path, ApiMethod.Download), outputFile); return(op.ExecuteAsync()); }
public RecentFile(IStorageFile storageFile, bool printErrors) { StorageFile = storageFile; Token = StorageApplicationPermissions.FutureAccessList.Add(file: storageFile); PrintErrors = printErrors; }
private async Task AnalyzeNode(BatProject project, BatNode node, IStorageFile rawDataFile) { RawNodeData rawData = await _batNodeLogReader.Load(rawDataFile); _logAnalyzer.Analyze(project, node, rawData); }
/// <summary> /// Updates the id3 tags. WARNING, there needs to be more testing with lower end devices. /// </summary> /// <param name="song">The song.</param> /// <param name="file">The file.</param> private async Task <bool> UpdateId3TagsAsync(Song song, IStorageFile file) { using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false)) { TagLib.File tagFile; try { tagFile = TagLib.File.Create(new SimpleFileAbstraction(file.Name, fileStream, fileStream)); } catch (CorruptFileException) { await CollectionHelper.DeleteEntryAsync(song); await file.DeleteAsync(); return(false); } catch { return(false); } var newTags = tagFile.GetTag(TagTypes.Id3v2, true); newTags.Title = song.Name; if (song.Artist.ProviderId != "autc.unknown") { newTags.Performers = song.ArtistName.Split(',').Select(p => p.Trim()).ToArray(); } newTags.Album = song.Album.Name; newTags.AlbumArtists = new[] { song.Album.PrimaryArtist.Name }; if (!string.IsNullOrEmpty(song.Album.Genre)) { newTags.Genres = song.Album.Genre.Split(',').Select(p => p.Trim()).ToArray(); } newTags.Track = (uint)song.TrackNumber; newTags.MusicIpId = song.RadioId.ToString(); newTags.MusicBrainzTrackId = song.CloudId; newTags.Comment = "Downloaded by airstem for Windows 10."; try { if (song.Album.HasArtwork) { var albumFilePath = string.Format(AppConstant.ArtworkPath, song.Album.Id); var artworkFile = await StorageHelper.GetFileAsync(albumFilePath).ConfigureAwait(false); using (var artworkStream = await artworkFile.OpenAsync(PCLStorage.FileAccess.Read)) { using (var memStream = new MemoryStream()) { await artworkStream.CopyToAsync(memStream); newTags.Pictures = new IPicture[] { new Picture( new ByteVector( memStream.ToArray(), (int)memStream.Length)) }; } } } } catch (UnauthorizedAccessException) { ToastManager.ShowError("UnauthorizedAccess Exception."); // Should never happen, since we are opening the files in read mode and nothing is locking it. } await Task.Run(() => tagFile.Save()); return(true); } }
public StorageFile(IStorageFile file) { Populate(file, this); }
private Document(IStorageFile storageFile) : base(storageFile) { }
public override void Close() { base.Close(); StorageFile = null; }
internal static async Task <ReportItem> CreateReportItemAsync(string title, string description, IMappablePoint point, IStorageFile image) { var item = new ReportItem() { Title = title, Description = description, NativeId = Guid.NewGuid().ToString(), Status = ReportItemStatus.New }; item.SetLocation(point); // save... var conn = StreetFooRuntime.GetUserDatabase(); await conn.InsertAsync(item); // stage the image... if (image != null) { // new path... var manager = new ReportImageCacheManager(); var folder = await manager.GetCacheFolderAsync(); // create... await image.CopyAsync(folder, item.NativeId + ".jpg"); } // return... return(item); }
private async Task CalculateFrameRateFromFileAsync(IStorageFile file) { MediaEncodingProfile profile = await MediaEncodingProfile.CreateFromFileAsync(file); FrameRate = (double)profile.Video.FrameRate.Numerator / profile.Video.FrameRate.Denominator; }
public IAsyncAction MoveAndReplaceAsync(IStorageFile fileToReplace) => AsyncAction.FromTask(ct => _impl.MoveAndReplace(ct, fileToReplace));
static async Task <int> SearchFileAsync(IStorageFile file, SearchRequest request, CancellationToken cancellationToken) { var streamToRead = await file.OpenStreamForReadAsync().ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); StreamReader GetStreamReader() { if (request.Encoding == null) { return(new StreamReader(streamToRead, true)); } else { return(new StreamReader(streamToRead, request.Encoding, true)); } }; int occurrences = 0; string data; Encoding detectedEncoding; using (var streamReader = GetStreamReader()) { detectedEncoding = streamReader.CurrentEncoding; data = streamReader.ReadToEnd(); cancellationToken.ThrowIfCancellationRequested(); for (int i = 0; i < request.SearchFor.Length; i++) { var searchText = request.SearchFor[i]; string searchString; if (!request.UseRegularExpression) { searchString = Regex.Escape(searchText); } else { searchString = searchText; } var regex = new Regex(searchString, request.MatchCase ? RegexOptions.None : RegexOptions.IgnoreCase); var matches = regex.Matches(data); if (matches.Count > 0) { occurrences += matches.Count; if (request is SearchAndReplaceRequest replaceRequest) { var replaceText = replaceRequest.ReplaceWith[i]; data = regex.Replace(data, replaceText); } } cancellationToken.ThrowIfCancellationRequested(); } } if (request is SearchAndReplaceRequest) { if (occurrences > 0) { var streamToWrite = await file.OpenStreamForWriteAsync().ConfigureAwait(false); streamToWrite.SetLength(0); using (var streamWriter = new StreamWriter(streamToWrite, detectedEncoding)) { streamWriter.Write(data); streamWriter.Flush(); } } } return(occurrences); }
internal Task CopyAndReplace(CancellationToken ct, IStorageFile target) => _impl.CopyAndReplace(ct, target);
/// <summary> /// Constructs a LiveDownloadOperationResult object. /// </summary> /// <param name="file">The IStorageFile object for the downloaded file.</param> internal LiveDownloadOperationResult(IStorageFile file) { this.File = file; }
private async Task <List <ImportFileItem> > GetFilesInArchive(SkyDriveItemType parentType, IStorageFile file) { List <ImportFileItem> listItems = new List <ImportFileItem>(); if (file != null) { IRandomAccessStream accessStream = await file.OpenReadAsync(); Stream s = accessStream.AsStreamForRead((int)accessStream.Size); //get list of file IArchive archive = null; if (parentType == SkyDriveItemType.Rar) { archive = SharpCompress.Archive.Rar.RarArchive.Open(s); } else if (parentType == SkyDriveItemType.Zip) { archive = SharpCompress.Archive.Zip.ZipArchive.Open(s); } else if (parentType == SkyDriveItemType.SevenZip) { archive = SharpCompress.Archive.SevenZip.SevenZipArchive.Open(s); } foreach (var entry in archive.Entries) { if (!entry.IsDirectory) { Stream data = new MemoryStream(); entry.WriteTo(data); data.Position = 0; String name = entry.FilePath; SkyDriveItemType type = SkyDriveItemType.File; int dotIndex = -1; if ((dotIndex = name.LastIndexOf('.')) != -1) { String substrName = name.Substring(dotIndex).ToLower(); type = SkyDriveImportPage.GetSkyDriveItemType(substrName); } if (type == SkyDriveItemType.File) { data.Close(); continue; } ImportFileItem listItem = new ImportFileItem() { Name = name, Type = type, Stream = data }; listItems.Add(listItem); } } //close the zip stream since we have the stream of each item inside it already s.Close(); s = null; } return(listItems); }
public static EpubResolver GetResolverBasic(IStorageFile file) => new EpubResolver(file, "/contents/book.epub", "^/reader/", "ms-appx:///res/reader/", "/reader/index.html");
public override IAsyncAction MoveAndReplaceAsync(IStorageFile fileToReplace) { throw new NotSupportedException(); }
/// <summary> /// Saves the given <see cref="WriteableBitmap" /> to a specified storage file. /// </summary> /// <param name="writeableBitmap">The writeable bitmap.</param> /// <param name="storageFile">The storage file.</param> public static async Task SaveToStorageFile(this WriteableBitmap writeableBitmap, IStorageFile storageFile) { using (var writestream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, writestream); using (var pixelStream = writeableBitmap.PixelBuffer.AsStream()) { var pixels = new byte[pixelStream.Length]; await pixelStream.ReadAsync(pixels, 0, pixels.Length); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96.0, 96.0, pixels); await encoder.FlushAsync(); } } }
public async Task MoveAndReplaceAsync(IStorageFile fileToReplace) { }
public AddFileResult AddFile(string id, IStorageFile storageFile) { AddedFileIds.Add(id); return(ExpectedResult); }
protected abstract Task WriteTextToFileCore(IStorageFile file, string contents);