public void ItemSectionRoundTrip()
        {
            var ms = new MemoryStream();
            var fio = new FileIO(ms);
            var fw = new FormattedWriter(fio);
            var wc = new WriteContext(fw);
            wc.Description = new TeaFileDescription();
            var writeID =
                wc.Description.ItemDescription = ItemDescription.FromAnalysis<Event<OHLCV>>();
            ISectionFormatter f = new ItemSectionFormatter();
            f.Write(wc);

            ms.Position = 0;

            var fr = new FormattedReader(fio);
            var rc = new ReadContext(fr);
            rc.Description.Should().Not.Be.Null();
            f.Read(rc);
            rc.Description.Should().Not.Be.Null();
            var id = rc.Description.ItemDescription;

            id.ItemTypeName.Should().Be(typeof (Event<OHLCV>).GetLanguageName());
            id.ItemSize.Should().Be(wc.Description.ItemDescription.ItemSize);
            id.Fields.Select(ff => ff.Name).Should().Have.SameValuesAs("Time", "Open", "High", "Low", "Close", "Volume");
            id.Fields.Select(ff => ff.Index).Should().Have.SameValuesAs(0, 1, 2, 3, 4, 5);
            id.Fields.Select(ff => ff.FieldType).Should().Have.SameValuesAs(FieldType.Int64, FieldType.Double, FieldType.Double, FieldType.Double, FieldType.Double);
            id.Fields.Select(ff => ff.Offset).Should().Have.SameValuesAs(writeID.Fields.Select(ff => ff.Offset));

            ms.Position.Should().Be(ms.Length); // very important, all bytes must have been read
        }
        public void NameValueSectionRoundTrip1EntryTest()
        {
            var ms = new MemoryStream();
            var fio = new FileIO(ms);
            var fw = new FormattedWriter(fio);
            var wc = new WriteContext(fw);

            ISectionFormatter f = new NameValueSectionFormatter();
            wc.Description = new TeaFileDescription();
            wc.Description.NameValues = new NameValueCollection();
            wc.Description.NameValues.Add(new NameValue("someName", 1.23));
            f.Write(wc);

            ms.Position = 0;

            var fr = new FormattedReader(fio);
            var rc = new ReadContext(fr);
            f.Read(rc);

            rc.Description.Should().Not.Be.Null();
            rc.Description.NameValues.Should().Not.Be.Null();
            rc.Description.NameValues.Should().Have.Count.EqualTo(1);
            rc.Description.NameValues.First().Name.Should().Be("someName");
            rc.Description.NameValues.First().GetValue<double>().Should().Be(1.23);
        }
Beispiel #3
0
        public MainWindow()
        {
            InitializeComponent();
            int[] REQUIRE_FFACE_VER = { 4, 1, 0, 24 };

            this.Height = Properties.Settings.Default.WindowSize.Height;
            this.Width = Properties.Settings.Default.WindowSize.Width;
            this.Top = Properties.Settings.Default.WindowLocation.Y;
            this.Left = Properties.Settings.Default.WindowLocation.X;
            CampahStatus.SetStatus("Loading Settings", Modes.Stopped);
            settingsManager = new FileIO(tbBuyItemSelect);
            settingsManager.loadSettingsXML();
            if (CampahStatus.Instance.AutomaticUpdates && (App.mArgs.Length == 0 || App.mArgs[0] != "updated"))
            {
                //CheckUpdate();  //No longer supported
            }
            String[] ffacever = FileVersionInfo.GetVersionInfo("FFACE.dll").FileVersion.Split(',');
            for (int i = 0; i < ffacever.Length; i++)
            {
                if(int.Parse(ffacever[i]) < REQUIRE_FFACE_VER[i])
                {
                    MessageBox.Show("Campah Requires FFACE.dll version 4.1.0.24 or higher.  Please download the latest version from ffevo forums");
                    Application.Current.Shutdown();
                }
            }
            if (File.Exists("Updater.exe"))
                File.Delete("Updater.exe");
            selectProcess();
            rtb_chatlog.Document = Chatlog.Instance.chatlog;
        }
Beispiel #4
0
 public void ImportTest()
 {
     var f = new FileIO(Filepath, "err.log");
     IEnumerable<ChessGame> gs = f.ImportPGN();
     String[] pgn = new PGNParser().Generate(gs.ElementAt(0)).ToArray();
     CollectionAssert.AreEqual(FirstGamePGN, pgn);
 }
        private void btSave_Click(object sender, EventArgs e)
        {
            string path = Directory.GetCurrentDirectory(); // Directory of settings file
            FileIO fio = new FileIO();

            fio.Save(plist, path, (Parameters)bs.Current);
        }
 public void Execute(ArgumentList arguments, TaskList tasklist, TagList tags, TagFolder folder)
 {
     FileIO loader = new FileIO();
     if (tasklist.MarkAsDone(arguments.GetParameter(1)))
     loader.SaveTasks(tasklist.GetTasks());
         else
             Console.WriteLine("No task with that id found to mark as done");
 }
Beispiel #7
0
        public static FileIO GetIO()
        {
            if (io == null)
            {
                io = new DiskIO();
            }

            return io;
        }
 public void Execute(ArgumentList arguments, TaskList tasks, TagList tags, TagFolder folder)
 {
     FileIO loader = new FileIO();
     TaskTagger tagTasks = new TaskTagger(tasks.GetTasks());
     if (tagTasks.Untag(arguments.GetParameter(1), arguments.GetParameter(2)))
         loader.SaveTasks(tagTasks.GetTasks());
     else
         Console.WriteLine("No task with that id found to untag");
 }
        public static string SaveClientData( string request )
        {
            string response = "Successfully saved";
            FileIO file = new FileIO();

            if( !file.saveToFile( request ) )
                response = "Failed to save";

            return response;
        }
 public void Execute(ArgumentList arguments, TaskList tasklist, TagList tags, TagFolder folder)
 {
     FileIO loader = new FileIO();
     if (tasklist.RemoveTask(arguments.GetParameter(1)))
         {
         loader.SaveTasks(tasklist.GetTasks());
         Console.WriteLine("Task " + arguments.GetParameter(1) + " removed.");
         }
     else
     Console.WriteLine("No task with that id found to remove");
 }
        public void TestDelete()
        {
            var fileIO = new FileIO("applicationhost_deleted.config");
            var siteToDelete = XDocument.Load("New_Site.xml").Element("site");
            var expected = WebSite.GetAllWebsites(fileIO).Count - 1;

            fileIO.Delete(siteToDelete, 1);
            var actual = WebSite.GetAllWebsites(fileIO).Count;

            Assert.Equal(expected, actual);
        }
Beispiel #12
0
 public SearchItem(FileIO.MovieModel movie)
 {
     Size = new System.Drawing.Size(331, 52);
     BackColor = System.Drawing.Color.FromArgb(50, 250, 250, 250);
     var title = new ELabel
     {
         Text = movie.Name,
         Size = new System.Drawing.Size(195, 24),
         Location = new System.Drawing.Point(5, 0 + 5 ),
         ForeColor = Helper.All["SearchItem"][0],
         BackColor = Helper.All["SearchItem"][1],
         Font = new System.Drawing.Font(Helper.FontNormal, 14F),
     };
     Controls.Add(title);
     var score = new ELabel
     {
         Text = movie.Score + "分",
         Size = new System.Drawing.Size(54, 24),
         Location = new System.Drawing.Point(217, 0 + 5),
         ForeColor = Helper.All["SearchItem"][2],
         BackColor = Helper.All["SearchItem"][3],
         Font = new System.Drawing.Font(Helper.FontNormal, 12F),
     };
     Controls.Add(score);
     var typestr = movie.Type.Aggregate("", (current, typestring) => current + (typestring + "/"));
     typestr = typestr.Substring(0, typestr.Length - 1);
     var type = new ELabel
     {
         Text = typestr,
         Size = new System.Drawing.Size(54, 24),
         Location = new System.Drawing.Point(217 + 54, 0 + 5),
         ForeColor = Helper.All["SearchItem"][2],
         BackColor = Helper.All["SearchItem"][3],
         Font = new System.Drawing.Font(Helper.FontNormal, 12F),
     };
     Controls.Add(type);
     var urlfly = new EFlyPal
     {
         Size = new System.Drawing.Size(331-5, 30),
         Location = new System.Drawing.Point(5, 26 + 7),
         //Dock = System.Windows.Forms.DockStyle.Bottom,
     };
     Controls.Add(urlfly);
     foreach (var keyname in movie.Url.Keys.Select(key => new ELabel
         {
             Text = key,
             ForeColor = Helper.All["SearchItem"][4],
             BackColor = Helper.All["SearchItem"][5],
         }))
     {
         urlfly.Controls.Add(keyname);
     }
 }
Beispiel #13
0
        public void Run(string[] args) {
            var kommandozeile = new Kommandozeile();
            var fileIo = new FileIO();
            var termine = new Termine();
            var ics = new ICS();

            var csv_dateiname = kommandozeile.CSV_Dateiname_ermitteln(args);
            var ics_dateiname = kommandozeile.ICS_Dateiname_ermitteln(args);
            var dateiinhalt = fileIo.Datei_einlesen(csv_dateiname);
            var alle_termine = termine.Termine_erzeugen(dateiinhalt);
            ics.Termine_in_ICS_Datei_speichern(alle_termine, ics_dateiname);
        } 
Beispiel #14
0
 public void ReadInt32Test()
 {
     var stream = new Mock<Stream>(MockBehavior.Strict);
     stream.Setup(s => s.CanRead).Returns(true);
     stream.Setup(s => s.Read(It.IsAny<byte[]>(), 0, 4))
         .Returns((byte[] bytes, int i, int n) =>
             {
                 BitConverter.GetBytes(0x7f665544).CopyTo(bytes, 0);
                 return 4;
             });
     FileIO f = new FileIO(stream.Object);
     f.ReadInt32().Should().Be(0x7f665544);
 }
Beispiel #15
0
 public void ReadDoubleTest()
 {
     var stream = new Mock<Stream>(MockBehavior.Strict);
     stream.Setup(s => s.CanRead).Returns(true);
     stream.Setup(s => s.Read(It.IsAny<byte[]>(), 0, 8))
         .Returns((byte[] bytes, int i, int n) =>
             {
                 BitConverter.GetBytes(7.123).CopyTo(bytes, 0);
                 return 8;
             });
     FileIO f = new FileIO(stream.Object);
     f.ReadDouble().Should().Be(7.123);
 }
        public void TestSave()
        {
            var fileIO = new FileIO("applicationhost_saved.config");
            var newSite = XDocument.Load("New_Site.xml").Element("site");

            fileIO.Save(newSite, 1);

            var savedSite =
                (from s in XDocument.Load("applicationhost_saved.config").Descendants("site")
                 where s.Attribute("id").Value == "1"
                 select s).SingleOrDefault();
            Assert.Equal("false", savedSite.Attribute("serverAutoStart").Value);
        }
Beispiel #17
0
 public void ReadBytesTest()
 {
     var stream = new Mock<Stream>(MockBehavior.Strict);
     stream.Setup(s => s.CanRead).Returns(true);
     stream.Setup(s => s.Read(It.IsAny<byte[]>(), 0, 3))
         .Returns((byte[] bytes, int i, int n) =>
             {
                 bytes[0] = 0x11;
                 bytes[1] = 0x22;
                 bytes[2] = 0x33;
                 return 3;
             });
     FileIO f = new FileIO(stream.Object);
     f.ReadBytes(3).Should().Have.SameValuesAs<byte>(0x11, 0x22, 0x33);
 }
 public void Execute(ArgumentList arguments, TaskList tasks, TagList tags, TagFolder folder)
 {
     FileIO loader = new FileIO();
     TaskTagger tagTasks = new TaskTagger(tasks.GetTasks());
     if (tagTasks.DeleteTag(arguments.GetParameter(1)) || tags.HasTag(arguments.GetParameter(1)))
     {
         Tag tagToRemove = tags.GetTag(tags.GetTagIndex(arguments.GetParameter(1)));
         tags.RemoveTag(ref tagToRemove);
         loader.SaveTags(tags);
         loader.SaveTasks(tagTasks.GetTasks());
         Console.WriteLine("Tag {0} deleted", arguments.GetParameter(1));
     }
     else
         Console.WriteLine("No tag with that name available");
 }
