Inheritance: IStorageFolder, IStorageItem, IStorageFolderQueryOperations, IStorageItemProperties
Ejemplo n.º 1
1
        /// <summary>
        /// Loads file from path
        /// </summary>
        /// <param name="filepath">path to a file</param>
        /// <param name="folder">folder or null (to load from application folder)</param>
        /// <returns></returns>
        protected XDocument LoadFile(string filepath, StorageFolder folder)
        {
            try
            {
                StorageFile file;

                //load file
                if (folder == null)
                {
                    var uri = new Uri(filepath);
                    file = StorageFile.GetFileFromApplicationUriAsync(uri).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
                }
                else
                {
                    file = folder.GetFileAsync(filepath).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
                }

                //parse and return
                var result = FileIO.ReadTextAsync(file).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
                return XDocument.Parse(result);
            }
            catch
            {
                return null;
            }
        }
        static FileSnapshotTarget()
        {
            // create a task to load the folder...
            _setupTask = Task<Task<StorageFolder>>.Factory.StartNew(async () =>
            {
                // get...
                var root = ApplicationData.Current.LocalFolder;
                try
                {
                    await root.CreateFolderAsync(LogFolderName);
                }
                catch (FileNotFoundException ex)
                {
                    SinkException(ex);
                }

                // load...
                return await root.GetFolderAsync(LogFolderName);

            }).ContinueWith(async (t, args) =>
            {
                // set...
                LogFolder = await t.Result;

            }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.LongRunning);
        }
Ejemplo n.º 3
0
        async Task Init()
        {
            try
            {
                cacheFolder = await ApplicationData.Current.TemporaryFolder.CreateFolderAsync(cacheFolderName, CreationCollisionOption.OpenIfExists);
                await InitializeEntries().ConfigureAwait(false);
            }
            catch
            {
                StorageFolder folder = null;

                try
                {
                    folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(cacheFolderName);
                }
                catch (Exception)
                {
                }

                if (folder != null)
                {
                    await folder.DeleteAsync();
                    await ApplicationData.Current.LocalFolder.CreateFolderAsync(cacheFolderName, CreationCollisionOption.ReplaceExisting);
                }
            }
            finally
            {
                var task = CleanCallback();
            }
        }
        public MainPage()
        {
            InitializeComponent();
            Current = this;

            localFolder = ApplicationData.Current.LocalFolder;
        }
Ejemplo n.º 5
0
        private static async Task Inflate(StorageFile zipFile, StorageFolder destFolder)
        {
            if (zipFile == null)
            {
                throw new Exception("StorageFile (zipFile) passed to Inflate is null");
            }
            else if (destFolder == null)
            {
                throw new Exception("StorageFolder (destFolder) passed to Inflate is null");
            }

            Stream zipStream = await zipFile.OpenStreamForReadAsync();

            using (ZipArchive zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Read))
            {
                //Debug.WriteLine("Count = " + zipArchive.Entries.Count);
                foreach (ZipArchiveEntry entry in zipArchive.Entries)
                {
                    //Debug.WriteLine("Extracting {0} to {1}", entry.FullName, destFolder.Path);
                    try
                    {
                        await InflateEntryAsync(entry, destFolder);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Exception: " + ex.Message);
                    }
                }
            }
        }
 public async Task Init()
 {
     var path =  Package.Current.InstalledLocation;
     _installedPath = await path.CreateFolderAsync("Databases", CreationCollisionOption.OpenIfExists);
 
     _databaseInfoRepository = new DatabaseInfoRepository();
 }
Ejemplo n.º 7
0
        public GetPictures(StorageFolder folder)
        {
            Pictures = new ObservableCollection<Picture>();
            allPictures = new ObservableCollection<StorageFile>();

            GetAllPictures(folder);
        }
        /// <summary>
        ///     Specifies a path to directory where to save/load images.
        /// </summary>
        /// <param name="directory">
        ///     The path to directory with images.
        /// </param>
        /// <returns>
        ///     The instance of the loader.
        /// </returns>
        /// <remarks>
        ///     If the directory is not specified, i.e. <see cref="WithDirectory"/> is not called, then the default temp directory will be used.
        /// </remarks>
        public IsolatedStorageImageLoader WithDirectory(string directory)
        {
            if (string.IsNullOrWhiteSpace(directory))
            {
                throw new ArgumentNullException("directory");
            }

            lock (this.indexSyncObject)
            {
                if (this.cacheFolder == null || this.cacheFolder.Path.EndsWith(directory, StringComparison.InvariantCultureIgnoreCase) == false)
                {
                    if (this.updateIndexToken != null)
                    {
                        this.updateIndexToken.Cancel();
                    }

                    this.ClearIndex();

                    this.cacheFolder = ApplicationData.Current.LocalFolder.CreateFolderAsync(directory, CreationCollisionOption.OpenIfExists).GetAwaiter().GetResult();
                    this.updateIndexToken = new CancellationTokenSource();
                    this.UpdateIndexAsync(this.updateIndexToken.Token);
                }
            }

            return this;
        }
Ejemplo n.º 9
0
        public async Task<IEnumerable<IFile>> GetFiles()
        {
            if (m_files == null)
            {
                m_files = new List<IFile>();
                foreach (StorageFile file in await m_folder.GetFilesAsync())
                {
                    //don't ping the network
                    //make the configurable later
                    if (!file.Attributes.HasFlag(FileAttributes.LocallyIncomplete))
                    {
                        IFile f = await File.GetNew(file, m_root);
                        m_files.Add(f);
                    }
                }
            }

            //we want to clear out the StorageFolder so that it can be 
            //garbage collected after both the files and directories
            //have been retrieved
            if (m_dirs != null)
            {
                m_folder = null;
            }

            return m_files;
        }
Ejemplo n.º 10
0
        public Directory(StorageFolder folder, StorageFolder root)
        {
            m_folder = folder;
            m_root = root;

            m_path = folder.Path;
        }
Ejemplo n.º 11
0
        async Task Init()
        {
            if (isInitialized != null)
                return;

            cacheFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(cacheFolderName, CreationCollisionOption.OpenIfExists);

            try
            {
                isInitialized = InitializeWithJournal();
                await isInitialized;
            }
            catch
            {
                StorageFolder folder = null;

                try
                {
                    folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(cacheFolderName);
                }
                catch (Exception)
                {
                }

                if (folder != null)
                {
                    await folder.DeleteAsync();
                    await ApplicationData.Current.LocalFolder.CreateFolderAsync(cacheFolderName, CreationCollisionOption.ReplaceExisting);
                }
            }

            await CleanCallback();
        }
Ejemplo n.º 12
0
        public async Task itializeClass()
        {
            QueueCycleMilliSeconds = 500;
            this.folder = Windows.Storage.ApplicationData.Current.LocalFolder;

            try
            {

                this.file = folder.CreateFileAsync("SparkQueueDB.txt", CreationCollisionOption.OpenIfExists).AsTask().Result;

            }
            catch (Exception ex)
            {
                this.Errors.Add("Queue Failed To Initialize");
                this.Errors.Add(ex.Message.ToString());

            }

            inboundQueue = new Queue();
            outboundQueue = new Queue();

            //if (Program.strPowerOuttageMissedDownEvent.Length > 1)
            //{
            //    this.Enqueue(Program.strPowerOuttageMissedDownEvent);
            //    Program.strPowerOuttageMissedDownEvent = "";
            //}

            InboundDataTimer = new Timer(new TimerCallback(ProcessInboundEvent), new Object(), 250, 250);
            OutboundDataTimer = new Timer(new TimerCallback(ProcessOutboundEvent), new Object(), 250, 250);

            this.file = null;
            this.folder = null;
        }
		private async void BrowseButton_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				var folderPicker = new FolderPicker()
				{
					CommitButtonText = "Open",
					SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
					ViewMode = PickerViewMode.List
				};
				folderPicker.FileTypeFilter.Add(".shp");

				_folder = await folderPicker.PickSingleFolderAsync();
				if (_folder != null)
				{
					var qopts = new QueryOptions(CommonFileQuery.OrderByName, new string[] { ".shp" });
					var query = _folder.CreateFileQueryWithOptions(qopts);
					var files = await query.GetFilesAsync();
					FileListCombo.ItemsSource = files;
					FileListCombo.Visibility = (files.Any()) ? Visibility.Visible : Visibility.Collapsed;
				}
			}
			catch (Exception ex)
			{
				var _ = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
			}
		}
        public static async Task<BitmapImage> LoadAsync(StorageFolder folder, string fileName)
        {
            BitmapImage bitmap = new BitmapImage();

            var file = await folder.GetFileByPathAsync(fileName);
            return await bitmap.SetSourceAsync(file);
        }
