public static void Execute(StorageFolder device)
        {
            Console.WriteLine($"== Scenario6_CreateFilesInFolder ==");

            try
            {
                // In Scenario5 we created a folder structure.
                // This sample uses the folder stucture and creates files in those folders
                // D:\\Folder11\Folder21\Folder31


                // Build up the path for folders by using GetFolder, If the folder doesn't exist you will get an exception
                StorageFolder Folder11 = device.GetFolder("Folder11");
                StorageFolder Folder21 = Folder11.GetFolder("Folder22");
                StorageFolder Folder31 = Folder21.GetFolder("Folder31");


                // create a file (replace if there is already one with this name)
                var fileNew1 = Folder31.CreateFile("sample1.txt", CreationCollisionOption.ReplaceExisting);
                Console.WriteLine($"OK: Successfully created 1st file: {fileNew1.Path}");

                var fileNew2 = Folder31.CreateFile("sample2.txt", CreationCollisionOption.ReplaceExisting);
                Console.WriteLine($"OK: Successfully created 2nd file: {fileNew2.Path}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception creating files in folders: {ex.Message}");
            }
        }
        public static void Execute(StorageFolder device)
        {
            Console.WriteLine($"== Scenario4_WriteAndReadBytesInAFile ==");

            // create a file
            var myFile = device.CreateFile("file3.bin", CreationCollisionOption.ReplaceExisting);

            Console.WriteLine($"OK: Successfully created file: {myFile.Path}");

            string userContent = "this is a string to be saved as binary data";

            IBuffer writeBuffer   = GetBufferFromString(userContent);
            uint    bytesInBuffer = writeBuffer.Length;

            FileIO.WriteBuffer(myFile, writeBuffer);

            Console.WriteLine($"Of the {bytesInBuffer} in buffer, { writeBuffer.Length } remains to be written to '{myFile.Name}':\r\n{ userContent }");

            IBuffer readBuffer = FileIO.ReadBuffer(myFile);

            using (DataReader dataReader = DataReader.FromBuffer(readBuffer))
            {
                string fileContent = dataReader.ReadString(readBuffer.Length);

                Console.WriteLine($"The following {readBuffer.Length} bytes of text were read from '{myFile.Name}':\r\n{ fileContent }");
            }
        }
Example #3
0
        /// <summary>
        /// Read text file
        /// </summary>
        /// <returns>Text from file</returns>
        public string ReadText(string FilePath)
        {
            // Not capitalized in internal storage
            if (IsInternalStorage == false)
            {
                FilePath = FilePath.ToUpper();
            }

            try
            {
                //  Rem directory and filename set in FileExists
                if (FileExists(FilePath))
                {
                    var File = Sfolder.CreateFile(Fname, CreationCollisionOption.OpenIfExists);

                    return(FileIO.ReadText(File));
                }

                return(string.Empty);
            }

            catch (Exception ex)
            {
                return("Error: Reading file " + ex.Message);
            }
        }
        public static void Execute(StorageFolder device)
        {
            Console.WriteLine($"== Scenario2_CreateAFileInStorage ==");

            try
            {
                // create a file (replace if there is already one with this name)
                var fileNew = device.CreateFile("file1.txt", CreationCollisionOption.ReplaceExisting);

                Console.WriteLine($"OK: Successfully created file: {fileNew.Path}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: Unable to create file: {ex.Message}");
            }
        }