Beispiel #19
0
 public void Execute(ArgumentList arguments, TaskList tasklist, TagList tags, TagFolder folder)
 {
     if (tasklist.HasSameTask(arguments.GetParameter(1)) == false)
     {
         Task task = new Task();
         FileIO loader = new FileIO();
         task.TaskDescription = arguments.GetParameter(1);
         task.IsNewTask = true;
         task = CheckDueDate(arguments, task);
         tasklist.AddTask(ref task);
         loader.SaveTasks(tasklist.GetTasks());
         Console.WriteLine("Task {0} added", task.TaskDescription);
     }
     else Console.WriteLine("Task already in list");
 }
        public void TestGetSitesSection()
        {
            var expected = XDocument.Load("LongValidSites.xml").Descendants("sites");
            var fileIO = new FileIO("applicationhost.config");

            var actual = fileIO.GetSitesSection();

            Assert.Equal(expected.Count(), actual.Count());
            foreach (var x in actual)
            {
                foreach (var y in expected)
                {
                    Assert.True(XElement.DeepEquals(x, y));
                }
            }
        }
        public void ReadRecordsNormalTest()
        {
            FileStream fs = new FileStream("readTestDB", FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine("record0ValueA|record0ValueB|");
            sw.WriteLine("record1ValueA|record1ValueB|");
            sw.Flush();
            fs.Close();

            FileIO db = new FileIO("readTestDB");
            var records = db.ReadRecords("|");

            Assert.AreEqual(records[0][0], "record0ValueA");
            Assert.AreEqual(records[0][1], "record0ValueB");
            Assert.AreEqual(records[1][0], "record1ValueA");
            Assert.AreEqual(records[1][1], "record1ValueB");
        }
Beispiel #22
0
        public void Execute(IPlayer player)
        {
            if (String.IsNullOrEmpty(player.ReceivedInput))
                return;

            string[] args = player.ReceivedInput.Split(' ');
            string direction = String.Empty;

            if (args.Length >= 2) //will always be at least 1, as the command itself is at index 0, making length 1
                direction = args[1]; //Assume Walk North, so [1] = North (or any other direction)
            else
            {
                player.SendMessage("Please specify which direction you would like to walk.");
                return;
            }

            AvailableTravelDirections travelDirection = TravelDirections.GetTravelDirectionValue(direction);

            if (travelDirection == AvailableTravelDirections.None)
            {
                player.SendMessage("Invalid direction!");
                return;
            }

            if (player.Location.DoorwayExists(travelDirection))
            {
                IDoor door = player.Location.GetDoorway(travelDirection);
                player.Move(door.Arrival);

                //Make sure we have a valid save path
                var filePath = Path.Combine(Directory.GetCurrentDirectory(), EngineSettings.Default.PlayerSavePath, player.Username + ".char");
                var path = Path.GetDirectoryName(filePath);

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                //Save the player using our serialization class
                FileIO fileSave = new FileIO();
                fileSave.Save(player, filePath);
            }

            player.SwitchState(new LookingState());
        }
        public MainWindow()
        {
            InitializeComponent();

            try
            {
                _fileIO = new FileIO(
                    Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    @"IISExpress\config\applicationhost.config"));
                _fileIO.FileChanged += FileChanged;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Application.Current.Shutdown();
            }
        }
Beispiel #24
0
 public WebSite CreateWebsite(FileIO fileIO, int id, string name, bool serverAutoStart,
     string applicationPath, string applicationPool, string virtualPath, string physicalPath,
     WebSite.BindingProtocol protocol, string bindingInfo)
 {
     var dirIsValid = false;
     try
     {
         dirIsValid = fileIO.Exists(physicalPath);
         var newSite = new WebSite(id, name, serverAutoStart, applicationPath, applicationPool, virtualPath,
             physicalPath, protocol, bindingInfo, dirIsValid);
         newSite.Save(fileIO);
         return newSite;
     }
     catch (Exception ex)
     {
         throw new ApplicationException(string.Format("Error creating new website: {0}", ex));
     }
 }
Beispiel #25
0
        //public enum BindingProtocol { Unknown = 0, http, ftp };
        public ObservableCollection<WebSite> GetAllWebsites(FileIO fileIO)
        {
            if (fileIO == null)
            {
                throw new ArgumentNullException("fileIO");
            }

            IEnumerable<XElement> xdoc = null;
            try
            {
                xdoc = fileIO.GetSitesSection();
            }
            catch (Exception ex)
            {
                throw new ApplicationException(
                    String.Format("Error access IIS Express applicationhost config file: {0}", ex.Message));
            }
            if (xdoc == null)
            {
                return null;
            }

            try
            {
                return new ObservableCollection<WebSite>(
                    from site in xdoc.Descendants("site")
                    select new WebSite(
                        Convert.ToInt32(site.Attribute("id").Value),
                        site.Attribute("name").Value,
                        site.Attribute("serverAutoStart") == null ? true : Convert.ToBoolean(site.Attribute("serverAutoStart").Value),
                        site.Element("application").Attribute("path").Value,
                        site.Element("application").Attribute("applicationPool") == null ? string.Empty : site.Element("application").Attribute("applicationPool").Value,
                        site.Element("application").Element("virtualDirectory").Attribute("path").Value,
                        site.Element("application").Element("virtualDirectory").Attribute("physicalPath").Value,
                        (WebSite.BindingProtocol)Enum.Parse(typeof(WebSite.BindingProtocol), site.Element("bindings").Element("binding").Attribute("protocol").Value),
                        site.Element("bindings").Element("binding").Attribute("bindingInformation").Value,
                        fileIO.Exists(site.Element("application").Element("virtualDirectory").Attribute("physicalPath").Value)));
            }
            catch (Exception ex)
            {
                throw new ApplicationException(
                    String.Format("Error parsing applicationhost config file: {0}", ex.Message));
            }
        }
        public void ContentSectionFormatterRoundTrip()
        {
            const string testValue = "Météo pour Paris, France. @€";

            var ms = new MemoryStream();
            var fio = new FileIO(ms);
            var fw = new FormattedWriter(fio);
            var wc = new WriteContext(fw);
            wc.Description = new TeaFileDescription();
            wc.Description.ContentDescription = testValue;
            ISectionFormatter f = new ContentSectionFormatter();
            f.Write(wc);
            ms.Position = 0;
            var fr = new FormattedReader(fio);
            var rc = new ReadContext(fr);
            f.Read(rc);
            rc.Description.Should().Not.Be.Null();
            rc.Description.ContentDescription.Should().Be(testValue);
        }
Beispiel #27
0
        public MainWindow()
        {
            InitializeComponent();

            Height = Properties.Settings.Default.WindowSize.Height;
            Width = Properties.Settings.Default.WindowSize.Width;
            Top = Properties.Settings.Default.WindowLocation.Y;
            Left = Properties.Settings.Default.WindowLocation.X;
            CampahStatus.SetStatus("Loading Settings", Modes.Stopped);
            settingsManager = new FileIO(TbBuyItemSelect);
            settingsManager.loadSettingsXML();

            if (File.Exists("Updater.exe"))
            {
                File.Delete("Updater.exe");
            }

            SelectProcess();
            rtb_chatlog.Document = Chatlog.Instance.ChatLog;
        }
Beispiel #28
0
 public void Initialize(MainWindow window, BackpackWindow bpwindow, ClassRaceChoiceWindow crcwindow, StatWindow swindow)
 {
     Program.main = new Main(window, bpwindow, crcwindow, swindow);
     bpwindow.itemBox.ItemsSource = Program.main.player.backpack;
     window.Title = "Realm 2: " + GetTitle();
     if (!Program.noUpdate)
     {
         //if the game needs an update show the update dialog
         FileIO fi = new FileIO();
         if (fi.checkver())
         {
             DownloadNewVersionWindow dnvw = new DownloadNewVersionWindow(window);
             dnvw.Show();
         }
     }
     string temppath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\test.exe";
     if (File.Exists(temppath))
         File.Delete(temppath);
     Program.main.write("Hello there. It looks like you're new to Realm 2.", "Black", true);
     Program.main.write("What is your name?", "SteelBlue");
     Program.main.player.backpack.Add(new Stick());
     Program.main.gm = GameState.GettingPlayerInfo;
 }