Ejemplo n.º 15
0
        async public static Task UnZipFile(StorageFolder zipFileDirectory, string zipFilename, StorageFolder extractFolder = null)
        {
            if (extractFolder == null) extractFolder = zipFileDirectory;

            var folder = ApplicationData.Current.LocalFolder;

            using (var zipStream = await folder.OpenStreamForReadAsync(zipFilename))
            {
                using (MemoryStream zipMemoryStream = new MemoryStream((int)zipStream.Length))
                {
                    await zipStream.CopyToAsync(zipMemoryStream);

                    using (var archive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Read))
                    {
                        foreach (ZipArchiveEntry entry in archive.Entries)
                        {
                            if (entry.Name != "")
                            {
                                using (Stream fileData = entry.Open())
                                {
                                    StorageFile outputFile = await extractFolder.CreateFileAsync(entry.FullName, CreationCollisionOption.ReplaceExisting);
                                    using (Stream outputFileStream = await outputFile.OpenStreamForWriteAsync())
                                    {
                                        await fileData.CopyToAsync(outputFileStream);
                                        await outputFileStream.FlushAsync();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Gets a new filename which starts as the base filename parameter, but has a different end part.
        /// </summary>
        /// <param name="folder">The folder where the name will be checked.</param>
        /// <param name="baseFileName">Base filename to use as root.</param>
        /// <returns>
        /// The new filename.
        /// </returns>
        /// <example>
        /// In case that "naruto" does not exist in folder.
        /// GetNewFileName(folder, "naruto") -&gt; "naruto"
        /// GetNewFileName(folder, "naruto") -&gt; "naruto_1"
        /// GetNewFileName(folder, "naruto") -&gt; "naruto_2"
        /// ...
        ///   </example>
        public static string GetNewFileName(StorageFolder folder, string baseFileName)
        {
            try
            {
                var names = folder.GetFilesAsync()
                                .AsTask().Result
                                .Select(f => Path.GetFileNameWithoutExtension(f.Name));

                string possibleName = baseFileName;
                int index = 1;
                while (true)
                {
                    if (names.Any(n => n.Equals(possibleName, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        possibleName = baseFileName + index++;
                    }
                    else
                    {
                        break;
                    }
                }

                return possibleName;
            }
            catch (Exception)
            {
                return baseFileName;
            }
        }
Ejemplo n.º 17
0
		private async Task LoadData()
		{
			DarkMode = StorageHelper.GetSetting("DarkMode") == "1";
			DirectExit = StorageHelper.GetSetting("DirectExit") == "1";
			Tail = StorageHelper.GetSetting("Tail");
			if (string.IsNullOrEmpty(Tail))
				Tail = "From 花瓣UWP";

			var savePath = StorageHelper.GetSetting("SavePath");
			if (!string.IsNullOrWhiteSpace(savePath))
			{
				try
				{
					SavePath = await StorageFolder.GetFolderFromPathAsync(savePath);
				}
				catch (Exception ex)
				{
					SavePath = await KnownFolders.PicturesLibrary.CreateFolderAsync("huaban", CreationCollisionOption.OpenIfExists);
				}
			}
			else
			{
				SavePath = await KnownFolders.PicturesLibrary.CreateFolderAsync("huaban", CreationCollisionOption.OpenIfExists);
			}
		}
Ejemplo n.º 18
0
 public Library()
 {
     clientID = "76f442af00e77c8423177dc013a7f374a9d98de21ad2db7f4327fa030bf0f5c2";
     authEndPoint = "https://auth.teamsnap.com/oauth/authorize?client_id=";
     callBackURL = "https://www.bing.com/";
     localFolder = ApplicationData.Current.LocalFolder;
 }
Ejemplo n.º 19
0
 public static async Task<string[]> GetFiles(StorageFolder folder, string extension=null)
 {
     if (extension == null) {
         return await FileIO.GetFiles(folder);
     }
     return await FileIO.GetFiles(folder, extension);
 }
Ejemplo n.º 20
0
        private async void GetAllVideos(StorageFolder KnownFolders, QueryOptions QueryOptions)
        {
            StorageFileQueryResult query = KnownFolders.CreateFileQueryWithOptions(QueryOptions);
            IReadOnlyList<StorageFile> folderList = await query.GetFilesAsync();

            // Get all the videos in the folder past in parameter
            int id = 0;
            foreach (StorageFile file in folderList)
            {
                using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.VideosView, 200, ThumbnailOptions.UseCurrentScale))
                {
                    // Get video's properties
                    VideoProperties videoProperties = await file.Properties.GetVideoPropertiesAsync();

                    BitmapImage VideoCover = new BitmapImage();
                    VideoCover.SetSource(thumbnail);

                    Video video = new Video();
                    video.Id = id;
                    video.Name = file.Name;
                    video.DateCreated = file.DateCreated.UtcDateTime;
                    video.FileType = file.FileType;
                    video.VideoPath = file.Path;
                    video.Duration = videoProperties.Duration;
                    video.VideoFile = file;
                    video.VideoCover = VideoCover;

                    // Add the video to the ObservableCollection
                    Videos.Add(video);
                    id++;
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Gets File located in Local Storage,
        /// Input file name may include folder paths seperated by "\\".
        /// Example: filename = "Documentation\\Tutorial\\US\\ENG\\version.txt"
        /// </summary>
        /// <param name="filename">Name of file with full path.</param>
        /// <param name="rootFolder">Parental folder.</param>
        /// <returns>Target StorageFile.</returns>
        public async Task<StorageFile> GetFileAsync(string filename, StorageFolder rootFolder = null)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return null;
            }

            var semaphore = GetSemaphore(filename);
            await semaphore.WaitAsync();

            try
            {
                rootFolder = rootFolder ?? AntaresBaseFolder.Instance.RoamingFolder;
                return await rootFolder.GetFileAsync(NormalizePath(filename));
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogException(ex.ToString());
                return null;
            }
            finally
            {
                semaphore.Release();
            }
        }
Ejemplo n.º 22
0
 public static async Task UnzipFromStorage(StorageFile pSource, StorageFolder pDestinationFolder, IEnumerable<string> pIgnore)
 {
     using (var stream = await pSource.OpenStreamForReadAsync())
     {
         await UnzipFromStream(stream, pDestinationFolder,pIgnore.ToList());
     }
 }
Ejemplo n.º 23
0
        public FileDbCache(string name = null, StorageFolder folder = null)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = TileImageLoader.DefaultCacheName;
            }

            if (string.IsNullOrEmpty(Path.GetExtension(name)))
            {
                name += ".fdb";
            }

            if (folder == null)
            {
                folder = TileImageLoader.DefaultCacheFolder;
            }

            this.folder = folder;
            this.name = name;

            Application.Current.Resuming += async (s, e) => await Open();
            Application.Current.Suspending += (s, e) => Close();

            var task = Open();
        }
Ejemplo n.º 24
0
 public async void AddFolder(StorageFolder folder)
 {
     var path = folder.Path;
     if (!_playlist.Folders.Contains(path))
         _playlist.Folders.Add(path);
     await Save();
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Creates new LimitedStorageCache instance
 /// </summary>
 /// <param name="isf">StorageFolder instance to work with file system</param>
 /// <param name="cacheDirectory">Directory to store cache, starting with two slashes "\\"</param>
 /// <param name="cacheFileNameGenerator">ICacheFileNameGenerator instance to generate cache filenames</param>
 /// <param name="cacheLimitInBytes">Limit of total cache size in bytes, for example 10 mb == 10 * 1024 * 1024</param>
 /// <param name="cacheMaxLifetimeInMillis">Cache max lifetime in millis, for example two weeks = 2 * 7 * 24 * 60 * 60 * 1000; default value == one week; pass value &lt;= 0 to disable max cache lifetime</param>
 public LimitedStorageCache(StorageFolder isf, string cacheDirectory,
     ICacheGenerator cacheFileNameGenerator, long cacheLimitInBytes, long cacheMaxLifetimeInMillis = DefaultCacheMaxLifetimeInMillis)
     : base(isf, cacheDirectory, cacheFileNameGenerator, cacheMaxLifetimeInMillis)
 {
     _cacheLimitInBytes = cacheLimitInBytes;
     BeginCountCurrentCacheSize();
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Writes a string to a text file.
        /// </summary>
        /// <param name="text">The text to write.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="folder">The folder.</param>
        /// <param name="options">
        /// The enum value that determines how responds if the fileName is the same
        /// as the name of an existing file in the current folder. Defaults to ReplaceExisting.
        /// </param>
        /// <returns></returns>
        public static async Task SaveAsync(
            this string text,
            string fileName,
            StorageFolder folder = null,
            CreationCollisionOption options = CreationCollisionOption.ReplaceExisting)
        {
            folder = folder ?? ApplicationData.Current.LocalFolder;
            var file = await folder.CreateFileAsync(
                fileName,
                options);
            using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var outStream = fs.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outStream))
                    {
                        if (text != null)
                            dataWriter.WriteString(text);

                        await dataWriter.StoreAsync();
                        dataWriter.DetachStream();
                    }

                    await outStream.FlushAsync();
                }
            }
        }
Ejemplo n.º 27
0
		public WindowsIsolatedStorage(StorageFolder folder)
		{
			if (folder == null)
				throw new ArgumentNullException("folder");

			_folder = folder;
		}
Ejemplo n.º 28
0
        private async Task RegisterUnhandledErrorHandler()
        {
            logUploadFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("MyLogFile",
                CreationCollisionOption.OpenIfExists);

            CoreApplication.UnhandledErrorDetected += CoreApplication_UnhandledErrorDetected;
        }
Ejemplo n.º 29
0
        async void openFolder()
        {
            var folder = ApplicationData.Current.LocalFolder;
            newFolder = await folder.CreateFolderAsync("NewFolder", CreationCollisionOption.OpenIfExists);
            test1.Text = "Done";

        }
    public static async System.Threading.Tasks.Task <string> CacheFileAsync(string sourceFilePath)
    {
        string fileName = Path.GetFileName(sourceFilePath);

        Windows.Storage.StorageFile   sourceStorageFile  = Crosstales.FB.FileBrowserWSAImpl.LastOpenFile;
        Windows.Storage.StorageFolder cacheStorageFolder = Windows.Storage.ApplicationData.Current.LocalCacheFolder;
        var cacheStorageFile =
            await sourceStorageFile.CopyAsync(cacheStorageFolder, fileName, Windows.Storage.NameCollisionOption.ReplaceExisting);

        string cacheFilePath = cacheStorageFile.Path;

        return(cacheFilePath);
    }
Ejemplo n.º 31
0
    private async System.Threading.Tasks.Task <string> SaveImageFileAsync(string imageFileName, byte[] btImageContent, bool openIt)
    {
        Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        Windows.Storage.StorageFile   imageFile     = await storageFolder.CreateFileAsync(imageFileName,
                                                                                          Windows.Storage.CreationCollisionOption.ReplaceExisting);

        await Windows.Storage.FileIO.WriteBytesAsync(imageFile, btImageContent);

        if (openIt)
        {
            await Windows.System.Launcher.LaunchFileAsync(imageFile);
        }

        return(imageFile.Path);
    }
Ejemplo n.º 32
0
    async void LoadAllTasks()
    {
#if UNITY_WSA && !UNITY_EDITOR
        Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        Windows.Storage.StorageFile   file          = await storageFolder.CreateFileAsync(gameDataFileName,
                                                                                          Windows.Storage.CreationCollisionOption.OpenIfExists);

        string filePath = file.Path;
#else
        string filePath = Path.Combine(Application.streamingAssetsPath, gameDataFileName);
#endif


        if (File.Exists(filePath))
        {
            string dataAsJson;
            while (true)
            {
                dataAsJson = File.ReadAllText(filePath);
                if (dataAsJson.Length > 0)
                {
                    break;
                }
            }
            // Read the json from the file into a string

            // Pass the json to JsonUtility, and tell it to create a GameData object from it


            JObject obj = JObject.Parse(dataAsJson);

            JArray tasks = (JArray)obj["Tasks"];

            foreach (var task in tasks)
            {
                m_Dropdown.options.Add(new Dropdown.OptionData()
                {
                    text = task["Name"].ToString()
                });
            }
        }
        else
        {
            Debug.LogError("Cannot load task data!");
        }
    }
Ejemplo n.º 33
0
    public static async Task SerializeAsync <T>(T content, Windows.Storage.StorageFolder folder, string fileName, System.Threading.SemaphoreSlim semaphore)
    {
        await semaphore.WaitAsync();

        try
        {
            var f = await folder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

            using var s = (await f.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)).AsStream();
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            serializer.Serialize(s, content);
        }
        catch { }
        finally
        {
            semaphore.Release();
        }
    }
Ejemplo n.º 34
0
        //Save / Load
        internal async void LoadFile()
        {
            try
            {
                List <SaveDataSchema>         _data         = new List <SaveDataSchema>();
                Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                Windows.Storage.StorageFile   sampleFile    = await storageFolder.GetFileAsync("myconfig.json");

                //Reading Saved Data into String
                string json_str = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

                //Deserialize json and put it into a List
                _data          = JsonConvert.DeserializeObject <List <SaveDataSchema> >(json_str);
                _savedDataList = _data; //passing data to a global variable. (This list will hold all of the Deserialized Baddies)

                //Clear board BEFORE PROCEEDING
                ClearBoard();
                IsGameLoad = true;
                CreateBoard();
                SetButtonsOnLoad();
                _musicManager.PauseBgMusic();
                await _musicManager.PlayBackgroundMusicSound();

                isGameisLoaded = true;//-----------------------Set this flag to false to enable New keyEvent in Mainpage after load(otherwise goodie will freeze)

                loadedTimes++;
                if (loadedTimes > 1)
                {
                    IsloadedMorethanOnce = true;
                }
            }
            catch (Exception)
            {
                FileNotExistsMessage();
            }
        }
Ejemplo n.º 35
0
        private async void SpeechRecognitionFromMicrophone_ButtonClicked(object sender, RoutedEventArgs e)
        {
            // Creates an instance of a speech config with specified subscription key and service region.
            // Replace with your own subscription key and service region (e.g., "westus").
            var config = SpeechConfig.FromSubscription("1c514fb1fea2465a882f0fae12242cc0", "francecentral");

            config.SpeechRecognitionLanguage = "fr-FR";

            try
            {
                // Creates a speech recognizer using microphone as audio input.
                using (var recognizer = new SpeechRecognizer(config))
                {
                    // Starts speech recognition, and returns after a single utterance is recognized. The end of a
                    // single utterance is determined by listening for silence at the end or until a maximum of 15
                    // seconds of audio is processed.  The task returns the recognition text as result.
                    // Note: Since RecognizeOnceAsync() returns only a single utterance, it is suitable only for single
                    // shot recognition like command or query.
                    // For long-running multi-utterance recognition, use StartContinuousRecognitionAsync() instead.
                    var result = await recognizer.RecognizeOnceAsync().ConfigureAwait(false);

                    // Checks result.
                    StringBuilder sb = new StringBuilder();
                    if (result.Reason == ResultReason.RecognizedSpeech)
                    {
                        sb.AppendLine($"{result.Text}");
                    }
                    else if (result.Reason == ResultReason.NoMatch)
                    {
                        sb.AppendLine($"NOMATCH: Speech could not be recognized.");
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = CancellationDetails.FromResult(result);
                        sb.AppendLine($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            sb.AppendLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            sb.AppendLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}");
                            sb.AppendLine($"CANCELED: Did you update the subscription info?");
                        }
                    }

                    // Update the UI
                    NotifyUser(sb.ToString(), NotifyType.StatusMessage);

                    //Création de l'objet à séréaliser
                    string   texte    = sb.ToString();
                    Question question = new Question()
                    {
                        id    = "1234",
                        texte = sb.ToString(),
                    };
                    //Séréalisation de l'objet
                    string notjsonyet        = "'id':'123','texte':'" + texte + "'";
                    string jsonSerializedObj = JsonConvert.SerializeObject(question);

                    //Choix du local folder comme emplacement
                    //C:\Users\pauwe\AppData\Local\Packages\b6d47962-7028-4697-b1c3-c39fb3a25c97_npata57gt8602\LocalState\
                    //C:\Users\leays\AppData\Local\Packages\243E158E-1F25-44EF-90FC-68A410B06C6D_kqh4kznn2n4py\LocalState\
                    Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

                    //Création du fichier json contenant l'id de l'interlocuteur et son texte
                    Windows.Storage.StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.json",
                                                                                               Windows.Storage.CreationCollisionOption.ReplaceExisting);

                    //Ecriture dans le fichier json
                    await Windows.Storage.FileIO.WriteTextAsync(sampleFile, jsonSerializedObj);

                    //Envoi de la requête
                    await TryPostJsonAsync(notjsonyet);
                }
            }
            catch (Exception ex)
            {
                NotifyUser($"Enable Microphone First.\n {ex.ToString()}", NotifyType.ErrorMessage);
            }
        }
Ejemplo n.º 36
0
        public static string GetPath(string filename)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            return(storageFolder.Path + "\\" + CensorFilename(filename));
        }