Example #5
0
        public static void Execute(StorageFolder device)
        {
            Console.WriteLine($"== Scenario3_WriteAndReadTextInAFile ==");

            string textFromFile = null;

            // create a file
            var myFile = device.CreateFile("file2.txt", CreationCollisionOption.ReplaceExisting);

            Console.WriteLine($"OK: Successfully created file: {myFile.Path}");

            string textContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

            try
            {
                // write text to the file
                FileIO.WriteText(myFile, textContent);
            }
            catch (Exception)
            {
                Console.WriteLine($"ERROR: write operation on file failed.");
            }

            try
            {
                // read text from the file
                textFromFile = FileIO.ReadText(myFile);
            }
            catch (Exception)
            {
                Console.WriteLine($"ERROR: read operation on file failed.");
            }

            // compare
            if (textContent.GetHashCode() == textFromFile.GetHashCode())
            {
                Console.WriteLine($"OK: read text matches written text.");
            }
            else
            {
                Console.WriteLine($"ERROR: read text does not match written text.");
            }
        }
Example #6
0
        internal static void SaveData <T>(T data, string file)
        {
            string path = "Unkown";

#if WP81
            StorageFile f;
            int         tries = 0;
            Stream      str;
retry:
            try
            {
                f   = savegameStorage.CreateFileAsync(file, CreationCollisionOption.ReplaceExisting).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
                str = f.OpenStreamForWriteAsync().Result;
            }
            catch
            {
                if (tries > 10)
                {
                    Debug.WriteLine("__ALERT__: Failed to save file:" + file);
                    return;
                }
                tries++;
                goto retry;
            }
#elif UAP || ANDROID
            IsolatedStorageFileStream str = savegameStorage.CreateFile(file);
#else
            if (!Directory.Exists(savedir))
            {
                Directory.CreateDirectory(savedir);
            }
            FileStream str = File.Open(path = savedir + file, FileMode.Create);
#endif
            // TODO: Fix using intermediate serializer
            //XmlSerializer serializer = new XmlSerializer(typeof(T));
            //serializer.Serialize(str, data);
#if WINDOWS_UAP && DEBUG // Causes crashes after release
            path = str.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(str).ToString();
#endif
            Debug.WriteLine("______ALERT______SavedFileTo: " + path);
            str.Dispose();
        }
Example #7
0
 private void SetUrls(List <UrlCache> cache)
 {
     Settings.SetFile(_appVersionFolder.CreateFile(UrlsFileName), cache);
 }