Beispiel #29
0
 public void Execute(ArgumentList arguments, TaskList tasks, TagList tags, TagFolder folder)
 {
     FileIO loader = new FileIO();
     TaskTagger tagTasks = new TaskTagger(tasks.GetTasks());
     if (arguments.GetLength() == 2)
     {
         Tag tag = new Tag(arguments.GetParameter(1));
         tags.AddTag(ref tag);
         loader.SaveTags(tags);
     }
     else
     {
         if (tagTasks.AssignTag(arguments.GetParameter(1), arguments.GetParameter(2)))
         {
             loader.SaveTasks(tagTasks.GetTasks());
             Tag tag = new Tag(arguments.GetParameter(2));
             tags.AddTag(ref tag);
             loader.SaveTags(tags);
         }
         else
             Console.WriteLine("No task with that id found to tag");
     }
 }
 public void Execute(ArgumentList arguments, TaskList tasks, TagList tags, TagFolder folder)
 {
     FileIO loader = new FileIO();
     if (arguments.GetLength() == 2)
     {
         folder.FolderName = arguments.GetParameter(1);
         loader.SaveFolder(folder);
     }
     else if (arguments.GetLength() == 3 && arguments.GetParameter(1) == "tag")
     {
         Tag toAdd = new Tag(arguments.GetParameter(2));
         folder.AddTag(ref toAdd);
         loader.SaveFolder(folder);
     }
     else if (arguments.GetLength() == 3 && arguments.GetParameter(1) == "subfolder")
     {
         TagFolder toAdd = new TagFolder(arguments.GetParameter(2));
         folder.AddSubfolder(toAdd);
         loader.SaveFolder(folder);
     }
     else if (arguments.GetLength() == 5 && arguments.GetParameter(1) == "subfolder" && arguments.GetParameter(3) == "tag")
     {
         Tag toAdd = new Tag(arguments.GetParameter(4));
         TagFolder copy = folder.GetSubfolder(arguments.GetParameter(2));
         copy.AddTag(ref toAdd);
         folder.ReplaceSubFolder(folder.GetSubfolder(arguments.GetParameter(2)), copy);
         loader.SaveFolder(folder);
     }
     else if (arguments.GetLength() == 5 && arguments.GetParameter(1) == "subfolder" && arguments.GetParameter(3) == "subfolder")
     {
         TagFolder toAdd = new TagFolder(arguments.GetParameter(4));
         TagFolder copy = folder.GetSubfolder(arguments.GetParameter(2));
         copy.AddSubfolder(toAdd);
         folder.ReplaceSubFolder(folder.GetSubfolder(arguments.GetParameter(2)), copy);
         loader.SaveFolder(folder);
     }
 }
        private async void Editor_Loading(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(CodeContent))
            {
                CodeContent = await FileIO.ReadTextAsync(await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Content.txt")));

                ButtonHighlightRange_Click(null, null);
            }

            // Ready for Code
            var languages = new Monaco.LanguagesHelper(Editor);

            var available_languages = await languages.GetLanguagesAsync();

            //Debugger.Break();

            await languages.RegisterHoverProviderAsync("csharp", (model, position) =>
            {
                // TODO: See if this can be internalized? Need to figure out the best pattern here to expose async method through WinRT, as can't use Task for 'async' language compatibility in WinRT Component...
                return(AsyncInfo.Run(async delegate(CancellationToken cancelationToken)
                {
                    var word = await model.GetWordAtPositionAsync(position);
                    if (word != null && word.Word.IndexOf("Hit", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
                    {
                        return new Hover(new string[]
                        {
                            "*Hit* - press the keys following together.",
                            "Some **more** text is here.",
                            "And a [link](https://www.github.com/)."
                        }, new Range(position.LineNumber, position.Column, position.LineNumber, position.Column + 5));
                    }

                    return null;
                }));
            });

            await languages.RegisterCompletionItemProviderAsync("csharp", new LanguageProvider());

            _myCondition = await Editor.CreateContextKeyAsync("MyCondition", false);

            await Editor.AddCommandAsync(Monaco.KeyCode.F5, async() => {
                var md = new MessageDialog("You Hit F5!");
                await md.ShowAsync();

                // Turn off Command again.
                _myCondition?.Reset();

                // Refocus on CodeEditor
                Editor.Focus(FocusState.Programmatic);
            }, _myCondition.Key);

            await Editor.AddCommandAsync(Monaco.KeyMod.CtrlCmd | Monaco.KeyCode.KEY_W, async() =>
            {
                var word = await Editor.GetModel().GetWordAtPositionAsync(await Editor.GetPositionAsync());

                if (word == null)
                {
                    var md = new MessageDialog("No Word Found.");
                    await md.ShowAsync();
                }
                else
                {
                    var md = new MessageDialog("Word: " + word.Word + "[" + word.StartColumn + ", " + word.EndColumn + "]");
                    await md.ShowAsync();
                }

                Editor.Focus(FocusState.Programmatic);
            });

            await Editor.AddCommandAsync(Monaco.KeyMod.CtrlCmd | Monaco.KeyCode.KEY_L, async() =>
            {
                var model = Editor.GetModel();
                var line  = await model.GetLineContentAsync((await Editor.GetPositionAsync()).LineNumber);
                var lines = await model.GetLinesContentAsync();
                var count = await model.GetLineCountAsync();

                var md = new MessageDialog("Current Line: " + line + "\nAll Lines [" + count + "]:\n" + string.Join("\n", lines));
                await md.ShowAsync();

                Editor.Focus(FocusState.Programmatic);
            });

            await Editor.AddCommandAsync(Monaco.KeyMod.CtrlCmd | Monaco.KeyCode.KEY_U, async() =>
            {
                var range = new Range(2, 10, 3, 8);
                var seg   = await Editor.GetModel().GetValueInRangeAsync(range);

                var md = new MessageDialog("Segment " + range.ToString() + ": " + seg);
                await md.ShowAsync();

                Editor.Focus(FocusState.Programmatic);
            });

            await Editor.AddActionAsync(new TestAction());
        }
Beispiel #32
0
        /// <summary>
        /// Writes a series of bytes to the file - does nothing in the editor
        /// </summary>
        /// <param name="bytes">The bytes to write</param>
        public void WriteBytes(byte[] bytes)
        {
#if NETFX_CORE
            FileIO.WriteBytesAsync(OriginalFile, bytes).AsTask().Wait();
#endif
        }
        /// <summary>
        /// save document as template
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="name">template name</param>
        /// <returns></returns>
        public async Task <EntryTemplate> SaveAsTemplate(IDocumentEntry entry, String name)
        {
            EntryTemplate template;

            // get the id
            int id = _list.Count + 1;

            try
            {
                CurrencyAmount amount = (CurrencyAmount)entry
                                        .GetValue(EntryTemplate.AMOUNT);
                String text = (String)entry.GetValue(EntryTemplate.TEXT);
                if (entry is VendorEntry)
                {
                    template = new EntryTemplate(_coreDriver, _mdMgmt,
                                                 EntryType.VendorEntry, id, name);
                    template.AddDefaultValue(EntryTemplate.AMOUNT, amount);
                    template.AddDefaultValue(EntryTemplate.TEXT, text);

                    Object vendor = entry.GetValue(VendorEntry.VENDOR);
                    if (vendor != null)
                    {
                        template.AddDefaultValue(VendorEntry.VENDOR, vendor);
                    }
                    Object recAcc = entry.GetValue(VendorEntry.REC_ACC);
                    if (recAcc != null)
                    {
                        template.AddDefaultValue(VendorEntry.REC_ACC, recAcc);
                    }
                    Object costAcc = entry.GetValue(VendorEntry.GL_ACCOUNT);
                    if (costAcc != null)
                    {
                        template.AddDefaultValue(VendorEntry.GL_ACCOUNT, costAcc);
                    }
                    Object businessArea = entry.GetValue(VendorEntry.BUSINESS_AREA);
                    if (businessArea != null)
                    {
                        template.AddDefaultValue(VendorEntry.BUSINESS_AREA,
                                                 businessArea);
                    }

                    this.addTemplate(template);
                }
                else if (entry is GLAccountEntry)
                {
                    template = new EntryTemplate(_coreDriver, _mdMgmt,
                                                 EntryType.GLEntry, id, name);

                    template.AddDefaultValue(EntryTemplate.AMOUNT, amount);
                    template.AddDefaultValue(EntryTemplate.TEXT, text);

                    Object recAcc = entry.GetValue(GLAccountEntry.SRC_ACCOUNT);
                    if (recAcc != null)
                    {
                        template.AddDefaultValue(GLAccountEntry.SRC_ACCOUNT, recAcc);
                    }
                    Object costAcc = entry.GetValue(GLAccountEntry.DST_ACCOUNT);
                    if (costAcc != null)
                    {
                        template.AddDefaultValue(GLAccountEntry.DST_ACCOUNT,
                                                 costAcc);
                    }

                    this.addTemplate(template);
                }
                else if (entry is CustomerEntry)
                {
                    template = new EntryTemplate(_coreDriver, _mdMgmt,
                                                 EntryType.CustomerEntry, id, name);

                    template.AddDefaultValue(EntryTemplate.AMOUNT, amount);
                    template.AddDefaultValue(EntryTemplate.TEXT, text);

                    Object customer = entry.GetValue(CustomerEntry.CUSTOMER);
                    if (customer != null)
                    {
                        template.AddDefaultValue(CustomerEntry.CUSTOMER, customer);
                    }
                    Object recAcc = entry.GetValue(CustomerEntry.REC_ACC);
                    if (recAcc != null)
                    {
                        template.AddDefaultValue(CustomerEntry.REC_ACC, recAcc);
                    }
                    Object costAcc = entry.GetValue(CustomerEntry.GL_ACCOUNT);
                    if (costAcc != null)
                    {
                        template.AddDefaultValue(CustomerEntry.GL_ACCOUNT, costAcc);
                    }

                    this.addTemplate(template);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception e)
            {
                _coreDriver.logDebugInfo(this.GetType(), 72, e.Message,
                                         MessageType.ERRO);
                throw new SystemException(e);
            }

            // save
            await _coreDriver.MdMgmt.StoreAsync();

            String filePath = String.Format("%s/%s", _coreDriver.RootFolder.Path,
                                            FILE_NAME);
            StorageFile file = await _coreDriver.RootFolder.CreateFileAsync(
                FILE_NAME, CreationCollisionOption.OpenIfExists);

            XDocument xdoc = this.ToXMLDoc();

            await FileIO.WriteTextAsync(file, xdoc.ToString());

            return(template);
        }
Beispiel #34
0
        private async Task <bool> GetMediaDataAsync(string path)
        {
            if (this._groups.Count != 0)
            {
                return(false);
            }
            string jsonText = string.Empty;

            if (string.IsNullOrEmpty(path))
            {
                // load the default data
                //If retrieving json from web failed then use embedded json data file.
                if (string.IsNullOrEmpty(jsonText))
                {
                    Uri dataUri = new Uri("ms-appx:///DataModel/MediaData.json");

                    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);

                    jsonText = await FileIO.ReadTextAsync(file);

                    MediaDataPath = "ms-appx:///DataModel/MediaData.json";
                }
            }
            else
            {
                if (path.StartsWith("ms-appx://"))
                {
                    Uri dataUri = new Uri(path);

                    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);

                    jsonText = await FileIO.ReadTextAsync(file);

                    MediaDataPath = path;
                }
                else if (path.StartsWith("http://"))
                {
                    try
                    {
                        //Download the json file from the server to configure what content will be dislayed.
                        //You can also modify the local MediaData.json file and delete this code block to test
                        //the local json file
                        string MediaDataFile = path;
                        Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                        filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
                        Windows.Web.Http.HttpClient http = new Windows.Web.Http.HttpClient(filter);
                        Uri httpUri = new Uri(MediaDataFile);
                        jsonText = await http.GetStringAsync(httpUri);

                        MediaDataPath = MediaDataFile;
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message);
                    }
                }
                else
                {
                    try
                    {
                        //Download the json file from the server to configure what content will be dislayed.
                        //You can also modify the local MediaData.json file and delete this code block to test
                        //the local json file
                        string      MediaDataFile = path;
                        StorageFile file;
                        file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path);

                        if (file != null)
                        {
                            jsonText = await FileIO.ReadTextAsync(file);

                            MediaDataPath = MediaDataFile;
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message);
                    }
                }
            }

            if (string.IsNullOrEmpty(jsonText))
            {
                return(false);
            }

            try
            {
                JsonObject jsonObject = JsonObject.Parse(jsonText);
                JsonArray  jsonArray  = jsonObject["Groups"].GetArray();

                foreach (JsonValue groupValue in jsonArray)
                {
                    JsonObject     groupObject = groupValue.GetObject();
                    MediaDataGroup group       = new MediaDataGroup(groupObject["UniqueId"].GetString(),
                                                                    groupObject["Title"].GetString(),
                                                                    groupObject["Category"].GetString(),
                                                                    groupObject["ImagePath"].GetString(),
                                                                    groupObject["Description"].GetString());

                    foreach (JsonValue itemValue in groupObject["Items"].GetArray())
                    {
                        JsonObject itemObject = itemValue.GetObject();
                        long       timeValue  = 0;
                        group.Items.Add(new MediaItem(itemObject["UniqueId"].GetString(),
                                                      itemObject["Comment"].GetString(),
                                                      itemObject["Title"].GetString(),
                                                      itemObject["ImagePath"].GetString(),
                                                      itemObject["Description"].GetString(),
                                                      itemObject["Content"].GetString(),
                                                      itemObject["PosterContent"].GetString(),
                                                      (long.TryParse(itemObject["Start"].GetString(), out timeValue) ? timeValue : 0),
                                                      (long.TryParse(itemObject["Duration"].GetString(), out timeValue) ? timeValue : 0),
                                                      itemObject["PlayReadyUrl"].GetString(),
                                                      itemObject["PlayReadyCustomData"].GetString(),
                                                      itemObject["BackgroundAudio"].GetBoolean()));
                    }
                    this.Groups.Add(group);
                    return(true);
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message);
            }
            return(false);
        }
        public async Task When_GetFileFromApplicationUriAsync_Image_Nested()
        {
            var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Icons/menu.png"));

            Assert.IsTrue((await FileIO.ReadBufferAsync(file)).Length > 0);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void importFigatreeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (actionList.SelectedItem is Action a)
            {
                var f = FileIO.OpenFile("Supported Formats |*.dat;*.anim");

                HSDRawFile file;

                // if it's a maya anim then convert to figatree and set the symbol
                if (f.ToLower().EndsWith(".anim"))
                {
                    var anim = Converters.ConvMayaAnim.ImportFromMayaAnim(f, null);

                    file = new HSDRawFile(f);
                    file.Roots.Add(new HSDRootNode()
                    {
                        Name = a.Symbol,
                        Data = anim.ToFigaTree(0.01f)
                    });
                }
                else
                {
                    // just load dat normally
                    try
                    {
                        file = new HSDRawFile(f);
                    }
                    catch
                    {
                        return;
                    }
                }

                // check if figatree data is found
                if (file == null || file.Roots.Count > 0 && file.Roots[0].Data is HSD_FigaTree tree)
                {
                    //grab symbol
                    var symbol = file.Roots[0].Name;

                    //check if symbol exists and ok to overwrite
                    if (AJManager.GetAnimationData(symbol) != null)
                    {
                        if (MessageBox.Show($"Symbol \"{symbol}\" already exists.\nIs it okay to overwrite?", "Overwrite Symbol", MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                        {
                            return;
                        }
                    }

                    // set animation data
                    using (MemoryStream stream = new MemoryStream())
                    {
                        file.Save(stream);
                        AJManager.SetAnimation(symbol, stream.ToArray());
                    }

                    // set action symbol
                    a.Symbol = symbol;

                    // reselect action
                    LoadAnimation(symbol);

                    //
                    actionList.Invalidate();
                }
            }
        }
Beispiel #37
0
        /// <summary>
        /// Writes a string to the file - does nothing in the editor
        /// </summary>
        /// <param name="text">The string to write</param>
        public void WriteText(string text)
        {
#if NETFX_CORE
            FileIO.WriteTextAsync(OriginalFile, text).AsTask().Wait();
#endif
        }
        public async Task <WSAFacebookLoginResult> Login(List <string> permissions)
        {
            WSAFacebookLoginResult loginResult = new WSAFacebookLoginResult();

            try
            {
                Logout(false);

                string requestPermissions = "public_profile";

                if (permissions != null && permissions.Count > 0)
                {
                    requestPermissions = string.Join(",", permissions);
                }

                string accessToken = string.Empty;

#if UNITY_WSA_10_0
                Uri appCallbackUri = new Uri("ms-app://" + _packageSID);

                Uri requestUri = new Uri(
                    string.Format("https://www.facebook.com/dialog/oauth?client_id={0}&response_type=token&redirect_uri={1}&scope={2}",
                                  _facebookAppId, appCallbackUri, requestPermissions));

                WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, appCallbackUri);

                if (result.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    Match match = Regex.Match(result.ResponseData, "access_token=(.+)&");

                    accessToken = match.Groups[1].Value;
                }
#else
                if (_dxSwapChainPanel != null)
                {
                    string requestUri = string.Format("https://www.facebook.com/dialog/oauth?client_id={0}&response_type=token&redirect_uri={1}&scope={2}",
                                                      _facebookAppId, WSAFacebookConstants.WebRedirectUri, requestPermissions);

                    FacebookLogin dialog = new FacebookLogin(Screen.width, Screen.height);

                    accessToken = await dialog.Show(requestUri, WSAFacebookConstants.LoginDialogResponseUri, _dxSwapChainPanel);
                }
#endif

                if (!string.IsNullOrEmpty(accessToken))
                {
                    _accessToken = accessToken;
                    IsLoggedIn   = true;

                    try
                    {
                        StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(_savedDataFilename, CreationCollisionOption.ReplaceExisting);

                        await FileIO.WriteTextAsync(file, _accessToken);
                    }
                    catch
                    {
                    }
                }
            }
            catch (Exception e)
            {
                IsLoggedIn = false;
                loginResult.ErrorMessage = e.Message;
            }

            loginResult.Success     = IsLoggedIn;
            loginResult.AccessToken = !string.IsNullOrWhiteSpace(_accessToken) ? _accessToken : null;

            return(loginResult);
        }
Beispiel #39
0
        /// <summary>
        /// Generic function to run a FFMPEG command handle common errors related to FFMPEG conversion
        /// </summary>
        /// <param name="cmdParams">Command parameters to pass to ffmpeg</param>
        /// <param name="outputFile">Exact name of the output file as it appears in the command paramters (including quotes if required)</param>
        /// <param name="checkZeroOutputFileSize">If true, will check output file size and function will return false if the size is 0 or file doesn't exist, false to ignore output filesize and presence</param>
        /// <param name="ffmpegExecutedObject">Returns a pointer to the final executed ffmpeg object</param>
        /// <returns>True if successful</returns>
        public static bool FFMpegExecuteAndHandleErrors(string cmdParams, JobStatus jobStatus, Log jobLog, string outputFile, bool checkZeroOutputFileSize, out FFmpeg ffmpegExecutedObject)
        {
            FFmpeg ffmpeg = new FFmpeg(cmdParams, jobStatus, jobLog);

            ffmpeg.Run();

            // Check if it's a h264_mp4toannexb error, when converting H.264 video to MPEGTS format this can sometimes be an issue
            if (!ffmpeg.Success && ffmpeg.H264MP4ToAnnexBError)
            {
                jobLog.WriteEntry("h264_mp4toannexb error, retying and setting bitstream flag", Log.LogEntryType.Warning);

                // -bsf h264_mp4toannexb is required when this error occurs, put it just before the output filename
                cmdParams = cmdParams.Insert(cmdParams.IndexOf(outputFile), "-bsf h264_mp4toannexb ");
                ffmpeg    = new FFmpeg(cmdParams, jobStatus, jobLog);
                ffmpeg.Run();
            }

            // Check if it's a aac_adtstoasc error, when converting AAC Audio from MPEGTS to MP4 format this can sometimes be an issue
            if (!ffmpeg.Success && ffmpeg.AACADTSToASCError)
            {
                jobLog.WriteEntry("aac_adtstoasc error, retying and setting bitstream flag", Log.LogEntryType.Warning);

                // -bsf aac_adtstoasc is required when this error occurs, put it just before the output filename
                cmdParams = cmdParams.Insert(cmdParams.IndexOf(outputFile), "-bsf:a aac_adtstoasc ");
                ffmpeg    = new FFmpeg(cmdParams, jobStatus, jobLog);
                ffmpeg.Run();
            }

            // Check if we are asked to check for output filesize only here (generic errors)
            // Otherwise it might an error related to genpts (check if we ran the previous ffmpeg related to h264_mp4toannexb and it succeded) - genpts is done after trying to fix other issues
            if (checkZeroOutputFileSize)
            {
                jobLog.WriteEntry("Checking output file size [KB] -> " + (Util.FileIO.FileSize(outputFile) / 1024).ToString("N", System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
            }

            if ((!ffmpeg.Success || (checkZeroOutputFileSize ? (FileIO.FileSize(outputFile) <= 0) : false)) && !cmdParams.Contains("genpts")) // Possible that some combinations used prior to calling this already have genpts in the command line
            {
                jobLog.WriteEntry("Ffmpeg conversion failed, retying using GenPts", Log.LogEntryType.Warning);

                // genpt is required sometimes when -ss is specified before the inputs file, see ffmpeg ticket #2054
                cmdParams = "-fflags +genpts " + cmdParams;
                ffmpeg    = new FFmpeg(cmdParams, jobStatus, jobLog);
                ffmpeg.Run();
            }

            // Check again post genpts if it's a h264_mp4toannexb error (if not already done), when converting H.264 video to MPEGTS format this can sometimes be an issue
            if (!ffmpeg.Success && ffmpeg.H264MP4ToAnnexBError && !cmdParams.Contains("h264_mp4toannexb"))
            {
                jobLog.WriteEntry("H264MP4ToAnnexBError error, retying and setting bitstream flag", Log.LogEntryType.Warning);

                // -bsf h264_mp4toannexb is required when this error occurs, put it just before the output filename
                cmdParams = cmdParams.Insert(cmdParams.IndexOf(outputFile), "-bsf h264_mp4toannexb ");
                ffmpeg    = new FFmpeg(cmdParams, jobStatus, jobLog);
                ffmpeg.Run();
            }

            // Check again post genpts if it's a aac_adtstoasc error (if not already done), when converting AAC Audio from MPEGTS to MP4 format this can sometimes be an issue
            if (!ffmpeg.Success && ffmpeg.AACADTSToASCError && !cmdParams.Contains("aac_adtstoasc"))
            {
                jobLog.WriteEntry("aac_adtstoasc error, retying and setting bitstream flag", Log.LogEntryType.Warning);

                // -bsf aac_adtstoasc is required when this error occurs, put it just before the output filename
                cmdParams = cmdParams.Insert(cmdParams.IndexOf(outputFile), "-bsf:a aac_adtstoasc ");
                ffmpeg    = new FFmpeg(cmdParams, jobStatus, jobLog);
                ffmpeg.Run();
            }

            ffmpegExecutedObject = ffmpeg; // Set the return object to the final run ffmpeg object

            jobLog.WriteEntry("FFMpeg output file size [KB] -> " + (Util.FileIO.FileSize(outputFile) / 1024).ToString("N", System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);

            return(ffmpeg.Success && (checkZeroOutputFileSize ? (FileIO.FileSize(outputFile) > 0) : true));
        }
Beispiel #40
0
 private async Task UpdateCurrentPackageInfoAsync(JObject packageInfo)
 {
     await FileIO.WriteTextAsync(await GetStatusFileAsync().ConfigureAwait(false), JsonConvert.SerializeObject(packageInfo)).AsTask().ConfigureAwait(false);
 }
Beispiel #41
0
        private static async void SerializeNotesFileAsync(string notesJsonString, string fileName)
        {
            StorageFile localFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(localFile, notesJsonString);
        }
Beispiel #42
0
        internal async Task DownloadPackageAsync(JObject updatePackage, string expectedBundleFileName, Progress <HttpProgress> downloadProgress)
        {
            // Using its hash, get the folder where the new update will be saved
            StorageFolder codePushFolder = await GetCodePushFolderAsync().ConfigureAwait(false);

            var           newUpdateHash   = (string)updatePackage[CodePushConstants.PackageHashKey];
            StorageFolder newUpdateFolder = await GetPackageFolderAsync(newUpdateHash, false).ConfigureAwait(false);

            if (newUpdateFolder != null)
            {
                // This removes any stale data in newUpdateFolder that could have been left
                // uncleared due to a crash or error during the download or install process.
                await newUpdateFolder.DeleteAsync().AsTask().ConfigureAwait(false);
            }

            newUpdateFolder = await GetPackageFolderAsync(newUpdateHash, true).ConfigureAwait(false);

            StorageFile newUpdateMetadataFile = await newUpdateFolder.CreateFileAsync(CodePushConstants.PackageFileName).AsTask().ConfigureAwait(false);

            var         downloadUrlString = (string)updatePackage[CodePushConstants.DownloadUrlKey];
            StorageFile downloadFile      = await GetDownloadFileAsync().ConfigureAwait(false);

            var downloadUri = new Uri(downloadUrlString);

            // Download the file and send progress event asynchronously
            var request = new HttpRequestMessage(HttpMethod.Get, downloadUri);
            var client  = new HttpClient();
            var cancellationTokenSource = new CancellationTokenSource();

            using (HttpResponseMessage response = await client.SendRequestAsync(request).AsTask(cancellationTokenSource.Token, downloadProgress).ConfigureAwait(false))
                using (IInputStream inputStream = await response.Content.ReadAsInputStreamAsync().AsTask().ConfigureAwait(false))
                    using (IRandomAccessStream downloadFileStream = await downloadFile.OpenAsync(FileAccessMode.ReadWrite).AsTask().ConfigureAwait(false))
                    {
                        await RandomAccessStream.CopyAsync(inputStream, downloadFileStream).AsTask().ConfigureAwait(false);
                    }

            try
            {
                // Unzip the downloaded file and then delete the zip
                StorageFolder unzippedFolder = await CreateUnzippedFolderAsync().ConfigureAwait(false);

                ZipFile.ExtractToDirectory(downloadFile.Path, unzippedFolder.Path);
                await downloadFile.DeleteAsync().AsTask().ConfigureAwait(false);

                // Merge contents with current update based on the manifest
                StorageFile diffManifestFile = (StorageFile)await unzippedFolder.TryGetItemAsync(CodePushConstants.DiffManifestFileName).AsTask().ConfigureAwait(false);

                if (diffManifestFile != null)
                {
                    StorageFolder currentPackageFolder = await GetCurrentPackageFolderAsync().ConfigureAwait(false);

                    if (currentPackageFolder == null)
                    {
                        throw new InvalidDataException("Received a diff update, but there is no current version to diff against.");
                    }

                    await UpdateUtils.CopyNecessaryFilesFromCurrentPackageAsync(diffManifestFile, currentPackageFolder, newUpdateFolder).ConfigureAwait(false);

                    await diffManifestFile.DeleteAsync().AsTask().ConfigureAwait(false);
                }

                await FileUtils.MergeFoldersAsync(unzippedFolder, newUpdateFolder).ConfigureAwait(false);

                await unzippedFolder.DeleteAsync().AsTask().ConfigureAwait(false);

                // For zip updates, we need to find the relative path to the jsBundle and save it in the
                // metadata so that we can find and run it easily the next time.
                string relativeBundlePath = await UpdateUtils.FindJSBundleInUpdateContentsAsync(newUpdateFolder, expectedBundleFileName).ConfigureAwait(false);

                if (relativeBundlePath == null)
                {
                    throw new InvalidDataException("Update is invalid - A JS bundle file named \"" + expectedBundleFileName + "\" could not be found within the downloaded contents. Please check that you are releasing your CodePush updates using the exact same JS bundle file name that was shipped with your app's binary.");
                }
                else
                {
                    if (diffManifestFile != null)
                    {
                        // TODO verify hash for diff update
                        // CodePushUpdateUtils.verifyHashForDiffUpdate(newUpdateFolderPath, newUpdateHash);
                    }

                    updatePackage[CodePushConstants.RelativeBundlePathKey] = relativeBundlePath;
                }
            }
            catch (InvalidDataException)
            {
                // Downloaded file is not a zip, assume it is a jsbundle
                await downloadFile.RenameAsync(expectedBundleFileName).AsTask().ConfigureAwait(false);

                await downloadFile.MoveAsync(newUpdateFolder).AsTask().ConfigureAwait(false);
            }

            /*TODO: ZipFile.ExtractToDirectory is not reliable and throws exceptions if:
             * - path is too long
             * it needs to be handled
             */

            // Save metadata to the folder
            await FileIO.WriteTextAsync(newUpdateMetadataFile, JsonConvert.SerializeObject(updatePackage)).AsTask().ConfigureAwait(false);
        }
Beispiel #43
0
        private async Task SaveMessage(string message)
        {
            try
            {
                var tempFolder = ApplicationData.Current.TemporaryFolder;

                var raygunFolder = await tempFolder.CreateFolderAsync("RaygunIO", CreationCollisionOption.OpenIfExists).AsTask().ConfigureAwait(false);

                int number = 1;
                while (true)
                {
                    bool exists;

                    try
                    {
                        await raygunFolder.GetFileAsync("RaygunErrorMessage" + number + ".txt").AsTask().ConfigureAwait(false);

                        exists = true;
                    }
                    catch (FileNotFoundException) {
                        exists = false;
                    }

                    if (!exists)
                    {
                        string nextFileName = "RaygunErrorMessage" + (number + 1) + ".txt";

                        StorageFile nextFile = null;
                        try
                        {
                            nextFile = await raygunFolder.GetFileAsync(nextFileName).AsTask().ConfigureAwait(false);

                            await nextFile.DeleteAsync().AsTask().ConfigureAwait(false);
                        }
                        catch (FileNotFoundException) { }

                        break;
                    }

                    number++;
                }

                if (number == 11)
                {
                    try
                    {
                        StorageFile firstFile = await raygunFolder.GetFileAsync("RaygunErrorMessage1.txt").AsTask().ConfigureAwait(false);

                        await firstFile.DeleteAsync().AsTask().ConfigureAwait(false);
                    }
                    catch (FileNotFoundException) { }
                }

                var file = await raygunFolder.CreateFileAsync("RaygunErrorMessage" + number + ".txt").AsTask().ConfigureAwait(false);

                await FileIO.WriteTextAsync(file, message).AsTask().ConfigureAwait(false);

                Debug.WriteLine("Saved message: " + "RaygunIO\\RaygunErrorMessage" + number + ".txt");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Error saving message to isolated storage {0}", ex.Message));
            }
        }
Beispiel #44
0
        protected override async void OnActivated(IActivatedEventArgs args)
        {
            if (args is ProtocolActivatedEventArgs protocolActivated)
            {
                if (protocolActivated.Uri == new Uri("ftcmd://fluent.terminal?focus"))
                {
                    await ShowOrCreateWindow(protocolActivated.ViewSwitcher);

                    return;
                }

                MainViewModel mainViewModel = null;
                // IApplicationView to use for creating view models
                IApplicationView applicationView;

                if (_alreadyLaunched)
                {
                    applicationView =
                        (_mainViewModels.FirstOrDefault(o => o.ApplicationView.Id == _activeWindowId) ??
                         _mainViewModels.Last()).ApplicationView;
                }
                else
                {
                    // App wasn't launched before double clicking a shortcut, so we have to create a window
                    // in order to be able to communicate with user.
                    mainViewModel = _container.Resolve <MainViewModel>();

                    await CreateMainView(typeof(MainPage), mainViewModel, true);

                    applicationView = mainViewModel.ApplicationView;
                }

                bool isSsh;

                try
                {
                    isSsh = SshConnectViewModel.CheckScheme(protocolActivated.Uri);
                }
                catch (Exception ex)
                {
                    await new MessageDialog(
                        $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {ex.Message}",
                        "Invalid Link")
                    .ShowAsync();

                    mainViewModel?.ApplicationView.TryClose();

                    return;
                }

                if (isSsh)
                {
                    SshConnectViewModel vm;

                    try
                    {
                        vm = SshConnectViewModel.ParseUri(protocolActivated.Uri, _settingsService, applicationView,
                                                          _trayProcessCommunicationService, _container.Resolve <IFileSystemService>(),
                                                          _container.Resolve <ApplicationDataContainers>().HistoryContainer);
                    }
                    catch (Exception ex)
                    {
                        await new MessageDialog(
                            $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {ex.Message}",
                            "Invalid Link")
                        .ShowAsync();

                        mainViewModel?.ApplicationView.TryClose();

                        return;
                    }

                    if (_applicationSettings.AutoFallbackToWindowsUsernameInLinks && string.IsNullOrEmpty(vm.Username))
                    {
                        vm.Username = await _trayProcessCommunicationService.GetUserName();
                    }

                    var error = await vm.AcceptChangesAsync(true);

                    SshProfile profile = (SshProfile)vm.Model;

                    if (!string.IsNullOrEmpty(error))
                    {
                        // Link is valid, but incomplete (i.e. username missing), so we need to show dialog.
                        profile = await _dialogService.ShowSshConnectionInfoDialogAsync(profile);

                        if (profile == null)
                        {
                            // User clicked "Cancel" in the dialog.
                            mainViewModel?.ApplicationView.TryClose();

                            return;
                        }
                    }

                    if (mainViewModel == null)
                    {
                        await CreateTerminal(profile, _applicationSettings.NewTerminalLocation, protocolActivated.ViewSwitcher);
                    }
                    else
                    {
                        await mainViewModel.AddTerminalAsync(profile);
                    }

                    return;
                }

                if (CommandProfileProviderViewModel.CheckScheme(protocolActivated.Uri))
                {
                    CommandProfileProviderViewModel vm;

                    try
                    {
                        vm = CommandProfileProviderViewModel.ParseUri(protocolActivated.Uri, _settingsService,
                                                                      applicationView, _trayProcessCommunicationService,
                                                                      _container.Resolve <ICommandHistoryService>());
                    }
                    catch (Exception ex)
                    {
                        await new MessageDialog(
                            $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {ex.Message}",
                            "Invalid Link")
                        .ShowAsync();

                        mainViewModel?.ApplicationView.TryClose();

                        return;
                    }

                    var error = await vm.AcceptChangesAsync(true);

                    var profile = vm.Model;

                    if (!string.IsNullOrEmpty(error))
                    {
                        // Link is valid, but incomplete, so we need to show dialog.
                        profile = await _dialogService.ShowCustomCommandDialogAsync(profile);

                        if (profile == null)
                        {
                            // User clicked "Cancel" in the dialog.
                            mainViewModel?.ApplicationView.TryClose();

                            return;
                        }
                    }

                    if (mainViewModel == null)
                    {
                        await CreateTerminal(profile, _applicationSettings.NewTerminalLocation, protocolActivated.ViewSwitcher);
                    }
                    else
                    {
                        await mainViewModel.AddTerminalAsync(profile);
                    }
                    return;
                }

                await new MessageDialog(
                    $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {protocolActivated.Uri}",
                    "Invalid Link")
                .ShowAsync();

                mainViewModel?.ApplicationView.TryClose();

                return;
            }

            if (args is CommandLineActivatedEventArgs commandLineActivated)
            {
                var arguments = commandLineActivated.Operation.Arguments;
                if (string.IsNullOrWhiteSpace(arguments))
                {
                    arguments = "new";
                }

                _commandLineParser.ParseArguments(SplitArguments(arguments), typeof(NewVerb), typeof(RunVerb), typeof(SettingsVerb)).WithParsed(async verb =>
                {
                    if (verb is SettingsVerb settingsVerb)
                    {
                        if (!settingsVerb.Import && !settingsVerb.Export)
                        {
                            await ShowSettings().ConfigureAwait(true);
                        }
                        else if (settingsVerb.Export)
                        {
                            var exportFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("config.json", CreationCollisionOption.OpenIfExists);

                            var settings = _settingsService.ExportSettings();
                            await FileIO.WriteTextAsync(exportFile, settings);
                            await new MessageDialog($"{I18N.Translate("SettingsExported")} {exportFile.Path}").ShowAsync();
                        }
                        else if (settingsVerb.Import)
                        {
                            var file    = await ApplicationData.Current.LocalFolder.GetFileAsync("config.json");
                            var content = await FileIO.ReadTextAsync(file);
                            _settingsService.ImportSettings(content);
                            await new MessageDialog($"{I18N.Translate("SettingsImported")} {file.Path}").ShowAsync();
                        }
                    }
                    else if (verb is NewVerb newVerb)
                    {
                        var profile = default(ShellProfile);
                        if (!string.IsNullOrWhiteSpace(newVerb.Profile))
                        {
                            profile = _settingsService.GetShellProfiles().FirstOrDefault(x => x.Name.Equals(newVerb.Profile, StringComparison.CurrentCultureIgnoreCase));
                        }

                        if (profile == null)
                        {
                            profile = _settingsService.GetDefaultShellProfile();
                        }

                        if (!string.IsNullOrWhiteSpace(newVerb.Directory) && newVerb.Directory != ".")
                        {
                            profile.WorkingDirectory = newVerb.Directory;
                        }
                        else
                        {
                            profile.WorkingDirectory = commandLineActivated.Operation.CurrentDirectoryPath;
                        }

                        var location = newVerb.Target == Target.Default ? _applicationSettings.NewTerminalLocation
                            : newVerb.Target == Target.Tab ? NewTerminalLocation.Tab
                            : NewTerminalLocation.Window;

                        await CreateTerminal(profile, location).ConfigureAwait(true);
                    }
                    else if (verb is RunVerb runVerb)
                    {
                        var profile = new ShellProfile
                        {
                            Id               = Guid.Empty,
                            Location         = null,
                            Arguments        = runVerb.Command,
                            WorkingDirectory = runVerb.Directory
                        };

                        if (!string.IsNullOrWhiteSpace(runVerb.Theme))
                        {
                            var theme = _settingsService.GetThemes().FirstOrDefault(x => x.Name.Equals(runVerb.Theme, StringComparison.CurrentCultureIgnoreCase));
                            if (theme != null)
                            {
                                profile.TerminalThemeId = theme.Id;
                            }
                        }

                        if (string.IsNullOrWhiteSpace(profile.WorkingDirectory))
                        {
                            profile.WorkingDirectory = commandLineActivated.Operation.CurrentDirectoryPath;
                        }

                        var location = runVerb.Target == Target.Default ? _applicationSettings.NewTerminalLocation
                            : runVerb.Target == Target.Tab ? NewTerminalLocation.Tab
                            : NewTerminalLocation.Window;

                        await CreateTerminal(profile, location).ConfigureAwait(true);
                    }
                });
            }
        }
Beispiel #45
0
        private async void getQuoteButton_Click(object sender, RoutedEventArgs e)
        {
            string        prices        = "60,70,80,40,50,60,30,30,40";
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile   storageFile   = await storageFolder.CreateFileAsync("rushOrderPrices.txt", CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(storageFile, prices);

            string rushOrderPriceRaw = await FileIO.ReadTextAsync(storageFile);

            string[] rushOrderArray = rushOrderPriceRaw.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            customerName.Background = new SolidColorBrush(Colors.White);
            deskWidth.Background    = new SolidColorBrush(Colors.White);
            deskDepth.Background    = new SolidColorBrush(Colors.White);

            if (customerName.Text.Contains(',') || String.IsNullOrEmpty(customerName.Text))
            {
                customerName.Background = new SolidColorBrush(Colors.Red);
                var msg = new MessageDialog("Customer name must not be empty");
                await msg.ShowAsync();
            }
            else if (!Regex.IsMatch(deskWidth.Text, "^[0-9]*$"))
            {
                var msg = new MessageDialog("Width must only contain numbers.");
                deskWidth.Background = new SolidColorBrush(Colors.Red);
                await msg.ShowAsync();
            }
            else if (!Regex.IsMatch(deskDepth.Text, "^[0-9]*$"))
            {
                var msg = new MessageDialog("Depth must only contain numbers.");
                deskDepth.Background = new SolidColorBrush(Colors.Red);
                await msg.ShowAsync();
            }
            else
            {
                if (int.Parse(deskWidth.Text) < 24 || int.Parse(deskWidth.Text) > 96)
                {
                    var msg = new MessageDialog("Width must be between 24 and 96");
                    deskWidth.Background = new SolidColorBrush(Colors.Red);
                    await msg.ShowAsync();
                }
                else if (int.Parse(deskDepth.Text) < 12 || int.Parse(deskDepth.Text) > 48)
                {
                    var msg = new MessageDialog("Depth must be between 12 and 48");
                    deskDepth.Background = new SolidColorBrush(Colors.Red);
                    await msg.ShowAsync();
                }
                else
                {
                    Desk desk = new Desk();
                    desk.Width        = int.Parse(deskWidth.Text);
                    desk.Depth        = int.Parse(deskDepth.Text);
                    desk.Drawers      = (int)numberOfDrawers.Value;
                    desk.DeskMaterial = deskMaterial.SelectedItem.ToString();
                    DeskQuote deskQuote = new DeskQuote(desk);
                    deskQuote.RushOrderPriceArray = rushOrderArray;
                    deskQuote.CustomerName        = customerName.Text;
                    deskQuote.QuoteDate           = DateTime.Now.ToString("MM/dd/yyyy");
                    deskQuote.QuotePrice          = deskQuote.GetQuote();

                    if (rushOrderCheck.IsChecked == true)
                    {
                        deskQuote.RushOrder = ((KeyValuePair <string, int>)rushOrderDaysBox.SelectedValue).Value;
                    }
                    else
                    {
                        deskQuote.RushOrder = 14;
                    }

                    //Navigate to new page
                    this.Frame.Navigate(typeof(DisplayQuote), deskQuote);
                }
            }
        }
Beispiel #46
0
        private async void SaveFileKatalogTovarov_Click(object sender, RoutedEventArgs e)
        {
            Progress.IsActive = true;
            var savePicker4 = new Windows.Storage.Pickers.FileSavePicker();

            savePicker4.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            // Поле выбора типа файла в диалоге
            savePicker4.FileTypeChoices.Add("Файл данных скриптов футера ", new List <string>()
            {
                ".footerscripts"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker4.SuggestedFileName = "footer";
            //
            Windows.Storage.StorageFile Myfile4 = await savePicker4.PickSaveFileAsync();

            if (Myfile4 != null)
            {
                // Prevent updates to the remote version of the file until
                // we finish making changes and call CompleteUpdatesAsync.
                Windows.Storage.CachedFileManager.DeferUpdates(Myfile4);
                // write to file
                //await Windows.Storage.FileIO.WriteTextAsync(file, file.Name); //запись в файл имени



                await FileIO.WriteTextAsync(Myfile4, TextBoxSTYLEFooter.Text + "¶" + TextBoxCODEFooter.Text + "¶" +

                                            TextBoxFTPServer.Text + "¶" +
                                            TextBoxFTPUser.Text + "¶" +
                                            TextBoxFTPPass.Password + "¶");



                // Let Windows know that we're finished changing the file so
                // the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                Windows.Storage.Provider.FileUpdateStatus status =
                    await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(Myfile4);

                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    string text1 = await Windows.Storage.FileIO.ReadTextAsync(Myfile4);

                    string text02 = text1.Replace("\r\n", "  "); string text002 = text02.Replace("\n", "  "); string text2 = text002.Replace("\r", "  ");

                    await FileIO.WriteTextAsync(Myfile4, text2);

                    this.StatusFile.Text = "Файл данных скриптов футера " + Myfile4.Name + " успешно сохранен.";
                    Progress.IsActive    = false;

                    var messagedialog = new MessageDialog("Файл данных скриптов футера " + Myfile4.Name + " успешно сохранен.");
                    messagedialog.Commands.Add(new UICommand("Ok"));
                    await messagedialog.ShowAsync();
                }
                else
                {
                    this.StatusFile.Text = "Не удалось сохранить файл данных скриптов футера " + Myfile4.Name + ".";
                    Progress.IsActive    = false;

                    var messagedialog = new MessageDialog("Не удалось сохранить файл данных скриптов футера " + Myfile4.Name + ".");
                    messagedialog.Commands.Add(new UICommand("Ok"));
                    await messagedialog.ShowAsync();
                }
            }
            else
            {
                this.StatusFile.Text = "Операция записи файла данных скриптов футера была прервана.";
                Progress.IsActive    = false;

                var messagedialog = new MessageDialog("Операция записи файла данных скриптов футера была прервана.");
                messagedialog.Commands.Add(new UICommand("Ok"));
                await messagedialog.ShowAsync();
            }
            Progress.IsActive = false;
        }
Beispiel #47
0
        private async Task GetControlInfoDataAsync()
        {
            lock (_lock)
            {
                if (this.Groups.Count() != 0)
                {
                    return;
                }
            }

            Uri dataUri = new Uri("ms-appx:///DataModel/ControlInfoData.json");

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);

            string jsonText = await FileIO.ReadTextAsync(file);

            JsonObject jsonObject = JsonObject.Parse(jsonText);
            JsonArray  jsonArray  = jsonObject["Groups"].GetArray();

            lock (_lock)
            {
                foreach (JsonValue groupValue in jsonArray)
                {
                    JsonObject           groupObject = groupValue.GetObject();
                    ControlInfoDataGroup group       = new ControlInfoDataGroup(groupObject["UniqueId"].GetString(),
                                                                                groupObject["Title"].GetString(),
                                                                                groupObject["Subtitle"].GetString(),
                                                                                groupObject["ImagePath"].GetString(),
                                                                                groupObject["Description"].GetString());

                    foreach (JsonValue itemValue in groupObject["Items"].GetArray())
                    {
                        JsonObject itemObject = itemValue.GetObject();

                        string badgeString = null;

                        bool isNew     = itemObject.ContainsKey("IsNew") ? itemObject["IsNew"].GetBoolean() : false;
                        bool isUpdated = itemObject.ContainsKey("IsUpdated") ? itemObject["IsUpdated"].GetBoolean() : false;
                        bool isPreview = itemObject.ContainsKey("IsPreview") ? itemObject["IsPreview"].GetBoolean() : false;

                        if (isNew)
                        {
                            badgeString = "New";
                        }
                        else if (isUpdated)
                        {
                            badgeString = "Updated";
                        }
                        else if (isPreview)
                        {
                            badgeString = "Preview";
                        }

                        var item = new ControlInfoDataItem(itemObject["UniqueId"].GetString(),
                                                           itemObject["Title"].GetString(),
                                                           itemObject["Subtitle"].GetString(),
                                                           itemObject["ImagePath"].GetString(),
                                                           badgeString,
                                                           itemObject["Description"].GetString(),
                                                           itemObject["Content"].GetString(),
                                                           isNew,
                                                           isUpdated,
                                                           isPreview);

                        if (itemObject.ContainsKey("Docs"))
                        {
                            foreach (JsonValue docValue in itemObject["Docs"].GetArray())
                            {
                                JsonObject docObject = docValue.GetObject();
                                item.Docs.Add(new ControlInfoDocLink(docObject["Title"].GetString(), docObject["Uri"].GetString()));
                            }
                        }

                        if (itemObject.ContainsKey("RelatedControls"))
                        {
                            foreach (JsonValue relatedControlValue in itemObject["RelatedControls"].GetArray())
                            {
                                item.RelatedControls.Add(relatedControlValue.GetString());
                            }
                        }

                        group.Items.Add(item);
                    }

                    if (!Groups.Any(g => g.Title == group.Title))
                    {
                        Groups.Add(group);
                    }
                }
            }
        }
Beispiel #48
0
    public void Save(string fileName)
    {
        string jsonData = FileIO.ObjectToJson(new ListSerialization <int>(GetTileTypes()));

        FileIO.CreateJsonFile(Application.persistentDataPath + @"/Maps", fileName, jsonData);
    }
Beispiel #49
0
        public static Task <bool> AddModuleAsync(StorageFile module_zip)
        {
            return(Task.Run(async() =>
            {
                int id = new Random().Next(999999);
                StorageFolder folder_addon = await folder_modules.CreateFolderAsync(id + "", CreationCollisionOption.OpenIfExists);

                ZipFile.ExtractToDirectory(module_zip.Path, folder_addon.Path);

                StorageFile file_infos = await folder_addon.CreateFileAsync("infos.json", CreationCollisionOption.OpenIfExists);
                using (var reader = new StreamReader(await file_infos.OpenStreamForReadAsync()))
                    using (JsonReader JsonReader = new JsonTextReader(reader))
                    {
                        try
                        {
                            InfosModule content = new JsonSerializer().Deserialize <InfosModule>(JsonReader);

                            if (content != null)
                            {
                                content.ID = id; content.ModuleSystem = false; content.IsEnabled = true;

                                if (await folder_addon.TryGetItemAsync("theme_ace.js") != null)
                                {
                                    content.ContainMonacoTheme = true;
                                }
                                else
                                {
                                    content.ContainMonacoTheme = false;
                                }

                                switch (content.ModuleType)
                                {
                                case ModuleTypesList.Addon:
                                    content.CanBePinnedToToolBar = true;
                                    break;

                                case ModuleTypesList.Theme:
                                    content.CanBePinnedToToolBar = false;
                                    break;

                                case ModuleTypesList.Language:
                                    content.CanBePinnedToToolBar = false;
                                    break;
                                }

                                using (var reader_b = new StreamReader(await file.OpenStreamForReadAsync()))
                                    using (JsonReader JsonReader_b = new JsonTextReader(reader))
                                    {
                                        try
                                        {
                                            ModulesList list = new JsonSerializer().Deserialize <ModulesList>(JsonReader_b);

                                            if (list == null)
                                            {
                                                list = new ModulesList();
                                                list.Modules = new List <InfosModule>();
                                            }

                                            list.Modules.Add(content);
                                            await FileIO.WriteTextAsync(file, JsonConvert.SerializeObject(list, Formatting.Indented));

                                            foreach (CoreApplicationView view in CoreApplication.Views)
                                            {
                                                await view.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                                {
                                                    Messenger.Default.Send(new SMSNotification {
                                                        Type = TypeUpdateModule.NewModule, ID = id
                                                    });
                                                });
                                            }

                                            return true;
                                        }
                                        catch
                                        {
                                            return false;
                                        }
                                    }
                            }
                        }
                        catch
                        {
                            return false;
                        }
                    }

                return true;
            }));
        }
Beispiel #50
0
        private async void ButtonLogin_OnClick(object sender, RoutedEventArgs e)
        {
            ButtonLogin.IsEnabled = false;
            ButtonLogin.Content   = "登录中......";
            bool    isOk;
            JObject json;

            try
            {
                var queries = new Dictionary <string, object>();
                var account = TextBoxAccount.Text;
                var isPhone = Regex.Match(account, "^[0-9]+$").Success;
                queries[isPhone ? "phone" : "email"] = account;
                queries["password"] = TextBoxPassword.Password;
                (isOk, json)        = await Common.ncapi.RequestAsync(
                    isPhone?CloudMusicApiProviders.LoginCellphone : CloudMusicApiProviders.Login, queries);

                if (!isOk || json["code"].ToString() != "200")
                {
                    ButtonLogin.Visibility    = Visibility.Visible;
                    InfoBarLoginHint.IsOpen   = true;
                    InfoBarLoginHint.Title    = "登录失败";
                    ButtonLogin.Content       = "登录";
                    ButtonLogin.IsEnabled     = true;
                    InfoBarLoginHint.Severity = InfoBarSeverity.Warning;
                    InfoBarLoginHint.Message  = "登录失败 " + json["msg"];
                }
                else
                {
                    Common.Logined = true;
                    StorageFile sf = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(
                        "Settings\\UserPassword", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                    _ = FileIO.WriteTextAsync(sf,
                                              account + "\r\n" + TextBoxPassword.Password.ToString().ToByteArrayUtf8().ComputeMd5()
                                              .ToHexStringLower());
                    Common.LoginedUser.UserName      = json["profile"]["nickname"].ToString();
                    Common.LoginedUser.ImgUrl        = json["profile"]["avatarUrl"].ToString();
                    Common.LoginedUser.uid           = json["account"]["id"].ToString();
                    InfoBarLoginHint.IsOpen          = true;
                    InfoBarLoginHint.Title           = "登录成功";
                    ButtonLogin.Content              = "登录成功";
                    TextBlockUserName.Text           = json["profile"]["nickname"].ToString();
                    PersonPictureUser.ProfilePicture =
                        new BitmapImage(new Uri(json["profile"]["avatarUrl"].ToString()));
                    InfoBarLoginHint.Severity = InfoBarSeverity.Success;
                    InfoBarLoginHint.Message  = "欢迎 " + json["profile"]["nickname"].ToString();
                }
            }
            catch (Exception ex)
            {
                ButtonLogin.IsEnabled     = true;
                InfoBarLoginHint.IsOpen   = true;
                InfoBarLoginHint.Severity = InfoBarSeverity.Error;
                StorageFile sf = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(
                    "Settings\\Log", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                _ = FileIO.WriteTextAsync(sf,
                                          ex.ToString());
                InfoBarLoginHint.Message = "登录失败 " + ex.ToString();
            }
        }
Beispiel #51
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 async Task CreateFileAsync()
        {
            StorageFolder storageFolder = KnownFolders.DocumentsLibrary;

            switch (cbFormat.SelectedIndex)
            {
            case 0:
                await storageFolder.CreateFileAsync($"File.json", CreationCollisionOption.ReplaceExisting);

                StorageFile jsonFile = await storageFolder.GetFileAsync("File.json");

                await FileIO.WriteTextAsync(jsonFile, JsonConvert.SerializeObject(new Person {
                    FirstName = tbxFirst.Text, LastName = tbxLast.Text, Age = Convert.ToInt32(tbxAge.Text), City = tbxCity.Text
                }));

                var textFromJsonFile = await FileIO.ReadTextAsync(jsonFile);

                lwFiles.Items.Add(textFromJsonFile);
                ClearTextBoxes();
                break;

            case 1:
                await storageFolder.CreateFileAsync($"File.csv", CreationCollisionOption.ReplaceExisting);

                StorageFile csvFile = await storageFolder.GetFileAsync("File.csv");

                char delimiter = ';';
                var  content   = tbxFirst.Text + delimiter + tbxLast.Text + delimiter + Convert.ToInt32(tbxAge.Text) + delimiter + tbxCity.Text;
                var  lines     = new List <string> {
                    content
                };
                await FileIO.AppendLinesAsync(csvFile, lines);

                var textFromCsvFile = await FileIO.ReadTextAsync(csvFile);

                lwFiles.Items.Add(textFromCsvFile);
                ClearTextBoxes();


                break;

            case 2:
                await storageFolder.CreateFileAsync($"File.xml", CreationCollisionOption.ReplaceExisting);

                StorageFile file = await storageFolder.GetFileAsync("File.xml");

                using (var stream = await file.OpenStreamForWriteAsync())
                {
                    XmlWriterSettings settings = new XmlWriterSettings()
                    {
                        Indent      = true,
                        IndentChars = ("  "),
                        CloseOutput = true
                    };
                    using XmlWriter xml = XmlWriter.Create(stream, settings);
                    xml.WriteStartElement("people");
                    xml.WriteStartElement("person");
                    xml.WriteAttributeString("firstname", tbxFirst.Text);
                    xml.WriteElementString("lastname", tbxLast.Text);
                    xml.WriteElementString("age", tbxAge.Text);
                    xml.WriteElementString("city", tbxCity.Text);
                    xml.WriteEndElement();
                    xml.WriteEndElement();
                    xml.Close();
                    var textFromXmlFile = await FileIO.ReadTextAsync(file);

                    lwFiles.Items.Add(textFromXmlFile);
                    ClearTextBoxes();
                }
                break;

            case 3:
                await storageFolder.CreateFileAsync($"File.txt", CreationCollisionOption.ReplaceExisting);

                StorageFile txtFile = await storageFolder.GetFileAsync("File.txt");

                var text = tbxFirst.Text + " " + tbxLast.Text + " " + Convert.ToInt32(tbxAge.Text) + " " + tbxCity.Text;
                await FileIO.WriteTextAsync(txtFile, text);

                var textFromTxtFile = await FileIO.ReadTextAsync(txtFile);

                lwFiles.Items.Add(textFromTxtFile);
                ClearTextBoxes();
                break;
            }
        }
        /// <summary>
        /// Convert HTML URL to PDF
        /// </summary>
        /// <param name="url">The HTTP or HTTPS URL</param>
        /// <param name="name">Name of the PDF file</param>
        /// <returns></returns>
        public async Task <bool> ConvertHTML2PDF(string name)
        {
            if (string.IsNullOrWhiteSpace(URL))
            {
                return(false);
            }

            // Check if URL is valid HTTP or HTTPS
            Uri  uriResult;
            bool result = Uri.TryCreate(URL, UriKind.Absolute, out uriResult) &&
                          (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

            if (result == false)
            {
                return(false);
            }

            IsProgressRingActive = true;
            ProgressVisible      = Visibility.Visible;

            var workflowSetting = new WorkflowSetting();
            var wfConvertToPDF  = workflowSetting.AddNewConvertToPdfTask();

            string ddd = @"{ ""Url"": """ + URL + @""" }"; // @"{ ""Url"": ""https://www.pdftron.com/"" }";

            byte[]       byteArray = Encoding.UTF8.GetBytes(ddd);
            MemoryStream stream    = new MemoryStream(byteArray);

            var job = await mClient.StartNewJobAsync(workflowSetting, stream, "pdftron.bclurl");

            try
            {
                // Wait until job execution is completed and return PDF file
                var job_rsl = await job.WaitForJobExecutionCompletionAsync();

                var         folder     = ApplicationData.Current.LocalFolder;
                StorageFile outputFile = await folder.CreateFileAsync(name + ".pdf",
                                                                      CreationCollisionOption.ReplaceExisting);

                using (var memoryStream = new MemoryStream())
                {
                    await job_rsl.FileData.Stream.CopyToAsync(memoryStream);

                    byte[] outputBytes = memoryStream.ToArray();
                    await FileIO.WriteBytesAsync(outputFile, outputBytes);
                }

                // Open PDFDoc on PDFViewer
                PDFDoc doc = new PDFDoc(outputFile);
                PDFViewCtrl.SetDoc(doc);
            }
            catch (Exception ex)
            {
                // swallow exception
            }
            finally
            {
                IsProgressRingActive = false;
                ProgressVisible      = Visibility.Collapsed;
            }

            return(false);
        }
        public async Task <bool> Finish()
        {
            var ok = false;

            Flush();
            if (_writeVBRHeader)
            {
                _fs.Seek(0, SeekOrigin.Begin);
                WriteVBRHeader(false);
            }
            //完成转换写入文件
            if (_fs != null && _fs.Length > 0)
            {
                if (storageFile != null)
                {
                    if (isFileSavePicker)
                    {
                        ok = await FileToSavePicker(ok);

                        if (ok)
                        {
                            try
                            {
                                await storageFile.DeleteAsync();
                            }
                            catch
                            {
                                ok = false;
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            var name        = storageFile.DisplayName;
                            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                            var file        = await localFolder.CreateFileAsync("temp.mp3", CreationCollisionOption.OpenIfExists);

                            byte[] bytes = _fs.ToArray();
                            await FileIO.WriteBytesAsync(file, bytes);

                            await storageFile.RenameAsync(name + ".mp3", NameCollisionOption.ReplaceExisting);

                            //await file.CopyAndReplaceAsync(storageFile);
                            await file.MoveAndReplaceAsync(storageFile);

                            ok = true;
                        }
                        catch
                        {
                            ok = false;
                        }
                    }
                }
                else
                {
                    ok = await FileToSavePicker(ok);
                }
            }
            //_fs.Close();
            _fs.Dispose();
            return(ok);
        }
 public Filter(string srcPath)
 {
     this._bitmap = (Bitmap)FileIO.getImageFromFilePath(srcPath);
 }
Beispiel #56
0
        /// <summary>
        /// Tapped event handler for the "Export" NavigationView item.
        /// </summary>
        /// <param name="sender">Object which triggered this event.</param>
        /// <param name="e">Data related to the event which was triggered.</param>
        private async void Export_TappedAsync(object sender, TappedRoutedEventArgs e)
        {
            DateTime now = DateTime.Now;

            var fileSavePicker = new Windows.Storage.Pickers.FileSavePicker
            {
                SuggestedFileName      = $"Logger Export {now.Year}-{AddTrailingZero(now.Month)}-{AddTrailingZero(now.Day)}T{AddTrailingZero(now.Hour)}{AddTrailingZero(now.Minute)}{AddTrailingZero(now.Second)}.txt",
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary
            };

            fileSavePicker.FileTypeChoices.Add("Text (Tab delimited)", new List <string>()
            {
                ".txt"
            });

            StorageFile file = await fileSavePicker.PickSaveFileAsync();

            if (file != null)
            {
                // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
                CachedFileManager.DeferUpdates(file);

                List <DataGridTextColumn> columnsInOrder = new List <DataGridTextColumn>();
                List <string>             lines          = new List <string>();
                string columns = string.Empty;
                string row     = string.Empty;

                // Build a list of the columns sorted in the order in which they are currently displayed.
                for (int i = 0; i <= dgDataGrid.Columns.Count - 1; i++)
                {
                    foreach (DataGridTextColumn column in dgDataGrid.Columns)
                    {
                        if (column.DisplayIndex == i)
                        {
                            columnsInOrder.Add(column);
                        }
                    }
                }

                // Construct the column header line.
                foreach (DataGridTextColumn column in columnsInOrder)
                {
                    if (column == columnsInOrder.First())
                    {
                        columns = $"{column.Header}";
                    }
                    else
                    {
                        columns = $"{columns}\t{column.Header}";
                    }
                }

                lines.Add(columns);

                // Construct each line to be added to the file.
                foreach (Message message in Messages)
                {
                    // Lookup each column in the datagrid and find the corresponding generic property in the message.
                    // This handles the possibility that not all fifteen properties in the Message class were used in the datagrid.
                    foreach (DataGridTextColumn column in columnsInOrder)
                    {
                        switch (column.Binding.Path.Path)
                        {
                        case "Time":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Time}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Time}";
                            }
                            break;
                        }

                        case "ID":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.ID}";
                            }
                            else
                            {
                                row = $"{row}\t{message.ID}";
                            }
                            break;
                        }

                        case "Column1":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column1}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column1}";
                            }
                            break;
                        }

                        case "Column2":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column2}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column2}";
                            }
                            break;
                        }

                        case "Column3":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column3}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column3}";
                            }
                            break;
                        }

                        case "Column4":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column4}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column4}";
                            }
                            break;
                        }

                        case "Column5":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column5}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column5}";
                            }
                            break;
                        }

                        case "Column6":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column6}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column6}";
                            }
                            break;
                        }

                        case "Column7":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column7}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column7}";
                            }
                            break;
                        }

                        case "Column8":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column8}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column8}";
                            }
                            break;
                        }

                        case "Column9":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column9}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column9}";
                            }
                            break;
                        }

                        case "Column10":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column10}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column10}";
                            }
                            break;
                        }

                        case "Column11":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column11}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column11}";
                            }
                            break;
                        }

                        case "Column12":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column12}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column12}";
                            }
                            break;
                        }

                        case "Column13":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column13}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column13}";
                            }
                            break;
                        }

                        case "Column14":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column14}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column14}";
                            }
                            break;
                        }

                        case "Column15":
                        {
                            if (column == columnsInOrder.First())
                            {
                                row = $"{message.Column15}";
                            }
                            else
                            {
                                row = $"{row}\t{message.Column15}";
                            }
                            break;
                        }
                        }
                    }

                    lines.Add(row);
                    row = string.Empty;
                }

                // Write the contents of the datagrid to the file.
                await FileIO.WriteLinesAsync(file, lines);

                // Let the OS know that we're finished changing the file.
                await CachedFileManager.CompleteUpdatesAsync(file);
            }
        }
Beispiel #57
0
        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            FileTextBox.Text  = "";
            Progress.IsActive = true;
            ///////////////////////////////////////////////////////////////////////////////

            var savePicker4 = new Windows.Storage.Pickers.FileSavePicker();

            savePicker4.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            // Поле выбора типа файла в диалоге
            savePicker4.FileTypeChoices.Add("Файл данных скриптов футера ", new List <string>()
            {
                ".footerscripts"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker4.SuggestedFileName = "footer";
            //
            Windows.Storage.StorageFile Myfile4 = await savePicker4.PickSaveFileAsync();

            if (Myfile4 != null)
            {
                // Prevent updates to the remote version of the file until
                // we finish making changes and call CompleteUpdatesAsync.
                Windows.Storage.CachedFileManager.DeferUpdates(Myfile4);
                // write to file
                //await Windows.Storage.FileIO.WriteTextAsync(file, file.Name); //запись в файл имени



                await FileIO.WriteTextAsync(Myfile4, TextBoxSTYLEFooter.Text + "¶" + TextBoxCODEFooter.Text + "¶" +

                                            TextBoxFTPServer.Text + "¶" +
                                            TextBoxFTPUser.Text + "¶" +
                                            TextBoxFTPPass.Password + "¶");



                // Let Windows know that we're finished changing the file so
                // the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                Windows.Storage.Provider.FileUpdateStatus status =
                    await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(Myfile4);

                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    string text1 = await Windows.Storage.FileIO.ReadTextAsync(Myfile4);

                    string text02 = text1.Replace("\r\n", "  "); string text002 = text02.Replace("\n", "  "); string text2 = text002.Replace("\r", "  ");
                    await FileIO.WriteTextAsync(Myfile4, text2);

                    this.StatusFile.Text = "Файл данных скриптов футера " + Myfile4.Name + " успешно сохранен.";

                    var messagedialog = new MessageDialog("Файл данных скриптов футера " + Myfile4.Name + " успешно сохранен.");
                    messagedialog.Commands.Add(new UICommand("Ok"));
                    await messagedialog.ShowAsync();
                }
                else
                {
                    this.StatusFile.Text = "Не удалось сохранить файл данных скриптов футера " + Myfile4.Name + ".";

                    var messagedialog = new MessageDialog("Не удалось сохранить файл данных скриптов футера " + Myfile4.Name + ".");
                    messagedialog.Commands.Add(new UICommand("Ok"));
                    await messagedialog.ShowAsync();
                }
            }
            else
            {
                this.StatusFile.Text = "Операция записи файла данных скриптов футера была прервана.";

                var messagedialog = new MessageDialog("Операция записи файла данных скриптов футера была прервана.");
                messagedialog.Commands.Add(new UICommand("Ok"));
                await messagedialog.ShowAsync();
            }

            ///////////////////////////////////////////////////////////////////////////////

            StorageFolder localFolderUPLOAD = ApplicationData.Current.LocalFolder;
            StorageFile   UPLOADFile        = await localFolderUPLOAD.CreateFileAsync("upload.txt", CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(UPLOADFile, "<!-- ======================================СКРИПТЫ ФУТЕРА======================================================== -->\r\n");

            await FileIO.AppendTextAsync(UPLOADFile, "<!-- Bootstrap core JavaScript================================================== -->\r\n");

            await FileIO.AppendTextAsync(UPLOADFile, "<!-- Placed at the end of the document so the pages load faster -->\r\n");

            await FileIO.AppendTextAsync(UPLOADFile, "<script src=\"js/jquery.min.js\"></script>\r\n");

            await FileIO.AppendTextAsync(UPLOADFile, "<script src=\"js/bootstrap.min.js\"></script>\r\n");

            await FileIO.AppendTextAsync(UPLOADFile, "<script src=\"js/holder.min.js\"></script>\r\n");

            await FileIO.AppendTextAsync(UPLOADFile, "<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->\r\n");

            await FileIO.AppendTextAsync(UPLOADFile, "<script src=\"js/ie10-viewport-bug-workaround.js\"></script>\r\n");

            await FileIO.AppendTextAsync(UPLOADFile, TextBoxCODEFooter.Text + "\r\n");

            await FileIO.AppendTextAsync(UPLOADFile, "<!-- ======================================КОНЕЦ СКРИПТОВ ФУТЕРА================================================== -->\r\n");

            await FileIO.AppendTextAsync(UPLOADFile, "</body>\r\n</html>\r\n");


            ///////////////////////////////////////////////////////////////////////////////

            string text11 = await Windows.Storage.FileIO.ReadTextAsync(UPLOADFile);

            string text102 = text11.Replace("\r\n", "  "); string text1002 = text102.Replace("\n", "  "); string text12 = text1002.Replace("\r", "  ");

            FileTextBox.Text = text12;

            ///////////////////////////////////////////////////////////////////////////////

            if (TextBoxFTPServer.Text != "")
            {
                Progress.IsActive = true;
                DoDownloadOrUpload(false); ////см.проект kiewic ftp client
            }

            else
            {
                StatusFile.Text   = "Ошибка. Введите адрес FTP сервера.";
                Progress.IsActive = false;

                var messagedialog = new MessageDialog("Ошибка. Введите адрес FTP сервера.");
                messagedialog.Commands.Add(new UICommand("Ok"));
                await messagedialog.ShowAsync();
            }

            Progress.IsActive = false;
        }
Beispiel #58
0
        public async Task SaveFileAsync(string fileName, byte[] content)
        {
            StorageFile destinationFile = await _storage.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteBytesAsync(destinationFile, content);
        }
Beispiel #59
0
        private async void SaveFileKatalogTovarovTPL_Click(object sender, RoutedEventArgs e)
        {
            Progress.IsActive = true;
            var savePicker4 = new Windows.Storage.Pickers.FileSavePicker();

            savePicker4.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            // Поле выбора типа файла в диалоге
            savePicker4.FileTypeChoices.Add("TPL файл скриптов футера ", new List <string>()
            {
                ".tpl"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker4.SuggestedFileName = "footerscripts";
            //
            Windows.Storage.StorageFile Myfile4 = await savePicker4.PickSaveFileAsync();

            if (Myfile4 != null)
            {
                // Prevent updates to the remote version of the file until
                // we finish making changes and call CompleteUpdatesAsync.
                Windows.Storage.CachedFileManager.DeferUpdates(Myfile4);
                // write to file
                //await Windows.Storage.FileIO.WriteTextAsync(file, file.Name); //запись в файл имени

                await FileIO.WriteTextAsync(Myfile4, "<!-- ======================================СКРИПТЫ ФУТЕРА======================================================== -->\r\n");

                await FileIO.AppendTextAsync(Myfile4, "<!-- Bootstrap core JavaScript================================================== -->\r\n");

                await FileIO.AppendTextAsync(Myfile4, "<!-- Placed at the end of the document so the pages load faster -->\r\n");

                await FileIO.AppendTextAsync(Myfile4, "<script src=\"js/jquery.min.js\"></script>\r\n");

                await FileIO.AppendTextAsync(Myfile4, "<script src=\"js/bootstrap.min.js\"></script>\r\n");

                await FileIO.AppendTextAsync(Myfile4, "<script src=\"js/holder.min.js\"></script>\r\n");

                await FileIO.AppendTextAsync(Myfile4, "<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->\r\n");

                await FileIO.AppendTextAsync(Myfile4, "<script src=\"js/ie10-viewport-bug-workaround.js\"></script>\r\n");

                await FileIO.AppendTextAsync(Myfile4, TextBoxCODEFooter.Text + "\r\n");

                await FileIO.AppendTextAsync(Myfile4, "<!-- ======================================КОНЕЦ СКРИПТОВ ФУТЕРА================================================== -->\r\n");

                await FileIO.AppendTextAsync(Myfile4, "</body>\r\n</html>\r\n");

                // Let Windows know that we're finished changing the file so
                // the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                Windows.Storage.Provider.FileUpdateStatus status =
                    await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(Myfile4);

                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    this.StatusFile.Text = "TPL-файл скриптов футера " + Myfile4.Name + " успешно экспортирован.";


                    string text1 = await Windows.Storage.FileIO.ReadTextAsync(Myfile4);

                    string text02 = text1.Replace("\r\n", "  "); string text002 = text02.Replace("\n", "  "); string text2 = text002.Replace("\r", "  ");

                    FileTextBox.Text = text2;

                    await FileIO.WriteTextAsync(Myfile4, text2);

                    Progress.IsActive = false;

                    var messagedialog = new MessageDialog("TPL-файл скриптов футера " + Myfile4.Name + " успешно экспортирован.");
                    messagedialog.Commands.Add(new UICommand("Ok"));
                    await messagedialog.ShowAsync();
                }
                else
                {
                    this.StatusFile.Text = "Не удалось сохранить TPL-файл скриптов футера " + Myfile4.Name + ".";
                    Progress.IsActive    = false;

                    var messagedialog = new MessageDialog("Не удалось сохранить TPL-файл скриптов футера " + Myfile4.Name + ".");
                    messagedialog.Commands.Add(new UICommand("Ok"));
                    await messagedialog.ShowAsync();
                }
            }
            else
            {
                this.StatusFile.Text = "Операция записи TPL-файла скриптов футера была прервана.";
                Progress.IsActive    = false;

                var messagedialog = new MessageDialog("Операция записи TPL-файла скриптов футера была прервана.");
                messagedialog.Commands.Add(new UICommand("Ok"));
                await messagedialog.ShowAsync();
            }
            Progress.IsActive = false;
        }
Beispiel #60
0
        public async static Task <List <List <Course> > > LoadWeeklyDataFromIsoStoreAsync(List <List <Course> > weeklyList, int currentWeekNum)
        {
            try
            {
                string[] courseStartTime = new string[] { "8:30", "9:15", "10:05", "10:55", "11:40", "14:00", "14:45", "15:35", "16:20", "19:00", "19:40", "20:20" };
                string[] courseEndTime   = new string[] { "9:10", "9:55", "10:45", "11:35", "12:20", "14:40", "15:25", "16:15", "17:00", "19:40", "20:20", "21:00" };

                weeklyList = new List <List <Course> >();//保证列表为空,防止课程累加导致列表过长

                //StorageFile file = StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appdata:///Local/cqmu/{App.AppSettings.UserId}/Data/WeeklyData_{currentWeekNum - 1}.txt", UriKind.Absolute)).GetResults();
                StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appdata:///Local/cqmu/{App.AppSettings.UserId}/Data/WeeklyData_{currentWeekNum - 1}.txt", UriKind.Absolute));

                string weeklyData = await FileIO.ReadTextAsync(file);

                JObject json = JObject.Parse(weeklyData);
                for (int i = 0; i < json["WeeklyData"].Count(); i++)
                {
                    List <Course> dailyList = new List <Course>();

                    for (int j = 0; j < json["WeeklyData"][i]["DailyData"].Count() - 1; j++)
                    {
                        Course course = new Course();

                        course.FullName   = json["WeeklyData"][i]["DailyData"][j]["FullName"].ToString();
                        course.Teacher    = json["WeeklyData"][i]["DailyData"][j]["Teacher"].ToString();
                        course.Classroom  = json["WeeklyData"][i]["DailyData"][j]["Classroom"].ToString();
                        course.Credits    = json["WeeklyData"][i]["DailyData"][j]["Credits"].ToString();
                        course.Classify   = json["WeeklyData"][i]["DailyData"][j]["Classify"].ToString();
                        course.StartMark  = j;
                        course.StartTime  = courseStartTime[j];
                        course.CourseSpan = 1;

                        while (j < json["WeeklyData"][i]["DailyData"].Count() - 1 &&
                               course.FullName == json["WeeklyData"][i]["DailyData"][j + 1]["FullName"].ToString() &&
                               course.Classroom == json["WeeklyData"][i]["DailyData"][j + 1]["Classroom"].ToString() &&
                               course.Classify == json["WeeklyData"][i]["DailyData"][j + 1]["Classify"].ToString())
                        {
                            course.CourseSpan++;
                            j++;
                        }

                        course.EndTime = courseEndTime[j];

                        if (!string.IsNullOrEmpty(course.FullName))
                        {
                            dailyList.Add(course);
                        }
                    }

                    weeklyList.Add(dailyList);
                }

                return(weeklyList);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);

                return(null);
            }
        }