Ejemplo n.º 37
0
        private async void btnBrowse_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            var folderPicker = new Windows.Storage.Pickers.FolderPicker();

            folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
            folderPicker.FileTypeFilter.Add("*");

            Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                // Application now has read/write access to all contents in the picked folder
                // (including other sub-folder contents)
                Windows.Storage.AccessCache.StorageApplicationPermissions.
                FutureAccessList.AddOrReplace("PickedFolderToken", folder);

                var item = ((Button)sender).Tag;
                switch (item)
                {
                case "1":
                {
                    localSettings.Values["DesktopLocation"] = folder.Name;
                    App.AppSettings.DesktopPath             = folder.Name;
                    break;
                }

                case "2":
                {
                    localSettings.Values["DownloadsLocation"] = folder.Name;
                    App.AppSettings.DownloadsPath             = folder.Name;
                    break;
                }

                case "3":
                {
                    localSettings.Values["DocumentsLocation"] = folder.Name;
                    App.AppSettings.DocumentsPath             = folder.Name;
                    break;
                }

                case "4":
                {
                    localSettings.Values["PicturesLocation"] = folder.Name;
                    App.AppSettings.PicturesPath             = folder.Name;
                    break;
                }

                case "5":
                {
                    localSettings.Values["MusicLocation"] = folder.Name;
                    App.AppSettings.MusicPath             = folder.Name;
                    break;
                }

                case "6":
                {
                    localSettings.Values["VideosLocation"] = folder.Name;
                    App.AppSettings.VideosPath             = folder.Name;
                    break;
                }

                case "7":
                {
                    localSettings.Values["OneDriveLocation"] = folder.Name;
                    App.AppSettings.OneDrivePath             = folder.Name;
                    break;
                }
                }
            }
        }