Example #8
0
        private static void ServerCommandReceived(object source, WebServerEventArgs e)
        {
            try
            {
                var url = e.Context.Request.RawUrl;
                Debug.WriteLine($"Command received: {url}, Method: {e.Context.Request.HttpMethod}");

                if (url.ToLower() == "/sayhello")
                {
                    // This is simple raw text returned
                    WebServer.OutPutStream(e.Context.Response, "It's working, url is empty, this is just raw text, /sayhello is just returning a raw text");
                }
                else if (url.Length <= 1)
                {
                    // Here you can return a real html page for example

                    WebServer.OutPutStream(e.Context.Response, "<html><head>" +
                                           "<title>Hi from nanoFramework Server</title></head><body>You want me to say hello in a real HTML page!<br/><a href='/useinternal'>Generate an internal text.txt file</a><br />" +
                                           "<a href='/Text.txt'>Download the Text.txt file</a><br>" +
                                           "Try this url with parameters: <a href='/param.htm?param1=42&second=24&NAme=Ellerbach'>/param.htm?param1=42&second=24&NAme=Ellerbach</a></body></html>");
                }
#if HAS_STORAGE
                else if (url.ToLower() == "/useinternal")
                {
                    // This tells the web server to use the internal storage and create a simple text file
                    _storage = KnownFolders.InternalDevices.GetFolders()[0];
                    var testFile = _storage.CreateFile("text.txt", CreationCollisionOption.ReplaceExisting);
                    FileIO.WriteText(testFile, "This is an example of file\r\nAnd this is the second line");
                    WebServer.OutPutStream(e.Context.Response, "Created a test file text.txt on internal storage");
                }
#endif
                else if (url.ToLower().IndexOf("/param.htm") == 0)
                {
                    ParamHtml(e);
                }
                else if (url.ToLower().IndexOf("/api/") == 0)
                {
                    // Check the routes and dispatch
                    var routes = url.TrimStart('/').Split('/');
                    if (routes.Length > 3)
                    {
                        // Check the security key
                        if (!CheckAPiKey(e.Context.Request.Headers))
                        {
                            WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.Forbidden);
                            return;
                        }

                        var pinNumber = Convert.ToInt16(routes[2]);

                        // Do we have gpio ?
                        if (routes[1].ToLower() == "gpio")
                        {
                            if ((routes[3].ToLower() == "high") || (routes[3].ToLower() == "1"))
                            {
                                _controller.Write(pinNumber, PinValue.High);
                            }
                            else if ((routes[3].ToLower() == "low") || (routes[3].ToLower() == "0"))
                            {
                                _controller.Write(pinNumber, PinValue.Low);
                            }
                            else
                            {
                                WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.BadRequest);
                                return;
                            }

                            WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.OK);
                            return;
                        }
                        else if (routes[1].ToLower() == "open")
                        {
                            if (routes[3].ToLower() == "input")
                            {
                                if (!_controller.IsPinOpen(pinNumber))
                                {
                                    _controller.OpenPin(pinNumber);
                                }

                                _controller.SetPinMode(pinNumber, PinMode.Input);
                            }
                            else if (routes[3].ToLower() == "output")
                            {
                                if (!_controller.IsPinOpen(pinNumber))
                                {
                                    _controller.OpenPin(pinNumber);
                                }

                                _controller.SetPinMode(pinNumber, PinMode.Output);
                            }
                            else
                            {
                                WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.BadRequest);
                                return;
                            }
                        }
                        else if (routes[1].ToLower() == "close")
                        {
                            if (_controller.IsPinOpen(pinNumber))
                            {
                                _controller.ClosePin(pinNumber);
                            }
                        }
                        else
                        {
                            WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.BadRequest);
                            return;
                        }

                        WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.OK);
                        return;
                    }
                    else if (routes.Length == 2)
                    {
                        if (routes[1].ToLower() == "apikey")
                        {
                            // Check the security key
                            if (!CheckAPiKey(e.Context.Request.Headers))
                            {
                                WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.Forbidden);
                                return;
                            }

                            if (e.Context.Request.HttpMethod != "POST")
                            {
                                WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.BadRequest);
                                return;
                            }

                            // Get the param from the body
                            if (e.Context.Request.ContentLength64 == 0)
                            {
                                WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.BadRequest);
                                return;
                            }

                            byte[] buff = new byte[e.Context.Request.ContentLength64];
                            e.Context.Request.InputStream.Read(buff, 0, buff.Length);
                            string rawData    = new string(Encoding.UTF8.GetChars(buff));
                            var    parameters = rawData.Split('=');
                            if (parameters.Length < 2)
                            {
                                WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.BadRequest);
                                return;
                            }

                            if (parameters[0].ToLower() == "newkey")
                            {
                                _securityKey = parameters[1];
                                WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.OK);
                                return;
                            }

                            WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.BadRequest);
                            return;
                        }
                    }
                    else
                    {
                        ApiDefault(e);
                    }
                }
                else if (url.ToLower().IndexOf("/favicon.ico") == 0)
                {
                    WebServer.SendFileOverHTTP(e.Context.Response, "favicon.ico", Resources.GetBytes(Resources.BinaryResources.favicon));
                }
#if HAS_STORAGE
                else
                {
                    // Very simple example serving a static file on an SD card
                    var files = _storage.GetFiles();
                    foreach (var file in files)
                    {
                        if (file.Name == url)
                        {
                            WebServer.SendFileOverHTTP(e.Context.Response, file);
                            return;
                        }
                    }

                    WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.NotFound);
                }
#endif
            }
            catch (Exception)
            {
                WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.InternalServerError);
            }
        }
 private void SetApplicationConfiguration(ApplicationConfiguration configuration)
 {
     SetFile(_appVersionFolder.CreateFile(SettingsFileName), configuration);
 }