Ejemplo n.º 38
0
        //public string deviceName = "MikroKopter_BT"; // Specify the device name to be selected; You can find the device name from the webb under bluetooth

        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral
            //
            _deferral = taskInstance.GetDeferral();

            PowerManager.BatteryStatusChanged          += PowerManager_BatteryStatusChanged;
            PowerManager.PowerSupplyStatusChanged      += PowerManager_PowerSupplyStatusChanged;
            PowerManager.RemainingChargePercentChanged += PowerManager_RemainingChargePercentChanged;

            deviceId = await AzureIoTHub.TestHubConnection(false, "");

            DateTime d = DateTime.UtcNow;

            //RateSensor bs = new RateSensor();
            //bs.RateSensorInit();

            //await Task.Delay(1000);

            //bs.RateMonitorON();

            //mt = new MiotyTX();
            //mt.Init();
            //await Task.Delay(1000);

            long x = d.ToFileTime();

            if (deviceId != null)
            {
                await AzureIoTHub.SendDeviceToCloudMessageAsync("{\"pkey\":\"" + deviceId + "\", \"rkey\":\"" + x.ToString() + "\",\"status\":\"Device Restarted\"}");

                bool result = await AzureIoTHub.SendDeviceToCloudMessageAsync("Device Restarted");

                //InitAzureIotReceiver();
            }

            AzureIoTHub.counter++;

            // request access to vibration device
            //if (await VibrationDevice.RequestAccessAsync() != VibrationAccessStatus.Allowed)
            //{
            //    Debug.WriteLine("access to vibration device denied!!!!!!");
            //}

            //enable this to start periodic message to iot Hub
            this.timer = ThreadPoolTimer.CreateTimer(Timer_Tick, TimeSpan.FromSeconds(2));

            //this.fileReadTimer = ThreadPoolTimer.CreateTimer(FileReadTimer_Tick, TimeSpan.FromMilliseconds(900));

            try
            {
                await Task.Run(async() =>
                {
                    while (true)
                    {
                        string receivedMessage = null;

                        try
                        {
                            receivedMessage = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();
                            AzureIoTHub.counter++;
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("******ERROR RECEIVER: " + ex.Message);
                        }


                        if (receivedMessage == null)
                        {
                            continue;
                        }
                        Debug.WriteLine("Received message:" + receivedMessage);

                        JsonObject j = null;
                        try
                        {
                            j = JsonObject.Parse(receivedMessage);
                        }
                        catch
                        {
                            Debug.WriteLine(" error");
                            continue;
                        }

                        try
                        {
                            if (j.Keys.Contains("msg"))
                            {
                                string msg = j.GetNamedString("msg");
                                AzureIoTHub.counter++;
                                MessageListItem m = new MessageListItem();
                                m.message         = msg;
                                AzureIoTHub.msgList.Add(m);

                                Windows.Storage.StorageFolder storageFolder = Windows.Storage.KnownFolders.PicturesLibrary;
                                Windows.Storage.StorageFile msgFile         = await storageFolder.CreateFileAsync("message.txt", Windows.Storage.CreationCollisionOption.GenerateUniqueName);
                                await Windows.Storage.FileIO.AppendTextAsync(msgFile, msg);
                            }
                            if (j.Keys.Contains("cmd"))
                            {
                                string cmd = j.GetNamedString("cmd");
                                if (cmd == "info")
                                {
                                    await UpdateBatteryInfo();
                                }
                                if (cmd == "wake")
                                {
                                    if (ShutdownManager.IsPowerStateSupported(PowerState.ConnectedStandby))
                                    {
                                        ShutdownManager.EnterPowerState(PowerState.ConnectedStandby, TimeSpan.FromSeconds(1));
                                        //ShutdownManager.EnterPowerState(PowerState.SleepS3, TimeSpan.FromSeconds(15));
                                    }
                                }
                                if (cmd == "vibra")
                                {
                                    //try
                                    //{
                                    //    VibrationDevice VibrationDevice = await VibrationDevice.GetDefaultAsync();
                                    //    SimpleHapticsControllerFeedback BuzzFeedback = null;
                                    //    foreach (var f in VibrationDevice.SimpleHapticsController.SupportedFeedback)
                                    //    {
                                    //        if (f.Waveform == KnownSimpleHapticsControllerWaveforms.BuzzContinuous)
                                    //            BuzzFeedback = f;
                                    //    }
                                    //    if (BuzzFeedback != null)
                                    //    {
                                    //        VibrationDevice.SimpleHapticsController.SendHapticFeedbackForDuration(BuzzFeedback, 1, TimeSpan.FromMilliseconds(200));
                                    //    }
                                    //}
                                    //catch (Exception ex)
                                    //{
                                    //}
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                });
            }
            catch (Exception ex)
            {
            }


            //
            // Once the asynchronous method(s) are done, close the deferral.
            //
            //_deferral.Complete();
        }
Ejemplo n.º 39
0
        private async Task ConfigureJumpList()
        {
            Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            // using the favorites class
            // TODO: change name of "favorites" class to something else
            var jumpList = await Windows.UI.StartScreen.JumpList.LoadCurrentAsync();

            jumpList.Items.Clear();
            // Disable the system-managed jump list group.
            jumpList.SystemGroupKind = Windows.UI.StartScreen.JumpListSystemGroupKind.None;

            try
            {
                StorageFile sampleFile = await localFolder.GetFileAsync("QuickPinWeb.json");

                var JSONData = await FileIO.ReadTextAsync(sampleFile);

                FavouritesClass FavouritesListJSON = JsonConvert.DeserializeObject <FavouritesClass>(JSONData);
                foreach (var item in FavouritesListJSON.Websites)
                {
                    var itemj = JumpListItem.CreateWithArguments("item.UrlJSON.ToString()", "item.HeaderJSON.ToString()");

                    itemj.Description = "item.UrlJSON";

                    itemj.GroupName = "Quick pinned: ";


                    itemj.Logo = new Uri("ms-appx:///Assets/SmallTile.scale-100.png");



                    jumpList.Items.Add(itemj);
                }
            }
            catch
            {
                var           JSONData = "e";
                string        filepath = @"Assets\QuickPinWeb.json";
                StorageFolder folder   = Windows.ApplicationModel.Package.Current.InstalledLocation;
                StorageFile   file     = await folder.GetFileAsync(filepath);

                JSONData = await Windows.Storage.FileIO.ReadTextAsync(file);

                //  StorageFile sfile = await localFolder.CreateFileAsync("QuickPinWeb.json", CreationCollisionOption.ReplaceExisting);
                //  await FileIO.WriteTextAsync(sfile, JSONData);
                StorageFile sampleFile = await localFolder.CreateFileAsync("QuickPinWeb.json", CreationCollisionOption.ReplaceExisting);

                await FileIO.WriteTextAsync(sampleFile, JSONData);

                FavouritesClass FavouritesListJSON = JsonConvert.DeserializeObject <FavouritesClass>(JSONData);
                foreach (var item in FavouritesListJSON.Websites)
                {
                    var itemj = JumpListItem.CreateWithArguments(item.UrlJSON.ToString(), item.HeaderJSON.ToString());

                    itemj.Description = "item.UrlJSON";

                    itemj.GroupName = "Quick pinned: ";

                    itemj.Logo = new Uri("ms-appx:///Assets/SmallTile.scale-100.png");



                    jumpList.Items.Add(itemj);
                }
                await jumpList.SaveAsync();
            }
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Render ObjectDetector skill results
        /// </summary>
        /// <param name="frame"></param>
        /// <param name="objectDetections"></param>
        /// <returns></returns>
        private async Task DisplayFrameAndResultAsync(VideoFrame frame, int CCTVIndex)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                try
                {
                    SoftwareBitmap savedBmp = null;
                    if (frame.SoftwareBitmap != null)
                    {
                        await m_processedBitmapSource[CCTVIndex].SetBitmapAsync(frame.SoftwareBitmap);
                        savedBmp = frame.SoftwareBitmap;
                    }
                    else
                    {
                        var bitmap = await SoftwareBitmap.CreateCopyFromSurfaceAsync(frame.Direct3DSurface, BitmapAlphaMode.Ignore);
                        await m_processedBitmapSource[CCTVIndex].SetBitmapAsync(bitmap);
                        savedBmp = bitmap;
                    }

                    // Retrieve and filter results if requested
                    IReadOnlyList <ObjectDetectorResult> objectDetections = m_binding.DetectedObjects;
                    if (m_objectKinds?.Count > 0)
                    {
                        objectDetections = objectDetections.Where(det => m_objectKinds.Contains(det.Kind)).ToList();
                    }
                    if (objectDetections != null)
                    {
                        // Update displayed results
                        m_bboxRenderer[CCTVIndex].Render(objectDetections);
                        bool PersonDetected = false;
                        int PersonCount     = 0;
                        var rects           = new List <Rect>();
                        foreach (var obj in objectDetections)
                        {
                            if (obj.Kind.ToString().ToLower() == "person")
                            {
                                PersonCount++;
                                PersonDetected = true;
                                rects.Add(obj.Rect);
                            }
                        }
                        if (PersonDetected)
                        {
                            bool KeepDistance = false;
                            if ((bool)ChkSocialDistancing.IsChecked)
                            {
                                //make sure there is more than 1 person
                                if (rects.Count > 1)
                                {
                                    var res = SocialDistanceHelpers.Detect(rects.ToArray());
                                    if (res.Result)
                                    {
                                        KeepDistance = true;
                                        m_bboxRenderer[CCTVIndex].DistanceLineRender(res.Lines);
                                        await speech.Read($"Please keep distance in {DataConfig.RoomName[CCTVIndex]}");
                                    }
                                }
                                else
                                {
                                    m_bboxRenderer[CCTVIndex].ClearLineDistance();
                                }
                            }
                            else
                            {
                                m_bboxRenderer[CCTVIndex].ClearLineDistance();
                            }
                            var msg = $"I saw {PersonCount} person in {DataConfig.RoomName[CCTVIndex]}";
                            if ((bool)ChkMode.IsChecked)
                            {
                                PlaySound(Sounds[Rnd.Next(0, Sounds.Count - 1)]);
                            }
                            else if (!KeepDistance)
                            {
                                await speech.Read(msg);
                            }
                            if ((bool)ChkPatrol.IsChecked)
                            {
                                await NotificationService.SendMail("Person Detected in BMSpace", msg, DataConfig.MailTo, DataConfig.MailFrom);
                                await NotificationService.SendSms(DataConfig.SmsTo, msg);
                            }
                            bool IsFaceDetected = false;
                            if ((bool)ChkDetectMask.IsChecked)
                            {
                                SoftwareBitmap softwareBitmapInput = frame.SoftwareBitmap;
                                // Retrieve a SoftwareBitmap to run face detection
                                if (softwareBitmapInput == null)
                                {
                                    if (frame.Direct3DSurface == null)
                                    {
                                        throw (new ArgumentNullException("An invalid input frame has been bound"));
                                    }
                                    softwareBitmapInput = await SoftwareBitmap.CreateCopyFromSurfaceAsync(frame.Direct3DSurface);
                                }
                                // We need to convert the image into a format that's compatible with FaceDetector.
                                // Gray8 should be a good type but verify it against FaceDetector’s supported formats.
                                const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Gray8;
                                if (FaceDetector.IsBitmapPixelFormatSupported(InputPixelFormat))
                                {
                                    using (var detectorInput = SoftwareBitmap.Convert(softwareBitmapInput, InputPixelFormat))
                                    {
                                        // Run face detection and retrieve face detection result
                                        var faceDetectionResult = await m_faceDetector.DetectFacesAsync(detectorInput);

                                        // If a face is found, update face rectangle feature
                                        if (faceDetectionResult.Count > 0)
                                        {
                                            IsFaceDetected = true;
                                            // Retrieve the face bound and enlarge it by a factor of 1.5x while also ensuring clamping to frame dimensions
                                            BitmapBounds faceBound = faceDetectionResult[0].FaceBox;
                                            var additionalOffset   = faceBound.Width / 2;
                                            faceBound.X            = Math.Max(0, faceBound.X - additionalOffset);
                                            faceBound.Y            = Math.Max(0, faceBound.Y - additionalOffset);
                                            faceBound.Width        = (uint)Math.Min(faceBound.Width + 2 * additionalOffset, softwareBitmapInput.PixelWidth - faceBound.X);
                                            faceBound.Height       = (uint)Math.Min(faceBound.Height + 2 * additionalOffset, softwareBitmapInput.PixelHeight - faceBound.Y);

                                            var maskdetect  = await MaskDetect.PredictImageAsync(frame);
                                            var noMaskCount = maskdetect.Where(x => x.TagName == "no-mask").Count();
                                            if (noMaskCount > 0)
                                            {
                                                if (!KeepDistance)
                                                {
                                                    await speech.Read($"please wear a face mask in {DataConfig.RoomName[CCTVIndex]}");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (!IsFaceDetected)
                            {
                                m_bboxRenderer[CCTVIndex].ClearMaskLabel();
                            }
                            //save to picture libs

                            /*
                             * String path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                             * path += "\\CCTV";
                             * if (!Directory.Exists(path))
                             * {
                             *  Directory.CreateDirectory(path);
                             * }*/
                            var TS = DateTime.Now - LastSaved[CCTVIndex];
                            if (savedBmp != null && TS.TotalSeconds > DataConfig.CaptureIntervalSecs && (bool)ChkCapture.IsChecked)
                            {
                                var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
                                Windows.Storage.StorageFolder rootFolder    = myPictures.SaveFolder;
                                Windows.Storage.StorageFolder storageFolder = rootFolder;
                                var folderName = "cctv";
                                try
                                {
                                    storageFolder = await rootFolder.GetFolderAsync(folderName);
                                }
                                catch
                                {
                                    storageFolder = await rootFolder.CreateFolderAsync(folderName);
                                }
                                //if (Directory.Exists($"{rootFolder.Path}\\{folderName}"))
                                //else
                                // Create sample file; replace if exists.
                                //Windows.Storage.StorageFolder storageFolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(path);
                                Windows.Storage.StorageFile sampleFile =
                                    await storageFolder.CreateFileAsync($"cctv_{DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss")}_{CCTVIndex}.jpg",
                                                                        Windows.Storage.CreationCollisionOption.ReplaceExisting);
                                ImageHelpers.SaveSoftwareBitmapToFile(savedBmp, sampleFile);
                                LastSaved[CCTVIndex] = DateTime.Now;
                            }
                        }
                    }

                    // Update the displayed performance text
                    StatusLbl.Text = $"bind: {m_bindTime.ToString("F2")}ms, eval: {m_evalTime.ToString("F2")}ms";
                }
                catch (TaskCanceledException)
                {
                    // no-op: we expect this exception when we change media sources
                    // and can safely ignore/continue
                }
                catch (Exception ex)
                {
                    NotifyUser($"Exception while rendering results: {ex.Message}");
                }
            });
        }
Ejemplo n.º 41
0
        public static IAsyncOperation <StorageFile> CopyOrReplaceAsync(this StorageFile storageFile, StorageFolder destinationFolder)
        {
            if (storageFile == null)
            {
                throw new ArgumentNullException(nameof(storageFile));
            }

            if (destinationFolder == null)
            {
                throw new ArgumentNullException(nameof(destinationFolder));
            }

            return(storageFile.CopyAsync(destinationFolder, storageFile.Name, NameCollisionOption.ReplaceExisting));
        }
Ejemplo n.º 42
0
        }//Go_Click end

        // Timer tick for increment to count down from set number and print to screen. (async for media)
        private async void Timer_Tick(object sender, object e)
        {
            if (increment > 0)
            {
                increment--;
                timertext.Text = "    " + increment.ToString();
            }

            // game over if timer ticks to 0.
            if (increment == 0)
            {
                // reset variables and texts and print out final score and game over.
                Done.IsEnabled = false;
                Go.IsEnabled   = true;
                timer.Stop();
                Go.Content             = "Try Again";
                gameover.Text          = "   GAME OVER";
                gameover.Foreground    = new SolidColorBrush(Colors.Red);
                finalScore1.Text       = "SCORE: " + score.ToString();
                finalScore1.Foreground = new SolidColorBrush(Colors.Red);
                answerBox.IsEnabled    = false;
                correctCounter         = 0;


                //if statement to get the answer and to print out the correct answer to the user.

                if ((firstSymbol.Text == "+") && (secondSymbol.Text == "+"))
                {
                    answer = num1 + num2 + num3;
                }
                else if ((firstSymbol.Text == "+") && (secondSymbol.Text == "*"))
                {
                    answer = num1 + (num2 * num3);
                }
                else if ((firstSymbol.Text == "*") && (secondSymbol.Text == "+"))
                {
                    answer = (num1 * num2) + num3;
                }
                else if ((firstSymbol.Text == "*") && (secondSymbol.Text == "*"))
                {
                    answer = num1 * num2 * num3;
                }
                else if ((firstSymbol.Text == "*") && (secondSymbol.Text == "-"))
                {
                    answer = (num1 * num2) - num3;
                }
                else if ((firstSymbol.Text == "+") && (secondSymbol.Text == "-"))
                {
                    answer = num1 + num2 - num3;
                }
                else if ((firstSymbol.Text == "-") && (secondSymbol.Text == "*"))
                {
                    answer = num1 - (num2 * num3);
                }
                else if ((firstSymbol.Text == "-") && (secondSymbol.Text == "+"))
                {
                    answer = num1 - num2 + num3;
                }
                else
                {
                    answer = (num1 - num2 - num3);
                }

                Done.Content  = ("Correct Answer = " + answer.ToString());
                Done.FontSize = 18;

                // play game over sound and make sure autoplay doesnt occur
                Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets");

                Windows.Storage.StorageFile file = await folder.GetFileAsync("game-over.mp3");

                gameoverMp3.AutoPlay = false;
                gameoverMp3.Source   = MediaSource.CreateFromStorageFile(file);
                gameoverMp3.Play();

                //use try catch method to store highscore into local settings
                try
                {
                    int temp = Convert.ToInt32(localSettings.Values["hardHighScore"]);
                    if (temp < score)
                    {
                        localSettings.Values["hardHighScore"] = score.ToString();
                    }
                }
                catch
                {
                    // doesn't exist, just set the value
                    localSettings.Values["hardHighScore"] = score.ToString();
                }

                score       = 0;
                score1.Text = "";
            }
        }//timer_tick end
Ejemplo n.º 43
0
        public static async Task <ObservableCollection <WeaponSkin> > GetSkins()
        {
            //Collection of the skins
            ObservableCollection <WeaponSkin> SkinCollection = new ObservableCollection <WeaponSkin>();

            //CSGO-File where the URIs are stored in
            StorageFile inputFile = await GetSkinsFileAsync();

            //Saves the text of the inputFile in a string for further editing
            string text = await Windows.Storage.FileIO.ReadTextAsync(inputFile);

            //erases all entries in the text before the first url
            if (!text.StartsWith("weapon"))
            {
                text = text.Substring(text.IndexOf("weapon"));
            }

            //downloading the pictures from the different urls
            while (text.Length != 0)
            {
                WeaponSkin skin = new WeaponSkin();
                skin.Id  = text.Substring(0, text.IndexOf("="));
                text     = text.Substring(text.IndexOf("=") + 1);
                skin.Url = text.Substring(0, text.IndexOf("\r\n"));
                text     = text.Substring(text.IndexOf("\n") + 1);
                try
                {
                    //downloading the pictures from the urls
                    Uri sourceUri = new Uri("ms-appx:///Images/WeaponSkins/defaultSkin.png");

                    string destination = "ms-appx:///Images/WeaponSkins/" + skin.Id + ".png";

                    //getting the destination Folder for the pictures, by receiving the parent folder from a default file
                    StorageFile defaultFile = await StorageFile.GetFileFromApplicationUriAsync(sourceUri);

                    Windows.Storage.StorageFolder storageFolder = await defaultFile.GetParentAsync();

                    //creating the .png file for the picture
                    Windows.Storage.StorageFile destinationFile = await storageFolder.CreateFileAsync(skin.Id + ".png", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                    //StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName);

                    //downloading the picture from the url
                    BackgroundDownloader downloader = new BackgroundDownloader();
                    DownloadOperation    download   = downloader.CreateDownload(new Uri(skin.Url), destinationFile);

                    // Attach progress and completion handlers.
                    var result = download.StartAsync();

                    //assign the downloaded picture to the skin
                    skin.Icon = destinationFile.Path;
                }
                catch (Exception ex)
                {
                    //LogException("Download Error", ex);
                }
                //adding the skin to the collection
                SkinCollection.Add(skin);
            }
            return(SkinCollection);
        }
        /// <summary>
        /// Сохраняет развертку в локальную папку
        /// </summary>
        /// <param name="data"></param>
        /// <param name="Tail"></param>
        /// <param name="time"></param>
        /// <param name="nameFile"></param>
        /// <returns></returns>
        public async Task saveAsync(int[,] data, int[,] Tail, string time, string nameFile, bool Taill)
        {
            string cul          = "en-US";
            var    folderPicker = new Windows.Storage.Pickers.FolderPicker();

            folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
            folderPicker.FileTypeFilter.Add("*");

            Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                // Application now has read/write access to all contents in the picked folder
                // (including other sub-folder contents)
                Windows.Storage.AccessCache.StorageApplicationPermissions.
                FutureAccessList.AddOrReplace("PickedFolderToken", folder);
                StorageFolder storageFolderRazvertka = await folder.CreateFolderAsync("Развертка", CreationCollisionOption.OpenIfExists);

                StorageFile sampleFile = await storageFolderRazvertka.CreateFileAsync(nameFile + time + ".txt", CreationCollisionOption.ReplaceExisting);

                var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        string s = "i" + "\t" + "Ch1" + "\t" + "Ch2" + "\t" + "Ch3" + "\t" + "Ch4" + "\t" + "Ch5" + "\t" + "Ch6" + "\t" + "Ch7" + "\t" + "Ch8" + "\t" + "Ch9" + "\t" + "Ch10" + "\t" + "Ch11" + "\t" + "Ch12" + "\r\n";
                        for (int i = 0; i < 1024; i++)
                        {
                            s = s + (i + 1).ToString() + "\t";
                            for (int j = 0; j < 12; j++)
                            {
                                s = s + data[j, i] + "\t";
                            }
                            if (i < 1023)
                            {
                                s = s + "\r\n";
                            }
                            else
                            {
                            }
                        }
                        dataWriter.WriteString(s);
                        s = null;
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.
                if (Taill)
                {
                    // storageFolderRazvertka = await storageFolderRazvertka.CreateFolderAsync("Развертка", CreationCollisionOption.OpenIfExists);
                    sampleFile = await storageFolderRazvertka.CreateFileAsync(nameFile + time + "Хвост" + ".txt", CreationCollisionOption.ReplaceExisting);

                    stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                    using (var outputStream = stream.GetOutputStreamAt(0))
                    {
                        using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                        {
                            string s = "i" + "\t" + "Ch1" + "\t" + "Ch2" + "\t" + "Ch3" + "\t" + "Ch4" + "\t" + "Ch5" + "\t" + "Ch6" + "\t" + "Ch7" + "\t" + "Ch8" + "\t" + "Ch9" + "\t" + "Ch10" + "\t" + "Ch11" + "\t" + "Ch12" + "\r\n";
                            for (int i = 0; i < 20000; i++)
                            {
                                s = s + (i + 1).ToString() + "\t";
                                for (int j = 0; j < 12; j++)
                                {
                                    s = s + Tail[j, i] + "\t";
                                }
                                if (i < 19999)
                                {
                                    s = s + "\r\n";
                                }
                                else
                                {
                                }

                                dataWriter.WriteString(s);
                                s = null;
                            }

                            await dataWriter.StoreAsync();

                            await outputStream.FlushAsync();
                        }
                    }
                    stream.Dispose();
                }
            }
        }
        public async Task SetupSounds()
        {
            //Load All Sounds

            //probably could do this programatically but lol

            Debug.WriteLine("Setup Sounds Started");

            try
            {
                snd_Chord.AutoPlay      = false;
                snd_HaHa.AutoPlay       = false;
                snd_LosingHorn.AutoPlay = false;
                snd_SlotPull.AutoPlay   = false;
                snd_Win95.AutoPlay      = false;
                snd_MarioFail.AutoPlay  = false;
                snd_SadTrom.AutoPlay    = false;

                soundFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");



                soundFile_Chord = await soundFolder.GetFileAsync("Sounds\\chord.wav");

                var soundStream_Chord = await soundFile_Chord.OpenAsync(Windows.Storage.FileAccessMode.Read);

                snd_Chord.SetSource(soundStream_Chord, soundFile_Chord.ContentType);
                snd_Chord.Stop();
                Debug.WriteLine("chord Loaded");


                soundFile_HaHa = await soundFolder.GetFileAsync("Sounds\\haha.wav");

                var soundStream_HaHa = await soundFile_HaHa.OpenAsync(Windows.Storage.FileAccessMode.Read);

                snd_HaHa.SetSource(soundStream_HaHa, soundFile_HaHa.ContentType);
                snd_HaHa.Stop();
                Debug.WriteLine("HAha Loaded");

                soundFile_LosingHorn = await soundFolder.GetFileAsync("Sounds\\LosingHorn.wav");

                var soundStream_LosingHorn = await soundFile_LosingHorn.OpenAsync(Windows.Storage.FileAccessMode.Read);

                snd_LosingHorn.SetSource(soundStream_LosingHorn, soundFile_LosingHorn.ContentType);
                snd_LosingHorn.Stop();
                Debug.WriteLine("Losing Horn Loaded");


                soundFile_SlotPull = await soundFolder.GetFileAsync("Sounds\\SlotPull.wav");

                var soundStream_SlotPull = await soundFile_SlotPull.OpenAsync(Windows.Storage.FileAccessMode.Read);

                snd_SlotPull.SetSource(soundStream_SlotPull, soundFile_SlotPull.ContentType);
                snd_SlotPull.Stop();
                Debug.WriteLine("SLot Pull Loaded");


                soundFile_Win95 = await soundFolder.GetFileAsync("Sounds\\Win95.wav");

                var soundStream_Win95 = await soundFile_Win95.OpenAsync(Windows.Storage.FileAccessMode.Read);

                snd_Win95.SetSource(soundStream_Win95, soundFile_Win95.ContentType);
                snd_Win95.Stop();
                Debug.WriteLine("WIn 95 Loaded");


                soundFile_MarioFail = await soundFolder.GetFileAsync("Sounds\\mariofail.wav");

                var soundStream_MarioFail = await soundFile_MarioFail.OpenAsync(Windows.Storage.FileAccessMode.Read);

                snd_MarioFail.SetSource(soundStream_MarioFail, soundFile_MarioFail.ContentType);
                snd_MarioFail.Stop();
                Debug.WriteLine("Mario Fail Loaded");


                soundFile_SadTrom = await soundFolder.GetFileAsync("Sounds\\SadTrom.wav");

                var soundStream_SadTrom = await soundFile_SadTrom.OpenAsync(Windows.Storage.FileAccessMode.Read);

                snd_SadTrom.SetSource(soundStream_SadTrom, soundFile_SadTrom.ContentType);
                snd_SadTrom.Stop();
                Debug.WriteLine("Sad Trombone Loaded");


                Debug.WriteLine("Setup Sounds Completed");
            }

            catch (Exception e)
            {
                Debug.WriteLine("{0} Exception caught." + e.ToString() + " ---");
            }
        }
Ejemplo n.º 46
0
        private async void AppBarButton(object sender, RoutedEventArgs e)
        {
            var folderPicker = new Windows.Storage.Pickers.FolderPicker();

            folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
            folderPicker.FileTypeFilter.Add("*");

            Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                if (DataColec.Count != 0)
                {
                    using (StreamWriter writer =
                               new StreamWriter(await folder.OpenStreamForWriteAsync(
                                                    "SigLine" + "." + "txt", CreationCollisionOption.GenerateUniqueName)))
                    {
                        string sSob = "DateTime" + "\t" + "D1" + "\t" + "D2" + "\t" + "D3" + "\t" + "D4" + "\t" + "D5" + "\t" + "D6" + "\t" + "D7"
                                      + "\t" + "D8" + "\t" + "D9" + "\t" + "D10" + "\t" + "D11" + "\t" + "D12";


                        await writer.WriteLineAsync(sSob);

                        foreach (SigLine sob in DataColec)
                        {
                            string Sob = sob.dateTime.ToString() + "\t" + sob.mNullLine[0].ToString() + "\t" + sob.mNullLine[1].ToString() + "\t" +
                                         sob.mNullLine[2].ToString() + "\t" + sob.mNullLine[3].ToString() + "\t" + sob.mNullLine[4].ToString() + "\t" + sob.mNullLine[5].ToString() + "\t" + sob.mNullLine[6].ToString() + "\t" + sob.mNullLine[7].ToString() +
                                         "\t" + sob.mNullLine[8].ToString() + "\t" + sob.mNullLine[9].ToString() + "\t" + sob.mNullLine[10].ToString() + "\t" + sob.mNullLine[11].ToString();
                            await writer.WriteLineAsync(Sob);
                        }
                    }
                }
                if (DataColecN.Count != 0)
                {
                    using (StreamWriter writer =
                               new StreamWriter(await folder.OpenStreamForWriteAsync(
                                                    "РаспределениеSigLine" + "." + "txt", CreationCollisionOption.GenerateUniqueName)))
                    {
                        string sSob = "Код АЦП" + "D1" + "\t" + "D2" + "\t" + "D3" + "\t" + "D4" + "\t" + "D5" + "\t" + "D6" + "\t" + "D7"
                                      + "\t" + "D8" + "\t" + "D9" + "\t" + "D10" + "\t" + "D11" + "\t" + "D12";


                        await writer.WriteLineAsync(sSob);

                        foreach (ClassRasSig sob in DataColecN)
                        {
                            string Sob = sob.znacRas.ToString() + "\t" + sob.MNullLine[0].ToString() + "\t" + sob.MNullLine[1].ToString() + "\t" +
                                         sob.MNullLine[2].ToString() + "\t" + sob.MNullLine[3].ToString() + "\t" + sob.MNullLine[4].ToString() + "\t" + sob.MNullLine[5].ToString() + "\t" + sob.MNullLine[6].ToString() + "\t" + sob.MNullLine[7].ToString() +
                                         "\t" + sob.MNullLine[8].ToString() + "\t" + sob.MNullLine[9].ToString() + "\t" + sob.MNullLine[10].ToString() + "\t" + sob.MNullLine[11].ToString();
                            await writer.WriteLineAsync(Sob);
                        }
                    }
                }

                MessageDialog messageDialog = new MessageDialog("Статистика нулевых линий сохранена сохранен");
                await messageDialog.ShowAsync();
            }
            else
            {
            }
        }
Ejemplo n.º 47
0
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            CardNumber.Background  = new SolidColorBrush(Colors.White);
            SecurityNum.Background = new SolidColorBrush(Colors.White);

            _adress  = Adress.Text;
            _city    = City.Text;
            _country = Country.Text;

            try
            {
                if (CardNumber.Text.Length != 16)
                {
                    CardNumber.Background = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    _cardNumber = Convert.ToInt64(CardNumber.Text);
                }
            }
            catch
            {
                CardNumber.Background = new SolidColorBrush(Colors.Red);
            }

            _expiryDate = ExpiryDate.Date.ToString("d");

            try
            {
                if (SecurityNum.Text.Length != 3)
                {
                    SecurityNum.Background = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    _securityNumber = Convert.ToInt16(SecurityNum.Text);
                }
            }
            catch
            {
                SecurityNum.Background = new SolidColorBrush(Colors.Red);
            }

            if (SecurityNum.Text.Length == 3 && CardNumber.Text.Length == 16)
            {
                try
                {
                    Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                    Windows.Storage.StorageFile   sampleFile    = await storageFolder.CreateFileAsync(_email, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                    StorageFolder localFolder = ApplicationData.Current.LocalFolder;

                    var files = await localFolder.GetFilesAsync();

                    foreach (StorageFile storageFile in files)
                    {
                        if (storageFile.Name == _email)
                        {
                            var newFileContent = "--- Adress: --- \r\n" + _adress + "\r\n" + _city + "\r\n" + _country + "\r\n" + "--- Creditcard Information: ---- \r\n" + _cardNumber + "\r\n" + _expiryDate + "\r\n" + _securityNumber;
                            File.WriteAllText(storageFile.Path, newFileContent);

                            Adress.Text  = "";
                            City.Text    = "";
                            Country.Text = "";

                            CardNumber.Text  = "";
                            SecurityNum.Text = "";

                            MessageDialog message = new MessageDialog("Your data was saved!");
                            await message.ShowAsync();
                        }
                    }
                }
                catch
                {
                    StorageFolder localFolder = ApplicationData.Current.LocalFolder;

                    var files = await localFolder.GetFilesAsync();

                    foreach (StorageFile storageFile in files)
                    {
                        if (storageFile.Name == "Users.txt")
                        {
                            var newFileContent = "--- Adress: --- \r\n" + _adress + "\r\n" + _city + "\r\n" + _country + "\r\n" + "--- Creditcard Information: ---- \r\n" + _cardNumber + "\r\n" + _expiryDate + "\r\n" + _securityNumber;
                            File.WriteAllText(storageFile.Path, newFileContent);

                            Adress.Text  = "";
                            City.Text    = "";
                            Country.Text = "";

                            CardNumber.Text  = "";
                            SecurityNum.Text = "";

                            MessageDialog message = new MessageDialog("Your data was saved!");
                            await message.ShowAsync();
                        }
                    }
                }
            }
        }
Ejemplo n.º 48
0
        private async Task <bool> GetShopCartInfo()
        {
            try
            {
                Windows.Storage.StorageFolder storageFolder           = ApplicationData.Current.LocalFolder;
                Windows.Storage.StorageFile   shoppingCartStorageFile = await storageFolder.GetFileAsync("ShoppingCart.xml");

                //string rootPath = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
                //rootPath = rootPath + @"\Data";
                //StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(rootPath);
                //Windows.Storage.StorageFile shoppingCartStorageFile = await folder.GetFileAsync("ShoppingCart.xml");
                XmlDocument doc = await Windows.Data.Xml.Dom.XmlDocument.LoadFromFileAsync(shoppingCartStorageFile);

                IXmlNode root = null;
                foreach (var item in doc.ChildNodes)
                {
                    if (item.NodeName.Equals("goods"))
                    {
                        root = item;
                        break;
                    }
                }
                int goodsCount = 0;
                if (null != root)
                {
                    foreach (var goods in root.ChildNodes)
                    {
                        if (goods.NodeName.Equals("item"))
                        {
                            string      imgUrl      = goods.SelectSingleNode("img").InnerText;
                            string      singlePrice = goods.SelectSingleNode("price").InnerText;
                            string      name        = goods.SelectSingleNode("productName").InnerText;
                            string      count       = goods.SelectSingleNode("count").InnerText;
                            string      imagename   = goods.SelectSingleNode("imageName").InnerText;
                            GoodsInfo   info        = new GoodsInfo();
                            StorageFile file        = await StorageFile.GetFileFromPathAsync(imgUrl);

                            using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                            {
                                BitmapImage image = new BitmapImage();
                                image.SetSource(fileStream);
                                info.img = image;
                            }
                            info.name      = name;
                            info.price     = singlePrice;
                            info.count     = Convert.ToInt32(count);
                            info.imageName = imagename;
                            info.imgUri    = imgUrl;
                            goodsList.Add(info); goodsCount += Convert.ToInt32(count);
                        }
                    }
                }
                if (goodsCount > 0)
                {
                    shopcartGoodsNumber.Text       = Convert.ToString(goodsCount);
                    shopcartGoodsNumber.Visibility = Visibility.Visible;
                    shopcartEllipse.Visibility     = Visibility.Visible;
                }
                else
                {
                    shopcartGoodsNumber.Text       = "0";
                    shopcartGoodsNumber.Visibility = Visibility.Collapsed;
                    shopcartEllipse.Visibility     = Visibility.Collapsed;
                }
                return(true);
            }
            catch (Exception e)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(e.Message);
#endif
                return(false);
            }
        }
Ejemplo n.º 49
0
        private void submit_Click(object sender, RoutedEventArgs e)
        {
            double windowWidth;
            double windowHeight;

            if (Double.TryParse(inputWidth.Text, out windowWidth))
            {
                bool isValid = ValidateWindowWidth(windowWidth);
                if (!isValid)
                {
                    windowWidth     = 0;
                    inputWidth.Text = "";
                    widthError.Text = "Width must be between " + MINWIDTH + " and " + MAXWIDTH + ".";
                }
                else
                {
                    widthError.Text = ".";
                }
            }
            else
            {
                windowWidth     = 0;
                inputWidth.Text = "";
                widthError.Text = "Width must be a number.";
            }

            if (Double.TryParse(inputHeight.Text, out windowHeight))
            {
                bool isValid = ValidateWindowHeight(windowHeight);
                if (!isValid)
                {
                    windowHeight     = 0;
                    inputHeight.Text = "";
                    heightError.Text = "Height must be between " + MINHEIGHT + " and " + MAXHEIGHT + ".";
                }
                else
                {
                    heightError.Text = "";
                }
            }
            else
            {
                windowHeight     = 0;
                inputHeight.Text = "";
                heightError.Text = "Height must be a number.";
            }

            if (windowQuantity == 0)
            {
                quantityError.Text = "Quantity must be between 1 and 3";
                windowQuantity     = 0;
            }
            else
            {
                quantityError.Text = "";
            }

            if (windowTintColor == "" || windowTintColor == null)
            {
                tintError.Text  = "Pick a tint.";
                windowTintColor = "";
            }
            else
            {
                tintError.Text = "";
            }

            if (windowWidth != 0 && windowHeight != 0 && windowQuantity != 0 && windowTintColor != "")
            {
                double glassArea  = CalcGlassArea(windowWidth, windowHeight, windowQuantity);
                double woodLength = CalcWoodLength(windowWidth, windowHeight, windowQuantity);

                WindowBuild windowBuild = new WindowBuild(windowWidth, windowHeight, windowTintColor, windowQuantity);

                Windows.Storage.ApplicationDataContainer localSettings =
                    Windows.Storage.ApplicationData.Current.LocalSettings;
                Windows.Storage.StorageFolder localFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;

                localSettings.Values["windowWidth"]     = windowWidth;
                localSettings.Values["windowHeight"]    = windowHeight;
                localSettings.Values["windowTintColor"] = windowTintColor;
                localSettings.Values["windowQuantity"]  = windowQuantity;
                localSettings.Values["woodLength"]      = woodLength;
                localSettings.Values["glassArea"]       = glassArea;

                Frame.Navigate(typeof(Results));
            }
            else
            {
            }
        }
Ejemplo n.º 50
0
        }//timer_tick end

        //function for when done button is click
        public async void Done_Click(object sender, RoutedEventArgs e)
        {
            //reset text and variables
            Done.IsEnabled = false;
            Go.IsEnabled   = true;
            timer.Stop();
            timertext.Text = "";

            //calculate answer depending on the symbol
            if ((firstSymbol.Text == "+") && (secondSymbol.Text == "+"))
            {
                answer = num1 + num2 + num3;
            }
            else if ((firstSymbol.Text == "+") && (secondSymbol.Text == "*"))
            {
                answer = num1 + (num2 * num3);
            }
            else if ((firstSymbol.Text == "*") && (secondSymbol.Text == "+"))
            {
                answer = (num1 * num2) + num3;
            }
            else if ((firstSymbol.Text == "*") && (secondSymbol.Text == "*"))
            {
                answer = num1 * num2 * num3;
            }
            else if ((firstSymbol.Text == "*") && (secondSymbol.Text == "-"))
            {
                answer = (num1 * num2) - num3;
            }
            else if ((firstSymbol.Text == "+") && (secondSymbol.Text == "-"))
            {
                answer = num1 + num2 - num3;
            }
            else if ((firstSymbol.Text == "-") && (secondSymbol.Text == "*"))
            {
                answer = num1 - (num2 * num3);
            }
            else if ((firstSymbol.Text == "-") && (secondSymbol.Text == "+"))
            {
                answer = num1 - num2 + num3;
            }
            else
            {
                answer = (num1 - num2 - num3);
            }


            if (answerBox.Text == answer.ToString())
            {
                //reset boxes and variables and print correct to screen and update score
                answerBox.Text = "";
                timer.Stop();
                gameover.Text       = "      Correct!";
                gameover.Foreground = new SolidColorBrush(Colors.Green);
                score++;
                score1.Text       = "SCORE: " + score.ToString();
                score1.Foreground = new SolidColorBrush(Colors.Yellow);
                correctCounter++;

                //play correct sound
                Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets");

                Windows.Storage.StorageFile file = await folder.GetFileAsync("Correct-answer.mp3");

                correctMp3.AutoPlay = false;
                correctMp3.Source   = MediaSource.CreateFromStorageFile(file);
                correctMp3.Play();

                //this second timer is a timer to delay the go_click function for a second after the user click done or presses enter on their device
                var timer2 = new DispatcherTimer {
                    Interval = TimeSpan.FromSeconds(1)
                };
                timer2.Start();
                timer2.Tick += (sender1, args) =>
                {
                    timer2.Stop();
                    Go_Click(this, new RoutedEventArgs());
                };
            }

            //else incorrect answer
            else
            {
                //reset variables, print final score and Game over to screen
                gameover.Text          = "   GAME OVER";
                gameover.Foreground    = new SolidColorBrush(Colors.Red);
                finalScore1.Text       = "SCORE: " + score.ToString();
                finalScore1.Foreground = new SolidColorBrush(Colors.Red);

                //use try catch method to store highscore into local settings
                try
                {
                    int temp = Convert.ToInt32(localSettings.Values["hardHighScore"]);
                    if (temp < score)
                    {
                        localSettings.Values["hardHighScore"] = score.ToString();
                    }
                }
                catch
                {
                    // doesn't exist, just set the value
                    localSettings.Values["hardHighScore"] = score.ToString();
                }
                answerBox.IsEnabled = false;
                Go.Content          = "Try Again";
                correctCounter      = 0;
                score         = 0;
                score1.Text   = "";
                Done.Content  = ("Correct Answer = " + answer.ToString());
                Done.FontSize = 18;

                //play game over mp3
                Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets");

                Windows.Storage.StorageFile file = await folder.GetFileAsync("game-over.mp3");

                gameoverMp3.AutoPlay = false;
                gameoverMp3.Source   = MediaSource.CreateFromStorageFile(file);
                gameoverMp3.Play();
            }
        }//end of done_click
Ejemplo n.º 51
0
 public MainPage()
 {
     this.InitializeComponent();
     appHomeFolder         = Windows.Storage.ApplicationData.Current.LocalFolder;
     currentJournalEntries = new JournalEntries();
 }
Ejemplo n.º 52
0
 public static async Task <bool> FileExistsAsync(string key, Windows.Storage.StorageFolder folder)
 {
     return((await GetIfFileExistsAsync(key, folder)) != null);
 }
Ejemplo n.º 53
0
        public AppIconGenerator(Windows.Storage.StorageFolder outputFolder)
        {
            this.outputFolder = outputFolder;

            device = new CanvasDevice();
        }
Ejemplo n.º 54
0
 private static async Task <Windows.Storage.StorageFile> GetIfFileExistsAsync(string key, Windows.Storage.StorageFolder folder,
                                                                              Windows.Storage.CreationCollisionOption option = Windows.Storage.CreationCollisionOption.FailIfExists)
 {
     Windows.Storage.StorageFile retval;
     try
     {
         retval = await folder.GetFileAsync(key);
     }
     catch (System.IO.FileNotFoundException)
     {
         // System.Diagnostics.Debug.WriteLine("GetIfFileExistsAsync:FileNotFoundException");
         return(null);
     }
     return(retval);
 }
Ejemplo n.º 55
0
        static private async Task <ToastedDictionary> ReadToasted()
        {
            try
            {
                String json = null;
                using (Semaphore semFile = new Semaphore(1, 1, TOASTED_SEM))
                {
                    if (!semFile.WaitOne(2000))
                    {
                        throw new Exception("Failed to accquire toast access Semaphore");
                    }
                    try
                    {
                        Windows.Storage.StorageFolder temporaryFolder = ApplicationData.Current.TemporaryFolder;
                        StorageFile toastedFile = await temporaryFolder.GetFileAsync("toasted.json");

                        if (!toastedFile.IsAvailable)
                        {
                            return(new ToastedDictionary());
                        }

                        json = await FileIO.ReadTextAsync(toastedFile);
                    }
                    finally
                    {
                        semFile.Release();
                    }
                }

                // Sanity checks
                if (json == null)
                {
                    return(new ToastedDictionary());
                }

                json = json.Trim();
                if (String.IsNullOrEmpty(json))
                {
                    return(new ToastedDictionary());
                }

                // parse
                using (MemoryStream ms = new MemoryStream())
                {
                    using (StreamWriter wr = new StreamWriter(ms))
                    {
                        wr.Write(json);
                        wr.Flush();
                        ms.Position = 0;
                        var serializer       = new DataContractJsonSerializer(typeof(ToastedDictionary));
                        ToastedDictionary td = (ToastedDictionary)serializer.ReadObject(ms);
                        return(td);
                    }
                }
            }
            catch (FileNotFoundException)
            {
                return(new ToastedDictionary());
            }
            catch (Exception x)
            {
                ShowToast("ReadToasted:" + x.Message);
                return(new ToastedDictionary());
            }
        }
        private async void Durchsuchen_Click(object sender, RoutedEventArgs _1)
        {
            int BootsIDCounter = 1;
            int Filecounter    = 1;
            var folderPicker   = new Windows.Storage.Pickers.FolderPicker
            {
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop
            };

            folderPicker.FileTypeFilter.Add("*");

            Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                DataAccess.Reset();

                // Application now has read/write access to all contents in the picked folder
                // (including other sub-folder contents)
                Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
                DisplayImportwurdegestartet();
                IReadOnlyList <StorageFile> filelist = await folder.GetFilesAsync();

                FileImport_Progress_indicator.Maximum    = filelist.Count;
                FileImport_Progress_indicator.Visibility = Visibility.Visible;
                foreach (StorageFile file in filelist)
                {
                    if (file.FileType == ".xls" || file.FileType == ".xlsx")
                    {
                        FileImport_success_indicator.Text += "Successfully processed " + file.DisplayName + " at " + file.Path + " (" + file.FileType + ")\n";
                        //Get Exel ready
                        ISheet sheet;
                        using (Stream filetmp = await file.OpenStreamForReadAsync())
                        {
                            if (file.FileType == ".xls")
                            {
                                HSSFWorkbook hssfwb;
                                hssfwb = new HSSFWorkbook(filetmp);
                                sheet  = hssfwb.GetSheetAt(0);
                            }
                            else
                            {
                                XSSFWorkbook xssfwb;
                                xssfwb = new XSSFWorkbook(filetmp);
                                sheet  = xssfwb.GetSheetAt(0);
                            }
                        }
                        //import Exel to DataAcccess
                        int     BootsID          = BootsIDCounter++;
                        string  RennID           = CellLookup(sheet, "A12");
                        string  Bootsname        = CellLookup(sheet, "C26");
                        string  Verein           = CellLookup(sheet, "G12");
                        string  Steuerling       = NamenLookup(sheet, "D24", "C24");
                        string  SteuerlingVerein = CellLookup(sheet, "G16");
                        string  Athlet1          = NamenLookup(sheet, "D16", "C16");
                        string  Athlet1Verein    = CellLookup(sheet, "G16");
                        string  Athlet2          = NamenLookup(sheet, "D17", "C17");
                        string  Athlet2Verein    = CellLookup(sheet, "G17");
                        string  Athlet3          = NamenLookup(sheet, "D18", "C18");
                        string  Athlet3Verein    = CellLookup(sheet, "G18");
                        string  Athlet4          = NamenLookup(sheet, "D19", "C19");
                        string  Athlet4Verein    = CellLookup(sheet, "G19");
                        string  Athlet5          = NamenLookup(sheet, "D20", "C20");
                        string  Athlet5Verein    = CellLookup(sheet, "G20");
                        string  Athlet6          = NamenLookup(sheet, "D21", "C21");
                        string  Athlet6Verein    = CellLookup(sheet, "G21");
                        string  Athlet7          = NamenLookup(sheet, "D22", "C22");
                        string  Athlet7Verein    = CellLookup(sheet, "G22");
                        string  Athlet8          = NamenLookup(sheet, "D23", "C23");
                        string  Athlet8Verein    = CellLookup(sheet, "G23");
                        string  Meldername       = NamenLookup(sheet, "G3", "D3");
                        string  Melderadresse    = FirstCharToUpper(CellLookup(sheet, "D4"));
                        string  Melderort        = CellLookup(sheet, "D5") + " " + FirstCharToUpper(CellLookup(sheet, "F5"));
                        string  Melderverein     = CellLookup(sheet, "D6");
                        string  Melderemail      = CellLookup(sheet, "D7").ToLower();
                        string  Meldertel        = CellLookup(sheet, "D8");
                        string  Melderfax        = CellLookup(sheet, "D9");
                        string  Kommentare       = CellLookup(sheet, "D27");
                        decimal Bezahlt          = 0;

                        DataAccess.AddData(BootsID, 0, 0, RennID, Bootsname, Verein,
                                           Steuerling, SteuerlingVerein, Athlet1, Athlet1Verein, Athlet2, Athlet2Verein,
                                           Athlet3, Athlet3Verein, Athlet4, Athlet4Verein, Athlet5, Athlet5Verein,
                                           Athlet6, Athlet6Verein, Athlet7, Athlet7Verein, Athlet8, Athlet8Verein,
                                           Meldername, Melderadresse, Melderort, Melderverein, Melderemail,
                                           Meldertel, Melderfax, Bezahlt, Kommentare);
                    }
                    else
                    {
                        FileImport_success_indicator.Text += "\nFataly failed to process " + file.DisplayName + " at " + file.Path + " (" + file.FileType + ")\n\n";
                    }
                    FileImport_Progress_indicator.Value = Filecounter++;
                }
                durchsuchen.Background = new SolidColorBrush(Colors.Green);
            }
            else
            {
                FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
            }
        }
Ejemplo n.º 57
0
 /// <summary>
 /// Creates the change log.
 /// </summary>
 public static async void CreateChangeLog()
 {
     Windows.Storage.StorageFolder storageFolder =
         Windows.Storage.ApplicationData.Current.LocalFolder;
     await storageFolder.CreateFileAsync("Changelog.txt");
 }
Ejemplo n.º 58
0
        static public async void SaveProgect(ObservableCollection <ClassSob> classSobsColec)
        {
            DataSet   bookStore    = new DataSet("Project");
            DataTable booksTable   = new DataTable("Sob");
            DataTable NeutronTable = new DataTable("Neutrom");

            // добавляем таблицу в dataset
            bookStore.Tables.Add(booksTable);
            bookStore.Tables.Add(NeutronTable);


            DataColumn idColumnN = new DataColumn("Id", Type.GetType("System.Int32"));

            idColumnN.Unique            = true;  // столбец будет иметь уникальное значение
            idColumnN.AllowDBNull       = false; // не может принимать null
            idColumnN.AutoIncrement     = true;  // будет автоинкрементироваться
            idColumnN.AutoIncrementSeed = 1;     // начальное значение
            idColumnN.AutoIncrementStep = 1;     // приращении при добавлении новой строки

            DataColumn FileColumnN  = new DataColumn("file", Type.GetType("System.String"));
            DataColumn DColumnN     = new DataColumn("D", Type.GetType("System.Int32"));
            DataColumn AColumnN     = new DataColumn("Amp", Type.GetType("System.Int32"));
            DataColumn TimeColumnN  = new DataColumn("Time", Type.GetType("System.String"));
            DataColumn tFColumnN    = new DataColumn("tF", Type.GetType("System.Int32"));
            DataColumn tF3ColumnN   = new DataColumn("tF3", Type.GetType("System.Int32"));
            DataColumn tMaxColumnN  = new DataColumn("tMax", Type.GetType("System.Int32"));
            DataColumn tEndColumnN  = new DataColumn("tEnd", Type.GetType("System.Int32"));
            DataColumn tEnd3ColumnN = new DataColumn("tEnd3", Type.GetType("System.Int32"));


            NeutronTable.Columns.Add(idColumnN);
            NeutronTable.Columns.Add(FileColumnN);
            NeutronTable.Columns.Add(DColumnN);
            NeutronTable.Columns.Add(AColumnN);
            NeutronTable.Columns.Add(TimeColumnN);
            NeutronTable.Columns.Add(tFColumnN);
            NeutronTable.Columns.Add(tF3ColumnN);
            NeutronTable.Columns.Add(tMaxColumnN);
            NeutronTable.Columns.Add(tEndColumnN);
            NeutronTable.Columns.Add(tEnd3ColumnN);



            // создаем столбцы для таблицы Books
            DataColumn idColumn = new DataColumn("Id", Type.GetType("System.Int32"));

            idColumn.Unique            = true;  // столбец будет иметь уникальное значение
            idColumn.AllowDBNull       = false; // не может принимать null
            idColumn.AutoIncrement     = true;  // будет автоинкрементироваться
            idColumn.AutoIncrementSeed = 1;     // начальное значение
            idColumn.AutoIncrementStep = 1;     // приращении при добавлении новой строки



            DataColumn FileColumn = new DataColumn("file", Type.GetType("System.String"));
            DataColumn klColumn   = new DataColumn("kl", Type.GetType("System.String"));

            // priceColumn.DefaultValue = 100; // значение по умолчанию
            DataColumn TimeColumn = new DataColumn("Time", Type.GetType("System.String"));
            DataColumn SAColumn   = new DataColumn("SA", Type.GetType("System.Int32"));
            DataColumn SNColumn   = new DataColumn("SN", Type.GetType("System.Int32"));
            DataColumn AD1Column  = new DataColumn("AD1", Type.GetType("System.Int32"));
            DataColumn AD2Column  = new DataColumn("AD2", Type.GetType("System.Int32"));
            DataColumn AD3Column  = new DataColumn("AD3", Type.GetType("System.Int32"));
            DataColumn AD4Column  = new DataColumn("AD4", Type.GetType("System.Int32"));
            DataColumn AD5Column  = new DataColumn("AD5", Type.GetType("System.Int32"));
            DataColumn AD6Column  = new DataColumn("AD6", Type.GetType("System.Int32"));
            DataColumn AD7Column  = new DataColumn("AD7", Type.GetType("System.Int32"));
            DataColumn AD8Column  = new DataColumn("AD8", Type.GetType("System.Int32"));
            DataColumn AD9Column  = new DataColumn("AD9", Type.GetType("System.Int32"));
            DataColumn AD10Column = new DataColumn("AD10", Type.GetType("System.Int32"));
            DataColumn AD11Column = new DataColumn("AD11", Type.GetType("System.Int32"));
            DataColumn AD12Column = new DataColumn("AD12", Type.GetType("System.Int32"));

            DataColumn ND1Column  = new DataColumn("ND1", Type.GetType("System.Int32"));
            DataColumn ND2Column  = new DataColumn("ND2", Type.GetType("System.Int32"));
            DataColumn ND3Column  = new DataColumn("ND3", Type.GetType("System.Int32"));
            DataColumn ND4Column  = new DataColumn("ND4", Type.GetType("System.Int32"));
            DataColumn ND5Column  = new DataColumn("ND5", Type.GetType("System.Int32"));
            DataColumn ND6Column  = new DataColumn("ND6", Type.GetType("System.Int32"));
            DataColumn ND7Column  = new DataColumn("ND7", Type.GetType("System.Int32"));
            DataColumn ND8Column  = new DataColumn("ND8", Type.GetType("System.Int32"));
            DataColumn ND9Column  = new DataColumn("ND9", Type.GetType("System.Int32"));
            DataColumn ND10Column = new DataColumn("ND10", Type.GetType("System.Int32"));
            DataColumn ND11Column = new DataColumn("ND11", Type.GetType("System.Int32"));
            DataColumn ND12Column = new DataColumn("ND12", Type.GetType("System.Int32"));

            DataColumn Sig1Column  = new DataColumn("Sig1", Type.GetType("System.Decimal"));
            DataColumn Sig2Column  = new DataColumn("Sig2", Type.GetType("System.Decimal"));
            DataColumn Sig3Column  = new DataColumn("Sig3", Type.GetType("System.Decimal"));
            DataColumn Sig4Column  = new DataColumn("Sig4", Type.GetType("System.Decimal"));
            DataColumn Sig5Column  = new DataColumn("Sig5", Type.GetType("System.Decimal"));
            DataColumn Sig6Column  = new DataColumn("Sig6", Type.GetType("System.Decimal"));
            DataColumn Sig7Column  = new DataColumn("Sig7", Type.GetType("System.Decimal"));
            DataColumn Sig8Column  = new DataColumn("Sig8", Type.GetType("System.Decimal"));
            DataColumn Sig9Column  = new DataColumn("Sig9", Type.GetType("System.Decimal"));
            DataColumn Sig10Column = new DataColumn("Sig10", Type.GetType("System.Decimal"));
            DataColumn Sig11Column = new DataColumn("Sig11", Type.GetType("System.Decimal"));
            DataColumn Sig12Column = new DataColumn("Sig12", Type.GetType("System.Decimal"));

            DataColumn NullD1Column  = new DataColumn("NullD1", Type.GetType("System.Decimal"));
            DataColumn NullD2Column  = new DataColumn("NullD2", Type.GetType("System.Decimal"));
            DataColumn NullD3Column  = new DataColumn("NullD3", Type.GetType("System.Decimal"));
            DataColumn NullD4Column  = new DataColumn("NullD4", Type.GetType("System.Decimal"));
            DataColumn NullD5Column  = new DataColumn("NullD5", Type.GetType("System.Decimal"));
            DataColumn NullD6Column  = new DataColumn("NullD6", Type.GetType("System.Decimal"));
            DataColumn NullD7Column  = new DataColumn("NullD7", Type.GetType("System.Decimal"));
            DataColumn NullD8Column  = new DataColumn("NullD8", Type.GetType("System.Decimal"));
            DataColumn NullD9Column  = new DataColumn("NullD9", Type.GetType("System.Decimal"));
            DataColumn NullD10Column = new DataColumn("NullD10", Type.GetType("System.Decimal"));
            DataColumn NullD11Column = new DataColumn("NullD11", Type.GetType("System.Decimal"));
            DataColumn NullD12Column = new DataColumn("NullD12", Type.GetType("System.Decimal"));

            DataColumn TD1Column  = new DataColumn("TD1", Type.GetType("System.Int32"));
            DataColumn TD2Column  = new DataColumn("TD2", Type.GetType("System.Int32"));
            DataColumn TD3Column  = new DataColumn("TD3", Type.GetType("System.Int32"));
            DataColumn TD4Column  = new DataColumn("TD4", Type.GetType("System.Int32"));
            DataColumn TD5Column  = new DataColumn("TD5", Type.GetType("System.Int32"));
            DataColumn TD6Column  = new DataColumn("TD6", Type.GetType("System.Int32"));
            DataColumn TD7Column  = new DataColumn("TD7", Type.GetType("System.Int32"));
            DataColumn TD8Column  = new DataColumn("TD8", Type.GetType("System.Int32"));
            DataColumn TD9Column  = new DataColumn("TD9", Type.GetType("System.Int32"));
            DataColumn TD10Column = new DataColumn("TD10", Type.GetType("System.Int32"));
            DataColumn TD11Column = new DataColumn("TD11", Type.GetType("System.Int32"));
            DataColumn TD12Column = new DataColumn("TD12", Type.GetType("System.Int32"));

            // discountColumn.Expression = "Price * 0.2";

            booksTable.Columns.Add(idColumn);
            booksTable.Columns.Add(FileColumn);
            booksTable.Columns.Add(klColumn);
            booksTable.Columns.Add(TimeColumn);
            booksTable.Columns.Add(SAColumn);
            booksTable.Columns.Add(SNColumn);

            booksTable.Columns.Add(AD1Column);
            booksTable.Columns.Add(AD2Column);
            booksTable.Columns.Add(AD3Column);
            booksTable.Columns.Add(AD4Column);
            booksTable.Columns.Add(AD5Column);
            booksTable.Columns.Add(AD6Column);
            booksTable.Columns.Add(AD7Column);
            booksTable.Columns.Add(AD8Column);
            booksTable.Columns.Add(AD9Column);
            booksTable.Columns.Add(AD10Column);
            booksTable.Columns.Add(AD11Column);
            booksTable.Columns.Add(AD12Column);

            booksTable.Columns.Add(ND1Column);
            booksTable.Columns.Add(ND2Column);
            booksTable.Columns.Add(ND3Column);
            booksTable.Columns.Add(ND4Column);
            booksTable.Columns.Add(ND5Column);
            booksTable.Columns.Add(ND6Column);
            booksTable.Columns.Add(ND7Column);
            booksTable.Columns.Add(ND8Column);
            booksTable.Columns.Add(ND9Column);
            booksTable.Columns.Add(ND10Column);
            booksTable.Columns.Add(ND11Column);
            booksTable.Columns.Add(ND12Column);

            booksTable.Columns.Add(Sig1Column);
            booksTable.Columns.Add(Sig2Column);
            booksTable.Columns.Add(Sig3Column);
            booksTable.Columns.Add(Sig4Column);
            booksTable.Columns.Add(Sig5Column);
            booksTable.Columns.Add(Sig6Column);
            booksTable.Columns.Add(Sig7Column);
            booksTable.Columns.Add(Sig8Column);
            booksTable.Columns.Add(Sig9Column);
            booksTable.Columns.Add(Sig10Column);
            booksTable.Columns.Add(Sig11Column);
            booksTable.Columns.Add(Sig12Column);

            booksTable.Columns.Add(NullD1Column);
            booksTable.Columns.Add(NullD2Column);
            booksTable.Columns.Add(NullD3Column);
            booksTable.Columns.Add(NullD4Column);
            booksTable.Columns.Add(NullD5Column);
            booksTable.Columns.Add(NullD6Column);
            booksTable.Columns.Add(NullD7Column);
            booksTable.Columns.Add(NullD8Column);
            booksTable.Columns.Add(NullD9Column);
            booksTable.Columns.Add(NullD10Column);
            booksTable.Columns.Add(NullD11Column);
            booksTable.Columns.Add(NullD12Column);

            booksTable.Columns.Add(TD1Column);
            booksTable.Columns.Add(TD2Column);
            booksTable.Columns.Add(TD3Column);
            booksTable.Columns.Add(TD4Column);
            booksTable.Columns.Add(TD5Column);
            booksTable.Columns.Add(TD6Column);
            booksTable.Columns.Add(TD7Column);
            booksTable.Columns.Add(TD8Column);
            booksTable.Columns.Add(TD9Column);
            booksTable.Columns.Add(TD10Column);
            booksTable.Columns.Add(TD11Column);
            booksTable.Columns.Add(TD12Column);
            // определяем первичный ключ таблицы books
            booksTable.PrimaryKey = new DataColumn[] { booksTable.Columns["Id"] };

            foreach (ClassSob classSob in classSobsColec)
            {
                DataRow row = booksTable.NewRow();
                row.ItemArray = new object[] { null, classSob.nameFile, classSob.nameklaster, classSob.time, classSob.SumAmp, classSob.SumNeu, classSob.mAmp[0], classSob.mAmp[1], classSob.mAmp[2], classSob.mAmp[3],
                                               classSob.mAmp[4], classSob.mAmp[5], classSob.mAmp[6], classSob.mAmp[7], classSob.mAmp[8], classSob.mAmp[9], classSob.mAmp[10], classSob.mAmp[11], classSob.Nnut0, classSob.Nnut1, classSob.Nnut2, classSob.Nnut3,
                                               classSob.Nnut4, classSob.Nnut5, classSob.Nnut6, classSob.Nnut7, classSob.Nnut8, classSob.Nnut9, classSob.Nnut10, classSob.Nnut11, classSob.sig0, classSob.sig1, classSob.sig2, classSob.sig3,
                                               classSob.sig4, classSob.sig5, classSob.sig6, classSob.sig7, classSob.sig8, classSob.sig9, classSob.sig10, classSob.sig11, classSob.Nnull0, classSob.Nnull1, classSob.Nnull2, classSob.Nnull3,
                                               classSob.Nnull4, classSob.Nnull5, classSob.Nnull6, classSob.Nnull7, classSob.Nnull8, classSob.Nnull9, classSob.Nnull10, classSob.Nnull11, classSob.mTimeD[0], classSob.mTimeD[1], classSob.mTimeD[2],
                                               classSob.mTimeD[3], classSob.mTimeD[4], classSob.mTimeD[5], classSob.mTimeD[6], classSob.mTimeD[7], classSob.mTimeD[8], classSob.mTimeD[9], classSob.mTimeD[10], classSob.mTimeD[11] };
                booksTable.Rows.Add(row); // добавляем первую строку

                if (classSob.SumNeu > 0)
                {
                    foreach (ClassSobNeutron sobNeutron in classSob.classSobNeutronsList)
                    {
                        DataRow rowN = NeutronTable.NewRow();
                        rowN.ItemArray = new object[] { null, classSob.nameFile, sobNeutron.D, sobNeutron.Amp, classSob.time, sobNeutron.TimeFirst, sobNeutron.TimeFirst3,
                                                        sobNeutron.TimeAmp, sobNeutron.TimeEnd, sobNeutron.TimeEnd3 };
                        NeutronTable.Rows.Add(rowN);
                    }
                }
            }

            var folderPicker = new Windows.Storage.Pickers.FolderPicker();

            folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
            folderPicker.FileTypeFilter.Add("*");

            Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                // Application now has read/write access to all contents in the picked folder
                // (including other sub-folder contents)
                Windows.Storage.AccessCache.StorageApplicationPermissions.
                FutureAccessList.AddOrReplace("PickedFolderToken", folder);

                StorageFolder storageFolder = ApplicationData.Current.LocalFolder;



                // ObservableCollection<ClassSobColl> classSobs = new ObservableCollection<ClassSobColl>();
                using (StreamWriter writer =
                           new StreamWriter(await folder.OpenStreamForWriteAsync(
                                                "Progect.uranprog", CreationCollisionOption.OpenIfExists)))
                {
                    bookStore.WriteXml(writer);
                }
            }
            else
            {
            }
            MessageDialog messageDialog = new MessageDialog("Сохранено");
            await messageDialog.ShowAsync();
        }
Ejemplo n.º 59
0
        private async void submitButton_Click(object sender, RoutedEventArgs e)
        {
            //MessageBox
            if (selectProblemButton.Content.ToString() == "choose a problem")
            {
                MessageDialog invalidProblem = new MessageDialog("You need to select a problem type before you can submit a ticket.", "Invalid problem type");
                await invalidProblem.ShowAsync();
            }

            else if (descriptionText.Text == "")
            {
                MessageDialog invalidDescription = new MessageDialog("You need to type a description before you can submit a ticket.", "You need to type a description");
                await invalidDescription.ShowAsync();
            }

            else if (expletiveslist.expletivesArray.Contains(descriptionText.Text))
            {
                MessageDialog expletivesDetected = new MessageDialog("There are expletives in your description. Please remove these before sending the ticket.", "Expletives detected");
                await expletivesDetected.ShowAsync();
            }

            else
            {
                //Get variables
                var submitDate   = DateTime.Now.ToString();
                var problem      = selectProblemButton.Content.ToString();
                var location     = selectRoomButton.Content.ToString();
                var attachedFile = fileText.Text.ToString();

                string videoAttached = null;
                if (attachedFile.Contains("mp4"))
                {
                    videoAttached = "Attached video: " + attachedFile;
                }

                else
                {
                    videoAttached = "Attached photo: " + attachedFile;
                }

                //WRITE
                //Create the text file to hold the data
                Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                Windows.Storage.StorageFile   ticketsFile   = await storageFolder.CreateFileAsync("tickets.txt", Windows.Storage.CreationCollisionOption.OpenIfExists);

                await FileIO.AppendTextAsync(ticketsFile, "\n" + "Submitted: " + submitDate + "\n" + "Problem: " + problem + "\n" + "Room: " + location + "\n" + "Description: " + descriptionText.Text + "\n" + "Priority: " + priority + "\n" + videoAttached + "\n");

                //Use stream to write to the file
                var stream = await ticketsFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.*/

                //READ
                //Open the text file
                stream = await ticketsFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                ulong size = stream.Size;

                using (var inputStream = stream.GetInputStreamAt(0))
                {
                    using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
                    {
                        uint numBytesLoaded = await dataReader.LoadAsync((uint)size);

                        string savedTickets = dataReader.ReadString(numBytesLoaded);

                        ticketTextBlock.Text = savedTickets;
                    }
                }
                stream.Dispose();

                //SEND EMAIL
                string messageBody  = "\n" + "Ticket submitted: " + submitDate + "\n" + "Problem: " + problem.ToUpper() + "\n" + "Room: " + location + "\n" + "Description: " + descriptionText.Text + "\n" + "Priority: " + priority + "\n" + videoAttached + "\n" + "\n" + "----------------------------------------------------------" + "\n" + "Sent from wh-at Helpdesk (for Windows 10)" + "\n" + "\n" + "You may respond to this email, it will send an email to the sender.";
                string messageTitle = problem.ToUpper() + " | " + location;

                if (_file == null)
                {
                    EmailMessage emailMessage = new EmailMessage();
                    emailMessage.To.Add(new EmailRecipient("*****@*****.**"));
                    emailMessage.Body    = messageBody;
                    emailMessage.Subject = messageTitle;
                    await EmailManager.ShowComposeNewEmailAsync(emailMessage);
                }

                else
                {
                    EmailMessage emailMessage = new EmailMessage();
                    emailMessage.To.Add(new EmailRecipient("*****@*****.**"));
                    emailMessage.Body    = messageBody;
                    emailMessage.Subject = messageTitle;

                    var emailStream = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(_file);
                    var attachment  = new Windows.ApplicationModel.Email.EmailAttachment(
                        _file.Name,
                        emailStream);
                    emailMessage.Attachments.Add(attachment);

                    await EmailManager.ShowComposeNewEmailAsync(emailMessage);
                }
            }
        }
Ejemplo n.º 60
-31
        public async void InitFolders()
        {
            _localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            var folderName = "";
            try
            {
                folderName = "medium";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}")) _mediumFolder = await _localFolder.GetFolderAsync(folderName);
                else _mediumFolder = await _localFolder.CreateFolderAsync(folderName);

                folderName = "thumb";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}")) _thumbFolder = await _localFolder.GetFolderAsync(folderName);
                else _thumbFolder = await _localFolder.CreateFolderAsync(folderName);

                folderName = "original";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}")) _originalFolder = await _localFolder.GetFolderAsync(folderName);
                else _originalFolder = await _localFolder.CreateFolderAsync(folderName);

                folderName = "tile";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}")) _tileFolder = await _localFolder.GetFolderAsync(folderName);
                else _tileFolder = await _localFolder.CreateFolderAsync(folderName);

            }
            catch //(System.IO.FileNotFoundException ex)
            {
                //todo: what would ever cause this ??! need to work out how to handle this type of error
            }
            
        }