public override bool FolderExists(string path)
        {
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();

            return(store.DirectoryExists(path));
        }
Exemplo n.º 2
0
        private void ProcessTransfer(BackgroundTransferRequest transfer)
        {
            switch (transfer.TransferStatus)
            {
            case TransferStatus.Completed:
                if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
                {
                    // Remove the transfer request in order to make room in the
                    // queue for more transfers. Transfers are not automatically
                    // removed by the system.
                    ReceivedChatBubble chatBubble;
                    requestIdChatBubbleMap.TryGetValue(transfer.RequestId, out chatBubble);
                    if (chatBubble != null)
                    {
                        chatBubble.setAttachmentState(Attachment.AttachmentState.COMPLETED);
                    }
                    RemoveTransferRequest(transfer.RequestId);
                    //RemoveTransferRequest(transfer.RequestId);
                    // In this example, the downloaded file is moved into the root
                    // Isolated Storage directory
                    if (transfer.UploadLocation == null)
                    {
                        using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            string destinationPath      = HikeConstants.FILES_BYTE_LOCATION + transfer.Tag;
                            string destinationDirectory = destinationPath.Substring(0, destinationPath.LastIndexOf("/"));
                            if (isoStore.FileExists(destinationPath))
                            {
                                isoStore.DeleteFile(destinationPath);
                            }
                            if (!isoStore.DirectoryExists(destinationDirectory))
                            {
                                isoStore.CreateDirectory(destinationDirectory);
                            }
                            isoStore.MoveFile(transfer.DownloadLocation.OriginalString, destinationPath);
                            isoStore.DeleteFile(transfer.DownloadLocation.OriginalString);

                            if (chatBubble != null && chatBubble.FileAttachment.ContentType.Contains(HikeConstants.IMAGE))
                            {
                                IsolatedStorageFileStream myFileStream = isoStore.OpenFile(destinationPath, FileMode.Open, FileAccess.Read);
                                MediaLibrary library = new MediaLibrary();
                                myFileStream.Seek(0, 0);
                                library.SavePicture(chatBubble.FileAttachment.FileName, myFileStream);
                            }
                            var currentPage = ((App)Application.Current).RootFrame.Content as NewChatThread;
                            if (currentPage != null)
                            {
                                currentPage.displayAttachment(chatBubble, true);
                            }
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                    try
                    {
                        RemoveTransferRequest(transfer.RequestId);
                        // This is where you can handle whatever error is indicated by the
                        // StatusCode and then remove the transfer from the queue.
                        if (transfer.TransferError != null)
                        {
                            // Handle TransferError if one exists.
                        }
                    }
                    catch (InvalidOperationException)
                    { }
                }
                break;

            case TransferStatus.WaitingForExternalPower:
                WaitingForExternalPower = true;
                break;

            case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
                WaitingForExternalPowerDueToBatterySaverMode = true;
                break;

            case TransferStatus.WaitingForNonVoiceBlockingNetwork:
                WaitingForNonVoiceBlockingNetwork = true;
                break;

            case TransferStatus.WaitingForWiFi:
                WaitingForWiFi = true;
                break;
            }
        }
Exemplo n.º 3
0
 public Task <bool> GetDirectoryExistsAsync(string path)
 {
     return(Task.FromResult(isolatedStorageFile.DirectoryExists(path)));
 }
Exemplo n.º 4
0
        void GapBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.IsInDesignTool)
            {
                return;
            }

            // prevents refreshing web control to initial state during pages transitions
            if (this.IsBrowserInitialized)
            {
                return;
            }



            this.domStorageHelper = new DOMStorageHelper(this.CordovaBrowser);

            try
            {
                // Before we possibly clean the ISO-Store, we need to grab our generated UUID, so we can rewrite it after.
                string deviceUUID = "";

                using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    try
                    {
                        IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Open, FileAccess.Read, appStorage);

                        using (StreamReader reader = new StreamReader(fileStream))
                        {
                            deviceUUID = reader.ReadLine();
                        }
                    }
                    catch (Exception /*ex*/)
                    {
                        deviceUUID = Guid.NewGuid().ToString();
                    }

                    Debug.WriteLine("Updating IsolatedStorage for APP:DeviceID :: " + deviceUUID);
                    IsolatedStorageFileStream file = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Create, FileAccess.Write, appStorage);
                    using (StreamWriter writeFile = new StreamWriter(file))
                    {
                        writeFile.WriteLine(deviceUUID);
                        writeFile.Close();
                    }
                }

                StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("CordovaSourceDictionary.xml", UriKind.Relative));

                if (streamInfo != null)
                {
                    StreamReader sr = new StreamReader(streamInfo.Stream);
                    //This will Read Keys Collection for the xml file

                    XDocument document = XDocument.Parse(sr.ReadToEnd());

                    var files = from results in document.Descendants("FilePath")
                                select new
                    {
                        path = (string)results.Attribute("Value")
                    };
                    StreamResourceInfo fileResourceStreamInfo;

                    using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        foreach (var file in files)
                        {
                            fileResourceStreamInfo = Application.GetResourceStream(new Uri(file.path, UriKind.Relative));

                            if (fileResourceStreamInfo != null)
                            {
                                using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream))
                                {
                                    byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length);

                                    string strBaseDir = AppRoot + file.path.Substring(0, file.path.LastIndexOf(System.IO.Path.DirectorySeparatorChar));

                                    if (!appStorage.DirectoryExists(strBaseDir))
                                    {
                                        Debug.WriteLine("INFO: Creating Directory :: " + strBaseDir);
                                        appStorage.CreateDirectory(strBaseDir);
                                    }

                                    // This will truncate/overwrite an existing file, or
                                    using (IsolatedStorageFileStream outFile = appStorage.OpenFile(AppRoot + file.path, FileMode.Create))
                                    {
                                        Debug.WriteLine("INFO: Writing data for " + AppRoot + file.path + " and length = " + data.Length);
                                        using (var writer = new BinaryWriter(outFile))
                                        {
                                            writer.Write(data);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Debug.WriteLine("ERROR: Failed to write file :: " + file.path + " did you forget to add it to the project?");
                            }
                        }
                    }
                }

                CordovaBrowser.Navigate(StartPageUri);
                IsBrowserInitialized = true;
                AttachHardwareButtonHandlers();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ERROR: Exception in GapBrowser_Loaded :: {0}", ex.Message);
            }
        }
Exemplo n.º 5
0
        public void DirectoryExists()
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly();

            isf.CreateDirectory("subdir");
            isf.CreateDirectory("subdir/subdir2");
            isf.CreateDirectory("subdir3");

            Assert.AreEqual(true, isf.DirectoryExists("subdir/"), "#A0");
            Assert.AreEqual(true, isf.DirectoryExists("subdir/subdir2/"), "#A1");
            Assert.AreEqual(true, isf.DirectoryExists("subdir3"), "#A2");
            Assert.AreEqual(true, isf.DirectoryExists(String.Empty), "#A3"); // Weird
            Assert.AreEqual(false, isf.DirectoryExists("subdir99"), "#A4");
            Assert.AreEqual(false, isf.DirectoryExists("../../subdir"), "#A5");
            Assert.AreEqual(false, isf.DirectoryExists("*"), "#A5");
            Assert.AreEqual(false, isf.DirectoryExists("subdir*"), "#A6");

            isf.DeleteDirectory("subdir3");
            Assert.AreEqual(false, isf.DirectoryExists("subdir3"), "#B0");

            isf.DeleteDirectory("subdir/subdir2");
            isf.DeleteDirectory("subdir");

            try
            {
                isf.DirectoryExists(null);
                Assert.Fail("#Exc1");
            }
            catch (ArgumentNullException)
            {
            }

            isf.Close();
            try
            {
                isf.DirectoryExists("subdir");
                Assert.Fail("#Exc2");
            }
            catch (InvalidOperationException)
            {
            }

            isf.Dispose();
            try
            {
                isf.DirectoryExists("subdir");
                Assert.Fail("#Exc3");
            }
            catch (ObjectDisposedException)
            {
            }

            // We want to be sure that if not closing but disposing
            // should fire ObjectDisposedException instead of InvalidOperationException
            isf = IsolatedStorageFile.GetUserStoreForAssembly();
            isf.Dispose();

            try
            {
                isf.DirectoryExists("subdir");
                Assert.Fail("#Exc4");
            }
            catch (ObjectDisposedException)
            {
            }
        }
Exemplo n.º 6
0
        private void InitializeIsolatedStorage()
        {
            try
            {
                string targetFile = GetTargetFile();
                _storage = IsolatedStorageFile.GetUserStoreForApplication();

                if (_storage.DirectoryExists(folderName))
                {
                    // remove old log files
                    var files = _storage.GetFileNames(folderName + @"\" + _filePrefix + "*");
                    foreach (string file in files)
                    {
                        if (!file.EndsWith(targetFile))
                        {
                            try
                            {
                                _storage.DeleteFile(folderName + @"\" + file);
                            }
                            catch (Exception ex)
                            {
                                // can't delete file, it can be opened. It's not critical for us.
                                RaiseErrorOccured(ex, "Can't delete file '{0}' from IsolatedStorage");
                            }
                        }
                    }
                }
                else
                {
                    _storage.CreateDirectory(folderName);
                }

                if (_storage.AvailableFreeSpace < minimumAvailableSpace)
                {
                    try
                    {
                        // remove current log file
                        if (_storage.FileExists(folderName + @"\" + targetFile))
                        {
                            _storage.DeleteFile(folderName + @"\" + targetFile);
                        }
                    }
                    catch (Exception ex)
                    {
                        // can't delete file, it can be opened. It's not critical for us.
                        RaiseErrorOccured(ex, string.Format("Can't delete file '{0}' from IsolatedStorage", targetFile));
                    }

                    // check again is enough space
                    if (_storage.AvailableFreeSpace < minimumAvailableSpace)
                    {
                        // Not enoug available free space, disable logging to Isolated Storage.
                        double availableSpace = _storage.AvailableFreeSpace;
                        Dispose();
                        RaiseErrorOccured(null, string.Format("Not enough space in IsolatedStorage for log: Available={0}, Needed={1}", availableSpace, minimumAvailableSpace));
                        return;
                    }
                }

                _stream = new IsolatedStorageFileStream(folderName + @"\" + targetFile, FileMode.Append,
                                                        FileAccess.Write, FileShare.ReadWrite, _storage);
                _writer           = new StreamWriter(_stream);
                _writer.AutoFlush = true;
            }
            catch (Exception ex)
            {
                Dispose();
                RaiseErrorOccured(ex, "Can't initialize logging to IsolatedStorage: ");
            }
        }
Exemplo n.º 7
0
        public void download(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest  webRequest      = null;
            string          callbackId;

            try
            {
                // source, target, trustAllHosts, this._id, headers
                string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options);

                downloadOptions          = new TransferOptions();
                downloadOptions.Url      = optionStrings[0];
                downloadOptions.FilePath = optionStrings[1];

                bool trustAll = false;
                bool.TryParse(optionStrings[2], out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Id         = optionStrings[3];
                downloadOptions.Headers    = optionStrings[4];
                downloadOptions.CallbackId = callbackId = optionStrings[5];
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                // is the URL a local app file?
                if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
                {
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//", "");

                        // pre-emptively create any directories in the FilePath that do not exist
                        string directoryName = getDirectoryName(downloadOptions.FilePath);
                        if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                        {
                            isoFile.CreateDirectory(directoryName);
                        }

                        // just copy from one area of iso-store to another ...
                        if (isoFile.FileExists(downloadOptions.Url))
                        {
                            isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
                        }
                        else
                        {
                            // need to unpack resource from the dll
                            Uri uri      = new Uri(cleanUrl, UriKind.Relative);
                            var resource = Application.GetResourceStream(uri);

                            if (resource != null)
                            {
                                // create the file destination
                                if (!isoFile.FileExists(downloadOptions.FilePath))
                                {
                                    var destFile = isoFile.CreateFile(downloadOptions.FilePath);
                                    destFile.Close();
                                }

                                using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile))
                                {
                                    long totalBytes = resource.Stream.Length;
                                    int  bytesRead  = 0;
                                    using (BinaryReader reader = new BinaryReader(resource.Stream))
                                    {
                                        using (BinaryWriter writer = new BinaryWriter(fileStream))
                                        {
                                            int    BUFFER_SIZE = 1024;
                                            byte[] buffer;

                                            while (true)
                                            {
                                                buffer = reader.ReadBytes(BUFFER_SIZE);
                                                // fire a progress event ?
                                                bytesRead += buffer.Length;
                                                if (buffer.Length > 0)
                                                {
                                                    writer.Write(buffer);
                                                    DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
                                                }
                                                else
                                                {
                                                    writer.Close();
                                                    reader.Close();
                                                    fileStream.Close();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath);
                    if (entry != null)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId);
                    }

                    return;
                }
                else
                {
                    // otherwise it is web-bound, we will actually download it
                    //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                    webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
                }
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                       new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                try
                {
                    // Associate cookies with the request
                    // This is an async call, so we need to await it in order to preserve proper control flow
                    Task cookieTask = CopyCookiesFromWebBrowser(webRequest);
                    cookieTask.Wait();
                }
                catch (AggregateException ae)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                           new FileTransferError(FileTransfer.ConnectionError, downloadOptions.Url, downloadOptions.FilePath, 0, ae.InnerException.Message)));
                    return;
                }

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                try
                {
                    webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
                }
                catch (WebException)
                {
                    // eat it
                }
                // dispatch an event for progress ( 0 )
                lock (state)
                {
                    if (!state.isCancelled)
                    {
                        var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress());
                        plugRes.KeepCallback = true;
                        plugRes.CallbackId   = callbackId;
                        DispatchCommandResult(plugRes, callbackId);
                    }
                }
            }
        }
Exemplo n.º 8
0
        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                Debugger.Break();
            }
            else
            {
                //ATT: Programatically exiting app...
                if (e.Exception.Message == "Cannot go back when CanGoBack is false.")
                {
                    return;
                }

                string sException = "RootFrame_NavigationFailed...\n\nMessage:\n" + e.Exception.Message +
                                    "\n\nStack Trace:\n" + e.Exception.StackTrace;

                IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();

                string sPath = "System";
                if (!store.DirectoryExists(sPath))
                {
                    store.CreateDirectory(sPath);
                }
                sPath += "\\Events";
                if (!store.DirectoryExists(sPath))
                {
                    store.CreateDirectory(sPath);
                }

                DateTime dNow = DateTime.Now;
                sPath += "\\";
                sPath += dNow.Year.ToString() + "-";
                if (dNow.Month < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Month.ToString() + "-";
                if (dNow.Day < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Day.ToString();
                sPath += "_";
                if (dNow.Hour < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Hour.ToString() + "-";
                if (dNow.Minute < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Minute.ToString() + "-";
                if (dNow.Second < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Second.ToString();

                string sPathWrk = sPath;
                int    i        = 0;
                for (;;)
                {
                    sPathWrk = sPath + "_" + i.ToString();
                    if (!store.FileExists(sPathWrk + ".error"))
                    {
                        break;
                    }
                    i++;
                }
                sPath = sPathWrk + ".error";
                IsolatedStorageFileStream stream = store.CreateFile(sPath);
                StreamWriter sw = new StreamWriter(stream);
                sw.Write(sException);
                sw.Close();
                stream.Close();

                MessageBox.Show(sException);
            }
        }
Exemplo n.º 9
0
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.ProgressIndicator = new ProgressIndicator();
            SystemTray.ProgressIndicator.IsIndeterminate = true;
            if ((string)store["disableLandscape"] == "true")
            {
                ListTopicPage.SupportedOrientations = SupportedPageOrientation.Portrait;
            }
            if (store.Contains("navigatedback"))
            {
                store.Remove("navigatedback");
                if (isoStore.DirectoryExists("topics"))
                {
                    foreach (string fileName in isoStore.GetFileNames("topics/*"))
                    {
                        isoStore.DeleteFile("topics/" + fileName);
                    }
                }
            }
            else
            {
                // Récupération de l'URI de la sous-catégorie
                NavigationContext.QueryString.TryGetValue("souscaturi", out souscatUri);
                souscatUri = HttpUtility.UrlDecode(souscatUri);

                // Récupération de l'ID de la catégorie
                NavigationContext.QueryString.TryGetValue("idcat", out idCat);

                // Récupération du nom du forum
                NavigationContext.QueryString.TryGetValue("souscatname", out souscatName);
                if (souscatName == null)
                {
                    souscatName = GetCatName.PlainNameFromId(idCat);
                }
                topicsPivot.Title = souscatName.ToUpper();

                // Récupération de la provenance
                NavigationContext.QueryString.TryGetValue("from", out from);
                if (from == "changepage")
                {
                    NavigationService.RemoveBackEntry();
                }

                // Pivot
                NavigationContext.QueryString.TryGetValue("pivot", out pivot);

                // listPageNumber
                NavigationContext.QueryString.TryGetValue("listpagenumber", out listPageNumber);
                if (Convert.ToInt32(listPageNumber) > 1)
                {
                    ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
                }
                else
                {
                    ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
                }
                if (!souscatUri.Contains("cat=0"))
                {
                    souscatUri = souscatUri.Substring(0, souscatUri.Length - 5) + listPageNumber + ".htm";
                }


                if (pivot == "drap")
                {
                    topicsPivot.SelectedIndex = 1;
                }
                else if (pivot == "topics")
                {
                    topicsPivot.SelectedIndex = 0;
                }

                // Récupération du cookie
                if (store.Contains("HFRcookies"))
                {
                    container = store["HFRcookies"] as CookieContainer;
                }
                else
                {
                    // Création du cookie de l'user
                    List <Cookie> listCookies = store["listHFRcookies"] as List <Cookie>;
                    foreach (Cookie c in listCookies)
                    {
                        container.Add(new Uri("https://forum.hardware.fr", UriKind.Absolute), c);
                    }
                    store.Remove("HFRcookies");
                    store.Add("HFRcookies", container);
                }

                // ItemsSources
                drapList.ItemsSource   = null;
                topicsList.ItemsSource = null;

                // Téléchargement de la liste
                DownloadTopicsDrapals(Convert.ToInt32(listPageNumber));
            }
        }
Exemplo n.º 10
0
        //-----------------------------------------------------------------------------------------------------------------



        //Prüfen ob Return gedrückt wurde
        //-----------------------------------------------------------------------------------------------------------------
        private void TBFolderName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            //Prüfen ob Return gedrückt wurde
            string tempkey = Convert.ToString(e.Key);

            if (tempkey == "Enter")
            {
                //";" Zeichen herauslöschen
                TBFolderName.Text = Regex.Replace(TBFolderName.Text, ";", "");
                //Prüfen ob noch Zeichen vorhanden
                if (TBFolderName.Text.Length > 0)
                {
                    //Prüfen ob leere Eingabe und zurücksetzen
                    bool temp = Regex.IsMatch(TBFolderName.Text, @"^[a-zA-Z0-9 ]+$");
                    temp = true;
                    if (temp == false)
                    {
                        MessageBox.Show(Lockscreen_Swap.AppResx.ErrorName);
                        TBFolderName.Text = FolderName;
                    }
                    else
                    {
                        //Prüfen ob Ordner bereits besteht
                        if (!file.DirectoryExists("/Folders/" + TBFolderName.Text))
                        {
                            try
                            {
                                //Ordnerdatei laden
                                IsolatedStorageFileStream filestream = file.OpenFile("Folders.dat", FileMode.Open);
                                StreamReader sr         = new StreamReader(filestream);
                                string       FoldersAll = sr.ReadToEnd();
                                filestream.Close();
                                FoldersAll = FoldersAll.TrimEnd(new char[] { '\r', '\n' });
                                //Ordner kopieren
                                file.CreateDirectory("/Folders/" + TBFolderName.Text);
                                string[] files = file.GetFileNames("/Folders/" + FolderName + "/");
                                foreach (string file2 in files)
                                {
                                    file.CopyFile("/Folders/" + FolderName + "/" + file2, "Folders/" + TBFolderName.Text + "/" + file2);
                                }
                                file.CreateDirectory("/Thumbs/" + TBFolderName.Text);
                                string[] files2 = file.GetFileNames("/Thumbs/" + FolderName + "/");
                                foreach (string file2 in files2)
                                {
                                    file.CopyFile("/Thumbs/" + FolderName + "/" + file2, "Thumbs/" + TBFolderName.Text + "/" + file2);
                                }
                                //Imagedatei kopieren
                                file.CopyFile("Thumbs/" + FolderName + ".dat", "Thumbs/" + TBFolderName.Text + ".dat");
                                //Ordnerdatei ändern
                                FoldersAll += TBFolderName.Text + "/";
                                //Neue Ordner Datei erstellen
                                filestream = file.CreateFile("Folders.dat");
                                StreamWriter sw = new StreamWriter(filestream);
                                sw.WriteLine(FoldersAll);
                                sw.Flush();
                                filestream.Close();
                                //Navigation zurück
                                NavigationService.GoBack();
                            }
                            catch
                            {
                                MessageBox.Show(Lockscreen_Swap.AppResx.ErrorName);
                                TBFolderName.Text = FolderName;
                            }
                        }
                        //Wenn Ordner bereits besteht
                        else
                        {
                            MessageBox.Show(Lockscreen_Swap.AppResx.ErrorName);
                            TBFolderName.Text = FolderName;
                        }
                    }
                }
                else
                {
                    MessageBox.Show(Lockscreen_Swap.AppResx.ErrorEnterName);
                    TBFolderName.Text = FolderName;
                }

                //Focus zurücksetzen
                //Focus();
            }
        }
Exemplo n.º 11
0
        //-----------------------------------------------------------------------------------------------------------------



        //Prüfen ob Return gedrückt wurde
        //-----------------------------------------------------------------------------------------------------------------
        private void TBFolderName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            //Prüfen ob Name vorhanden
            if (TBFolderName.Text.Length > 0)
            {
                //Prüfen ob Return gedrückt wurde
                string tempkey = Convert.ToString(e.Key);
                if (tempkey == "Enter")
                {
                    //";" Zeichen herauslöschen
                    TBFolderName.Text = Regex.Replace(TBFolderName.Text, ";", "");
                    //Prüfen ob noch Zeichen vorhanden
                    if (TBFolderName.Text.Length > 0)
                    {
                        //Prüfen ob leere Eingabe und zurücksetzen
                        bool temp = Regex.IsMatch(TBFolderName.Text, @"^[a-zA-Z0-9 ]+$");
                        temp = true;
                        if (temp == false)
                        {
                            MessageBox.Show(Lockscreen_Swap.AppResx.ErrorName);
                            TBFolderName.Text = "";
                        }
                        else
                        {
                            //Prüfen ob Ordner bereits besteht
                            if (!file.DirectoryExists("/Folders/" + TBFolderName.Text))
                            {
                                try
                                {
                                    //Ordner erstellen
                                    file.CreateDirectory("/Folders/" + TBFolderName.Text);
                                    file.CreateDirectory("/Thumbs/" + TBFolderName.Text);
                                    //FoldersDat erstellen
                                    IsolatedStorageFileStream filestream = file.CreateFile("FoldersDat/" + TBFolderName.Text + ".dat");
                                    StreamWriter sw = new StreamWriter(filestream);
                                    sw.WriteLine("0");
                                    sw.Flush();
                                    filestream.Close();
                                    //Zurück
                                    NavigationService.GoBack();
                                }
                                catch
                                {
                                    MessageBox.Show(Lockscreen_Swap.AppResx.ErrorName);
                                    TBFolderName.Text = "";
                                }
                            }
                            //Wenn Ordner bereits besteht
                            else
                            {
                                MessageBox.Show(Lockscreen_Swap.AppResx.ErrorName);
                                TBFolderName.Text = "";
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(Lockscreen_Swap.AppResx.ErrorEnterName);
                        TBFolderName.Text = "";
                    }

                    //Focus zurücksetzen
                    //Focus();
                }
            }
        }
 /// <summary>
 /// Returns true if <paramref name="pathName"/> represents
 /// the path to an existing "directory" in the persistence store
 /// </summary>
 /// <param name="pathName"></param>
 /// <returns></returns>
 public bool DirectoryExists(string pathName)
 {
     return(_isolatedStorage.DirectoryExists(pathName));
 }
Exemplo n.º 13
0
 public bool DirectoryExists(string path)
 {
     return(WrappedSubject.DirectoryExists(path));
 }
Exemplo n.º 14
0
        public static void AddSysEvent(string sText, bool bErr = false, string sCustTimeStampPart = "")
        {
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();

            string sPath = "System";

            if (!store.DirectoryExists(sPath))
            {
                store.CreateDirectory(sPath);
            }
            sPath += "\\Events";
            if (!store.DirectoryExists(sPath))
            {
                store.CreateDirectory(sPath);
            }

            sPath += "\\";
            if (bErr)
            {
                sPath += "ERR_";
            }
            else
            {
                sPath += "INF_";
            }

            if (sCustTimeStampPart.Length == 0)
            {
                DateTime dNow = DateTime.Now;
                sPath += dNow.Year.ToString() + "-";
                if (dNow.Month < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Month.ToString() + "-";
                if (dNow.Day < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Day.ToString();
                sPath += "_";
                if (dNow.Hour < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Hour.ToString() + "-";
                if (dNow.Minute < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Minute.ToString() + "-";
                if (dNow.Second < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Second.ToString();
            }
            else
            {
                sPath += sCustTimeStampPart;
            }

            string sExt;

            if (bErr)
            {
                sExt = ".error";
            }
            else
            {
                sExt = ".info";
            }

            string sPathWrk = sPath;

            if (sCustTimeStampPart.Length == 0)
            {
                int i = 0;
                for (;;)
                {
                    sPathWrk = sPath + "_" + i.ToString();
                    if (!store.FileExists(sPathWrk + sExt))
                    {
                        break;
                    }
                    i++;
                }
            }
            sPath = sPathWrk + sExt;
            IsolatedStorageFileStream stream = store.CreateFile(sPath);
            StreamWriter sw = new StreamWriter(stream);

            sw.Write(sText);
            sw.Close();
            stream.Close();
        }
Exemplo n.º 15
0
 private static bool DirectoryExists(string path)
 {
     using (IsolatedStorageFile iss = IsolatedStorageFile.GetUserStoreForApplication())
         return(iss.DirectoryExists(path));
 }
Exemplo n.º 16
0
        //Aktion
        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            //Bild vom Internet in den Isolated Storage speichern
            try
            {
                //Dateiname anhand der DownloadID erstellen
                if (DownloadID == 0)
                {
                    //Dateiname erstellen
                    FileName = "txt.txt";
                    //Alte Datei löschen
                    if (file.FileExists("TempStyles/txt.txt"))
                    {
                        file.DeleteFile("TempStyles/txt.txt");
                    }
                }
                else
                {
                    //Dateiname erstellen
                    FileName = "1.png";
                    //Alte Datei löschen
                    if (file.FileExists("TempStyles/1.png"))
                    {
                        file.DeleteFile("TempStyles/1.png");
                    }
                }


                //Prüfen ob Downloadordner existiert
                if (file.DirectoryExists("TempStyles"))
                {
                }
                else
                {
                    file.CreateDirectory("TempStyles");
                }

                //Prüfen ob Datei bereits vorhanden
                if (file.FileExists("TempStyles/" + FileName))
                {
                    file.DeleteFile("TempStyles/" + FileName);
                }

                //Datei in Isolated Storage laden
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("TempStyles/" + FileName, System.IO.FileMode.Create, file))
                {
                    byte[] buffer = new byte[1024];
                    while (e.Result.Read(buffer, 0, buffer.Length) > 0)
                    {
                        stream.Write(buffer, 0, buffer.Length);
                    }
                }

                //Nach dem Das Bild heruntergeladen wurde, Bild laden und in Storage schreiben
                if (DownloadID == 1)
                {
                    //Writeable Bitmap erstellen
                    var    tempImage = new WriteableBitmap(1, 1);
                    byte[] data1;
                    {
                        using (IsolatedStorageFileStream isfs = file.OpenFile("TempStyles/1.png", FileMode.Open, FileAccess.Read))
                        {
                            data1 = new byte[isfs.Length];
                            isfs.Read(data1, 0, data1.Length);
                            isfs.Close();
                        }
                    }
                    MemoryStream ms = new MemoryStream(data1);

                    //Bild in WriteableBitmap
                    tempImage.SetSource(ms);
                    ImagesOnline1.Source = tempImage;

                    //Bild Spiegeln
                    tempImage = tempImage.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                    //Altes Bild löschen
                    if (file.FileExists("TempStyles/2.png"))
                    {
                        file.DeleteFile("TempStyles/2.png");
                    }
                    //Bild speichern
                    Decoders.AddDecoder <PngDecoder>();
                    var img     = tempImage.ToImage();
                    var encoder = new PngEncoder();
                    using (var stream = new IsolatedStorageFileStream("TempStyles/2.png", FileMode.Create, file))
                    {
                        encoder.Encode(img, stream);
                        stream.Close();
                    }
                    //Bild ausgeben
                    ImagesOnline2.Source = tempImage;


                    //Bild Spiegeln
                    tempImage = tempImage.Flip(WriteableBitmapExtensions.FlipMode.Horizontal);
                    //Altes Bild löschen
                    if (file.FileExists("TempStyles/3.png"))
                    {
                        file.DeleteFile("TempStyles/3.png");
                    }
                    //Bild speichern
                    Decoders.AddDecoder <PngDecoder>();
                    img     = tempImage.ToImage();
                    encoder = new PngEncoder();
                    using (var stream = new IsolatedStorageFileStream("TempStyles/3.png", FileMode.Create, file))
                    {
                        encoder.Encode(img, stream);
                        stream.Close();
                    }
                    //Bild ausgeben
                    ImagesOnline3.Source = tempImage;


                    //Bild Spiegeln
                    tempImage = tempImage.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                    //Altes Bild löschen
                    if (file.FileExists("TempStyles/4.png"))
                    {
                        file.DeleteFile("TempStyles/4.png");
                    }
                    //Bild speichern
                    Decoders.AddDecoder <PngDecoder>();
                    img     = tempImage.ToImage();
                    encoder = new PngEncoder();
                    using (var stream = new IsolatedStorageFileStream("TempStyles/4.png", FileMode.Create, file))
                    {
                        encoder.Encode(img, stream);
                        stream.Close();
                    }
                    //Bild ausgeben
                    ImagesOnline4.Source = tempImage;
                }
            }
            catch
            {
            }
            //DownloadID erhöhen um nächstes Bild aus aus dem Netz herunterzuladen
            DownloadID++;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Write out the current state of the director and all of its scenes.
        /// </summary>
        public void SerializeState()
        {
            // open up isolated storage
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // if our screen manager directory already exists, delete the contents
                if (storage.DirectoryExists(m_sStorageDirName))
                {
                    DeleteState(storage);
                }

                // otherwise just create the directory
                else
                {
                    storage.CreateDirectory(m_sStorageDirName);
                }

                // create a file we'll use to store the list of screens in the stack

                CCLog.Log("Saving CCDirector state to file: " + Path.Combine(m_sStorageDirName, m_sSaveFileName));

                try
                {
                    using (IsolatedStorageFileStream stream = storage.OpenFile(Path.Combine(m_sStorageDirName, m_sSaveFileName), FileMode.OpenOrCreate))
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            // write out the full name of all the types in our stack so we can
                            // recreate them if needed.
                            foreach (CCScene scene in m_pobScenesStack)
                            {
                                if (scene.IsSerializable)
                                {
                                    writer.WriteLine(scene.GetType().AssemblyQualifiedName);
                                }
                                else
                                {
                                    CCLog.Log("Scene is not serializable: " + scene.GetType().FullName);
                                }
                            }
                            // Write out our local state
                            if (m_pRunningScene != null && m_pRunningScene.IsSerializable)
                            {
                                writer.WriteLine("m_pRunningScene");
                                writer.WriteLine(m_pRunningScene.GetType().AssemblyQualifiedName);
                            }
                            // Add my own state
                            // [*]name=value
                            //
                        }
                    }

                    // now we create a new file stream for each screen so it can save its state
                    // if it needs to. we name each file "ScreenX.dat" where X is the index of
                    // the screen in the stack, to ensure the files are uniquely named
                    int    screenIndex = 0;
                    string fileName    = null;
                    foreach (CCScene scene in m_pobScenesStack)
                    {
                        if (scene.IsSerializable)
                        {
                            fileName = string.Format(Path.Combine(m_sStorageDirName, m_sSceneSaveFileName), screenIndex);

                            // open up the stream and let the screen serialize whatever state it wants
                            using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
                            {
                                scene.Serialize(stream);
                            }

                            screenIndex++;
                        }
                    }
                    // Write the current running scene
                    if (m_pRunningScene != null && m_pRunningScene.IsSerializable)
                    {
                        fileName = string.Format(Path.Combine(m_sStorageDirName, m_sSceneSaveFileName), "XX");
                        // open up the stream and let the screen serialize whatever state it wants
                        using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
                        {
                            m_pRunningScene.Serialize(stream);
                        }
                    }
                }
                catch (Exception ex)
                {
                    CCLog.Log("Failed to serialize the CCDirector state. Erasing the save files.");
                    CCLog.Log(ex.ToString());
                    DeleteState(storage);
                }
            }
        }
Exemplo n.º 18
0
        public void sync(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest  webRequest      = null;
            string          callbackId;

            try
            {
                // options.src, options.type, options.headers, options.id
                string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options);

                downloadOptions     = new TransferOptions();
                downloadOptions.Url = optionStrings[0];

                bool trustAll = false;
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Id = optionStrings[1];

                downloadOptions.FilePath = "content_sync/downloads/" + downloadOptions.Id;

                if (String.Equals(optionStrings[2], "replace"))
                {
                    downloadOptions.Type = Replace;
                }
                else
                {
                    downloadOptions.Type = Merge;
                }

                downloadOptions.Headers = optionStrings[3];

                bool copyCordovaAssets = false;
                bool.TryParse(optionStrings[4], out copyCordovaAssets);
                downloadOptions.CopyCordovaAssets = copyCordovaAssets;

                downloadOptions.CallbackId = callbackId = optionStrings[5];
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                // not sure if we still need this
                // is the URL a local app file?
                if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
                {
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//", "");

                        // pre-emptively create any directories in the FilePath that do not exist
                        string directoryName = getDirectoryName(downloadOptions.FilePath);
                        if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                        {
                            isoFile.CreateDirectory(directoryName);
                        }

                        // just copy from one area of iso-store to another ...
                        if (isoFile.FileExists(downloadOptions.Url))
                        {
                            isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
                        }
                        else
                        {
                            // need to unpack resource from the dll
                            Uri uri      = new Uri(cleanUrl, UriKind.Relative);
                            var resource = Application.GetResourceStream(uri);

                            if (resource != null)
                            {
                                // create the file destination
                                if (!isoFile.FileExists(downloadOptions.FilePath))
                                {
                                    var destFile = isoFile.CreateFile(downloadOptions.FilePath);
                                    destFile.Close();
                                }

                                using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Create, FileAccess.Write, isoFile))
                                {
                                    long totalBytes = resource.Stream.Length;
                                    int  bytesRead  = 0;
                                    using (BinaryReader reader = new BinaryReader(resource.Stream))
                                    {
                                        using (BinaryWriter writer = new BinaryWriter(fileStream))
                                        {
                                            int    BUFFER_SIZE = 1024;
                                            byte[] buffer;

                                            while (true)
                                            {
                                                buffer = reader.ReadBytes(BUFFER_SIZE);
                                                // fire a progress event ?
                                                bytesRead += buffer.Length;
                                                if (buffer.Length > 0)
                                                {
                                                    writer.Write(buffer);
                                                    DispatchSyncProgress(bytesRead, totalBytes, 1, callbackId);
                                                }
                                                else
                                                {
                                                    writer.Close();
                                                    reader.Close();
                                                    fileStream.Close();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    string result = "{ \"localPath\": \"" + downloadOptions.FilePath + "\" , \"Id\" : \"" + downloadOptions.Id + "\"}";
                    if (result != null)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, 0), callbackId);
                    }

                    return;
                }
                else
                {
                    // otherwise it is web-bound, we will actually download it
                    //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                    webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
                }
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                       new SyncError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                try
                {
                    webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
                }
                catch (WebException)
                {
                    // eat it
                }
                // dispatch an event for progress ( 0 )
                lock (state)
                {
                    if (!state.isCancelled)
                    {
                        var plugRes = new PluginResult(PluginResult.Status.OK, new SyncProgress());
                        plugRes.KeepCallback = true;
                        plugRes.CallbackId   = callbackId;
                        DispatchCommandResult(plugRes, callbackId);
                    }
                }
            }
        }
Exemplo n.º 19
0
        public static void CheckAndAdd(string currentVersion)
        {
            string activateFavAgent;
            string activateMpNotif;
            string runUnderLockscreen;
            // Activer les background agent et notifications ??
            MessageBoxResult activateMpNotifResult = MessageBox.Show("Voulez-vous activer les notifications de nouveau message privé ? Cette fonction nécessite l'activation d'un agent de fond qui utilise 20 ko de connexion data par heure. Celui-ci est désactivable dans les préférences de l'appli.", "Activer la notification de nouveau message privé ?", MessageBoxButton.OKCancel);

            if (activateMpNotifResult == MessageBoxResult.Cancel)
            {
                activateMpNotif = "false";
                MessageBoxResult activateFavAgentResult = MessageBox.Show("Voulez-vous activer l'agent de mise à jour des live tiles des sujets ? Cette fonction permet de mettre à jour automatiquement l'état (nouveaux messages ou non) des sujets que vous avez épinglés en page d'accueil. Ce service consomme environ 20 ko par heure. Celui-ci est désactivable dans les préférences de l'appli.", "Activer l'agent de mise à jour des live tiles ?", MessageBoxButton.OKCancel);
                if (activateFavAgentResult == MessageBoxResult.Cancel)
                {
                    activateFavAgent = "false";
                }
                else if (activateFavAgentResult == MessageBoxResult.OK)
                {
                    activateFavAgent = "true";
                }
                else
                {
                    activateFavAgent = "false";
                }
            }
            else if (activateMpNotifResult == MessageBoxResult.OK)
            {
                activateFavAgent = "true";
                activateMpNotif  = "true";
            }
            else
            {
                activateFavAgent = "false";
                activateMpNotif  = "false";
            }

            // Activer le run under lockscreen ?
            MessageBoxResult lockScreenNotifResult = MessageBox.Show("Si vous êtes en train de charger un sujet et que vous mettez votre téléphone en veille/que l'écran s'éteint, ce service vous permettra d'éviter bon nombre d'erreurs (il permet à la connexion de persister le temps que le sujet soit téléchargé). Ce service est désactivable dans les préférences de l'appli et votre choix sera pris en compte lors du prochain lancement.", "Autoriser le fonctionnement lors de l'écran éteint ?", MessageBoxButton.OKCancel);

            if (lockScreenNotifResult == MessageBoxResult.Cancel)
            {
                runUnderLockscreen = "false";
            }
            else
            {
                runUnderLockscreen = "true";
            }

            IsolatedStorageSettings store        = IsolatedStorageSettings.ApplicationSettings;
            IsolatedStorageFile     isoStore     = IsolatedStorageFile.GetUserStoreForApplication();
            List <AppSettings>      listSettings = new List <AppSettings>();

            listSettings.Add(new AppSettings()
            {
                settingName = "favorisType", settingValue = "1"
            });                                                                                      // Type de favoris ? (Par défaut drapeaux cyans + étoiles)
            listSettings.Add(new AppSettings()
            {
                settingName = "displayImages", settingValue = "always"
            });                                                                                              // Afficher les images ? (Par défaut "Toujours")
            listSettings.Add(new AppSettings()
            {
                settingName = "displayAvatars", settingValue = "always"
            });                                                                                              // Afficher les avatars ? (Par défaut "Toujours")
            listSettings.Add(new AppSettings()
            {
                settingName = "disableLandscape", settingValue = "false"
            });                                                                                               // Désactiver le mode paysage ? (Par défaut "Non")
            listSettings.Add(new AppSettings()
            {
                settingName = "refreshFavWP", settingValue = "false"
            });                                                                                           // Rafraichir à chaque retour ? (Par défaut "Non")
            listSettings.Add(new AppSettings()
            {
                settingName = "activateCache", settingValue = "true"
            });                                                                                           // Activer le préchargement ? (Par défaut "Oui")
            listSettings.Add(new AppSettings()
            {
                settingName = "pinchToZoomOption", settingValue = "false"
            });                                                                                                // Activer le pinch to zoom ? (Par défaut "Non")
            listSettings.Add(new AppSettings()
            {
                settingName = "isMpNotified", settingValue = "false"
            });                                                                                           // Création du mp notified
            listSettings.Add(new AppSettings()
            {
                settingName = "launch", settingValue = (bool)true
            });                                                                                        // Premier lancement
            listSettings.Add(new AppSettings()
            {
                settingName = "activateFavAgent", settingValue = activateFavAgent
            });
            listSettings.Add(new AppSettings()
            {
                settingName = "activateMpNotif", settingValue = activateMpNotif
            });
            listSettings.Add(new AppSettings()
            {
                settingName = "runUnderLockScreen", settingValue = runUnderLockscreen
            });
            listSettings.Add(new AppSettings()
            {
                settingName = "isConnected", settingValue = "true"
            });
            listSettings.Add(new AppSettings()
            {
                settingName = "vibrateLoad", settingValue = "true"
            });
            listSettings.Add(new AppSettings()
            {
                settingName = "fontSizeValue", settingValue = 13
            });
            listSettings.Add(new AppSettings()
            {
                settingName = "currentVersion", settingValue = currentVersion
            });


            foreach (AppSettings setting in listSettings)
            {
                if (!store.Contains(setting.settingName))
                {
                    store.Add(setting.settingName, setting.settingValue);
                }
            }

            store.Remove("currentVersion");
            store.Add("currentVersion", currentVersion);

            if (store.Contains("userPseudo"))
            {
                string pseudoTemp = (string)store["userPseudo"];
                store.Remove("userPseudo");
                store.Add("userPseudo", pseudoTemp);
            }

            if (!isoStore.DirectoryExists("topics"))
            {
                isoStore.CreateDirectory("topics");                                      // Création du dossier topics
            }
        }
Exemplo n.º 20
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

            MoSync.SystemPropertyManager.RegisterSystemPropertyProvider("mosync.path.local",
                                                                        delegate(String key)
            {
                // The isolated storage becomes the "root"
                return("/");
            }
                                                                        );

            ioctls.maFileOpen = delegate(int _path, int _mode)
            {
                String path = core.GetDataMemory().ReadStringAtAddress(_path);
                path = ConvertPath(path);

                File       file   = null;
                FileAccess access = 0;

                if (_mode == MoSync.Constants.MA_ACCESS_READ)
                {
                    access = FileAccess.Read;
                }
                else if (_mode == MoSync.Constants.MA_ACCESS_READ_WRITE)
                {
                    access = FileAccess.ReadWrite;
                }
                else
                {
                    throw new Exception("Invalid file access mode");
                }

                file = new File(path, access);

                if (file.IsDirectory)
                {
                    if (isolatedStorage.FileExists(path))
                    {
                        return(MoSync.Constants.MA_FERR_WRONG_TYPE);
                    }
                }
                else
                {
                    if (isolatedStorage.DirectoryExists(path))
                    {
                        return(MoSync.Constants.MA_FERR_WRONG_TYPE);
                    }
                    try
                    {
                        file.TryOpen();
                    }
                    catch (IsolatedStorageException e)
                    {
                        MoSync.Util.Log(e);
                        return(MoSync.Constants.MA_FERR_GENERIC);
                    }
                }

                mFileHandles.Add(mNextFileHandle, file);
                return(mNextFileHandle++);
            };

            ioctls.maFileClose = delegate(int _file)
            {
                File file = mFileHandles[_file];
                file.Close();
                mFileHandles.Remove(_file);
                return(0);
            };

            ioctls.maFileRead = delegate(int _file, int _dst, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                {
                    return(MoSync.Constants.MA_FERR_WRONG_TYPE);
                }
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                {
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }
                core.GetDataMemory().WriteFromStream(_dst, fileStream, _len);
                return(0);
            };

            ioctls.maFileReadToData = delegate(int _file, int _data, int _offset, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                {
                    return(MoSync.Constants.MA_FERR_WRONG_TYPE);
                }
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                {
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }
                Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Memory   data    = (Memory)dataRes.GetInternalObject();
                data.WriteFromStream(_offset, fileStream, _len);
                return(0);
            };

            ioctls.maFileWriteFromData = delegate(int _file, int _data, int _offset, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                {
                    return(MoSync.Constants.MA_FERR_WRONG_TYPE);
                }
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                {
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }
                Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Memory   data    = (Memory)dataRes.GetInternalObject();
                byte[]   bytes   = new byte[_len];
                data.ReadBytes(bytes, _offset, _len);
                fileStream.Write(bytes, 0, _len);
                fileStream.Flush();
                return(0);
            };

            ioctls.maFileWrite = delegate(int _file, int _src, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                {
                    return(MoSync.Constants.MA_FERR_WRONG_TYPE);
                }
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                {
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }
                byte[] bytes = new byte[_len];
                core.GetDataMemory().ReadBytes(bytes, _src, _len);
                fileStream.Write(bytes, 0, _len);
                fileStream.Flush();
                return(0);
            };

            ioctls.maFileSeek = delegate(int _file, int _offset, int _whence)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                {
                    return(MoSync.Constants.MA_FERR_WRONG_TYPE);
                }
                IsolatedStorageFileStream fileStream = file.FileStream;
                SeekOrigin origin;
                switch (_whence)
                {
                case MoSync.Constants.MA_SEEK_SET:
                    origin = SeekOrigin.Begin;
                    break;

                case MoSync.Constants.MA_SEEK_CUR:
                    origin = SeekOrigin.Current;
                    break;

                case MoSync.Constants.MA_SEEK_END:
                    origin = SeekOrigin.End;
                    break;

                default:
                    throw new Exception("maFileSeek whence");
                }

                try
                {
                    return((int)fileStream.Seek(_offset, origin));
                }
                catch (IOException e)
                {
                    MoSync.Util.Log(e);
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }
            };

            ioctls.maFileTell = delegate(int _file)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                {
                    return(MoSync.Constants.MA_FERR_WRONG_TYPE);
                }
                IsolatedStorageFileStream fileStream = file.FileStream;
                return((int)fileStream.Position);
            };

            ioctls.maFileExists = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return(file.Exists ? 1 : 0);
            };

            ioctls.maFileCreate = delegate(int _file)
            {
                File file = mFileHandles[_file];
                if (file.Exists)
                {
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }
                file.Create();
                return(0);
            };

            ioctls.maFileDelete = delegate(int _file)
            {
                File file = mFileHandles[_file];
                try
                {
                    file.Delete();
                }
                catch (IsolatedStorageException e)
                {
                    MoSync.Util.Log(e);
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }
                return(0);
            };

            ioctls.maFileSize = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return(file.Size());
            };

            ioctls.maFileAvailableSpace = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return(file.AvailableSpace());
            };

            ioctls.maFileTotalSpace = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return(file.TotalSpace());
            };

            ioctls.maFileDate = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return(Util.ToUnixTimeUtc(file.Date().ToFileTime()));
            };

            ioctls.maFileRename = delegate(int _file, int _newName)
            {
                File   file    = mFileHandles[_file];
                String newName = core.GetDataMemory().ReadStringAtAddress(_newName);
                newName = ConvertPath(newName);
                if (newName.Contains("\\"))
                {
                    if (newName[0] != '\\')
                    {
                        throw new Exception("Invalid newName");
                    }
                }
                else
                {   // add directory of old file.
                    newName = Path.GetDirectoryName(file.Path) + "\\" + newName;
                }
                file.Rename(newName);
                return(0);
            };

            ioctls.maFileTruncate = delegate(int _file, int _offset)
            {
                File file = mFileHandles[_file];
                file.Truncate(_offset);
                return(0);
            };

            ioctls.maFileListStart = delegate(int _path, int _filter, int _sorting)
            {
                // todo: respect _sorting.
                String path = core.GetDataMemory().ReadStringAtAddress(_path);
                path = ConvertPath(path);
                String filter           = core.GetDataMemory().ReadStringAtAddress(_filter);
                String pattern          = path + filter;
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                FileList            fl  = new FileList();
                fl.dirs  = isf.GetDirectoryNames(pattern);
                fl.files = isf.GetFileNames(pattern);
                fl.pos   = 0;

                mFileListHandles.Add(mNextFileListHandle, fl);
                return(mNextFileListHandle++);
            };

            ioctls.maFileListNext = delegate(int _list, int _nameBuf, int _bufSize)
            {
                FileList fl = mFileListHandles[_list];
                String   name;
                if (fl.pos < fl.dirs.Length)
                {
                    name = fl.dirs[fl.pos] + "/";
                }
                else if (fl.pos < fl.dirs.Length + fl.files.Length)
                {
                    name = fl.files[fl.pos - fl.dirs.Length];
                }
                else
                {
                    return(0);
                }
                if (name.Length >= _bufSize)
                {
                    return(name.Length);
                }
                core.GetDataMemory().WriteStringAtAddress(_nameBuf,
                                                          name, _bufSize);
                fl.pos++;
                return(name.Length);
            };

            ioctls.maFileListClose = delegate(int _list)
            {
                FileList fl = mFileListHandles[_list];
                mFileListHandles.Remove(_list);
                return(0);
            };
        }
Exemplo n.º 21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private void downloadCallback(IAsyncResult asynchronousResult)
        {
            DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
            HttpWebRequest       request  = reqState.request;

            string callbackId = reqState.options.CallbackId;

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                // send a progress change event
                DispatchFileTransferProgress(0, response.ContentLength, callbackId);

                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // create any directories in the path that do not exist
                    string directoryName = getDirectoryName(reqState.options.FilePath);
                    if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                    {
                        isoFile.CreateDirectory(directoryName);
                    }

                    // create the file if not exists
                    if (!isoFile.FileExists(reqState.options.FilePath))
                    {
                        var file = isoFile.CreateFile(reqState.options.FilePath);
                        file.Close();
                    }

                    using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile))
                    {
                        long totalBytes = response.ContentLength;
                        int  bytesRead  = 0;
                        using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                        {
                            using (BinaryWriter writer = new BinaryWriter(fileStream))
                            {
                                int    BUFFER_SIZE = 1024;
                                byte[] buffer;

                                while (true)
                                {
                                    buffer = reader.ReadBytes(BUFFER_SIZE);
                                    // fire a progress event ?
                                    bytesRead += buffer.Length;
                                    if (buffer.Length > 0 && !reqState.isCancelled)
                                    {
                                        writer.Write(buffer);
                                        DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
                                    }
                                    else
                                    {
                                        writer.Close();
                                        reader.Close();
                                        fileStream.Close();
                                        break;
                                    }
                                    System.Threading.Thread.Sleep(1);
                                }
                            }
                        }
                    }
                    if (reqState.isCancelled)
                    {
                        isoFile.DeleteFile(reqState.options.FilePath);
                    }
                }

                if (reqState.isCancelled)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(AbortError)),
                                          callbackId);
                }
                else
                {
                    File.FileEntry entry = new File.FileEntry(reqState.options.FilePath);
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
                }
            }
            catch (IsolatedStorageException)
            {
                // Trying to write the file somewhere within the IsoStorage.
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)),
                                      callbackId);
            }
            catch (SecurityException)
            {
                // Trying to write the file somewhere not allowed.
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)),
                                      callbackId);
            }
            catch (WebException webex)
            {
                // TODO: probably need better work here to properly respond with all http status codes back to JS
                // Right now am jumping through hoops just to detect 404.
                HttpWebResponse response = (HttpWebResponse)webex.Response;
                if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound) ||
                    webex.Status == WebExceptionStatus.UnknownError)
                {
                    // Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!!
                    // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away."
                    // FACEPALM
                    // Or just cast it to an int, whiner ... -jm
                    int    statusCode = (int)response.StatusCode;
                    string body       = "";

                    using (Stream streamResponse = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(streamResponse))
                        {
                            body = streamReader.ReadToEnd();
                        }
                    }
                    FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode, body);
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError),
                                          callbackId);
                }
                else
                {
                    lock (reqState)
                    {
                        if (!reqState.isCancelled)
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                                   new FileTransferError(ConnectionError)),
                                                  callbackId);
                        }
                        else
                        {
                            Debug.WriteLine("It happened");
                        }
                    }
                }
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                       new FileTransferError(FileNotFoundError)),
                                      callbackId);
            }

            //System.Threading.Thread.Sleep(1000);
            if (InProcDownloads.ContainsKey(reqState.options.Id))
            {
                InProcDownloads.Remove(reqState.options.Id);
            }
        }
Exemplo n.º 22
0
 public static void LoadFavourites(ObservableCollection <ConversationListObject> favList, Dictionary <string, ConversationListObject> _convmap)
 {
     lock (favReadWriteLock)
     {
         using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
         {
             if (!store.DirectoryExists(MISC_DIR))
             {
                 store.CreateDirectory(MISC_DIR);
                 return;
             }
             string fname = MISC_DIR + "\\" + FAVOURITES_FILE;
             if (!store.FileExists(fname))
             {
                 return;
             }
             using (var file = store.OpenFile(fname, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
             {
                 using (var reader = new BinaryReader(file))
                 {
                     int count = 0;
                     try
                     {
                         count = reader.ReadInt32();
                     }
                     catch { }
                     if (count > 0)
                     {
                         for (int i = 0; i < count; i++)
                         {
                             ConversationListObject item = new ConversationListObject();
                             try
                             {
                                 item.ReadFavOrPending(reader);
                                 if (_convmap.ContainsKey(item.Msisdn)) // if this item is in convList, just mark IsFav to true
                                 {
                                     favList.Add(_convmap[item.Msisdn]);
                                     _convmap[item.Msisdn].IsFav = true;
                                 }
                                 else
                                 {
                                     favList.Add(item);
                                 }
                             }
                             catch (Exception ex)
                             {
                                 Debug.WriteLine(ex);
                             }
                         }
                     }
                     reader.Close();
                 }
                 try
                 {
                     file.Close();
                     file.Dispose();
                 }
                 catch { }
             }
         }
     }
 }
Exemplo n.º 23
0
        public void MoveDirectory()
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly();

            // Mare sure to remove them if they exist already
            if (isf.DirectoryExists("subdir"))
            {
                isf.DeleteDirectory("subdir");
            }
            if (isf.DirectoryExists("subdir-new"))
            {
                isf.DeleteDirectory("subdir-new");
            }

            isf.CreateDirectory("subdir");
            Assert.AreEqual(true, isf.DirectoryExists("subdir"), "#A0");

            isf.MoveDirectory("subdir", "subdir-new");
            Assert.AreEqual(false, isf.DirectoryExists("subdir"), "#A1");
            Assert.AreEqual(true, isf.DirectoryExists("subdir-new"), "#A2");

            try
            {
                isf.MoveDirectory(String.Empty, "subdir-new-new");
                Assert.Fail("#Exc1");
            }
            catch (ArgumentException)
            {
            }

            try
            {
                isf.MoveDirectory("  ", "subdir-new-new");
                Assert.Fail("#Exc2");
            }
            catch (ArgumentException)
            {
            }

            try
            {
                isf.MoveDirectory("doesntexist", "subdir-new-new");
                Assert.Fail("#Exc3");
            }
            catch (DirectoryNotFoundException)
            {
            }

            try
            {
                isf.MoveDirectory("doesnexist/doesntexist", "subdir-new-new");
                Assert.Fail("#Exc4");
            }
            catch (DirectoryNotFoundException)
            {
            }

            try
            {
                isf.MoveDirectory("subdir-new", "doesntexist/doesntexist");
                Assert.Fail("#Exc5");
            }
            catch (DirectoryNotFoundException)
            {
            }

            // Out of storage dir
            try
            {
                isf.MoveDirectory("subdir-new", "../../subdir-new");
                Assert.Fail("#Exc6");
            }
            catch (IsolatedStorageException)
            {
            }

            isf.Remove();
            isf.Close();
            isf.Dispose();
        }
Exemplo n.º 24
0
 public static void LoadPendingRequests()
 {
     lock (pendingReadWriteLock)
     {
         using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
         {
             if (!store.DirectoryExists(MISC_DIR))
             {
                 store.CreateDirectory(MISC_DIR);
                 return;
             }
             string fname = MISC_DIR + "\\" + PENDING_REQ_FILE;
             if (!store.FileExists(fname))
             {
                 return;
             }
             using (var file = store.OpenFile(fname, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
             {
                 using (var reader = new BinaryReader(file))
                 {
                     int count = 0;
                     try
                     {
                         count = reader.ReadInt32();
                     }
                     catch { }
                     if (count > 0)
                     {
                         for (int i = 0; i < count; i++)
                         {
                             ConversationListObject item = new ConversationListObject();
                             try
                             {
                                 item.ReadFavOrPending(reader);
                                 if (App.ViewModel.ConvMap.ContainsKey(item.Msisdn))
                                 {
                                     App.ViewModel.PendingRequests.Add(App.ViewModel.ConvMap[item.Msisdn]);
                                 }
                                 else
                                 {
                                     item.Avatar = MiscDBUtil.getThumbNailForMsisdn(item.Msisdn);
                                     App.ViewModel.PendingRequests.Add(item);
                                 }
                             }
                             catch
                             {
                                 item = null;
                             }
                         }
                     }
                     reader.Close();
                 }
                 try
                 {
                     file.Close();
                     file.Dispose();
                 }
                 catch { }
             }
         }
     }
 }
Exemplo n.º 25
0
        private void ParseImg(HtmlNode htmlNode, ref List <Elements.BaseElement> elements)
        {
            string path = _ePubViewer.Book.GetFilePath(HttpUtility.UrlDecode(htmlNode.Attributes["src"].Value.Replace("../", "")));

            if (path == null) // img src file does not exists (don't render)
            {
                Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Warning: EPubReader.Parseer.ParseImg - Image \"{0}\" does not exists.", HttpUtility.UrlDecode(htmlNode.Attributes["src"].Value.Replace("../", ""))));
                return;
            }

            Stream s = IsolatedStorageHelper.ReadZipStream(path);

            string fileName = Guid.NewGuid().ToString();
            Size   size     = Size.Empty;

            // detect image type
            if (
                path.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".jpe", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".jif", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".jfif", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".jfi", StringComparison.OrdinalIgnoreCase)
                )
            {
                BitmapSource bs = new BitmapImage();
                bs.SetSource(s);

                size = new Size(bs.PixelWidth, bs.PixelHeight);

                // save image
                fileName += ".jpg";
                string isfPath = Path.Combine(_ePubViewer.Book.GetImagesDirectory(), fileName);
                try
                {
                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isf.DirectoryExists(Path.GetDirectoryName(isfPath)))
                        {
                            isf.CreateDirectory(Path.GetDirectoryName(isfPath));
                        }

                        using (IsolatedStorageFileStream isfs = isf.CreateFile(isfPath))
                        {
                            WriteableBitmap wb = new WriteableBitmap(bs);
                            wb.SaveJpeg(isfs, bs.PixelWidth, bs.PixelHeight, 0, 100);
                            isfs.Close();
                        }
                    }
                }
                catch
                {
                    Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Warning: EPubReader.Parseer.ParseImg - Error saving image \"{0}\".", isfPath));
                    return;
                }
            }
            else if (
                path.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".dib", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".png", StringComparison.OrdinalIgnoreCase)
                )
            {
                ImageTools.ExtendedImage    extendedImage = new ImageTools.ExtendedImage();
                ImageTools.IO.IImageDecoder decoder;

                if (
                    path.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)
                    ||
                    path.EndsWith(".dib", StringComparison.OrdinalIgnoreCase)
                    )
                {
                    decoder = new ImageTools.IO.Bmp.BmpDecoder();
                }
                else if (path.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
                {
                    decoder = new ImageTools.IO.Gif.GifDecoder();
                }
                else // if (path.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
                {
                    decoder = new ImageTools.IO.Png.PngDecoder();
                }

                decoder.Decode(extendedImage, s);

                size = new Size(extendedImage.PixelWidth, extendedImage.PixelHeight);

                ImageTools.IO.Png.PngEncoder pngEncoder = new ImageTools.IO.Png.PngEncoder();

                // save image
                fileName += ".png";
                string isfPath = Path.Combine(_ePubViewer.Book.GetImagesDirectory(), fileName);
                try
                {
                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isf.DirectoryExists(Path.GetDirectoryName(isfPath)))
                        {
                            isf.CreateDirectory(Path.GetDirectoryName(isfPath));
                        }

                        using (IsolatedStorageFileStream isfs = isf.CreateFile(isfPath))
                        {
                            pngEncoder.Encode(extendedImage, isfs);
                            isfs.Close();
                        }
                    }
                }
                catch
                {
                    Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Warning: EPubReader.Parseer.ParseImg - Error saving image \"{0}\".", isfPath));
                    return;
                }
            }
            else
            {
                s.Close();
                s.Dispose();

                Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Warning: EPubReader.Parseer.ParseImg - Not recognizable image type \"{0}\".", path));
                return;
            }

            RemoveLastBreak(ref elements);

            // add image
            Elements.BaseElement element = new Elements.Image()
            {
                FileName = fileName,
                Width    = (int)size.Width,
                Height   = (int)size.Height
            };

            ExtractId(htmlNode, ref element);

            elements.Add(element);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        public void startPlaying(string filePath)
        {
            if (this.recorder != null)
            {
                InvokeCallback(MediaError, MediaErrorRecordModeSet, false);
                //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorRecordModeSet),false);
                return;
            }


            if (this.player == null || this.player.Source.AbsoluteUri.LastIndexOf(filePath) < 0)
            {
                try
                {
                    // this.player is a MediaElement, it must be added to the visual tree in order to play
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                        if (page != null)
                        {
                            Grid grid = page.FindName("LayoutRoot") as Grid;
                            if (grid != null)
                            {
                                this.player = grid.FindName("playerMediaElement") as MediaElement;
                                if (this.player == null) // still null ?
                                {
                                    this.player      = new MediaElement();
                                    this.player.Name = "playerMediaElement";
                                    grid.Children.Add(this.player);
                                    this.player.Visibility = Visibility.Visible;
                                }
                                if (this.player.CurrentState == System.Windows.Media.MediaElementState.Playing)
                                {
                                    this.player.Stop(); // stop it!
                                }

                                this.player.Source       = null; // Garbage collect it.
                                this.player.MediaOpened += MediaOpened;
                                this.player.MediaEnded  += MediaEnded;
                                this.player.MediaFailed += MediaFailed;
                            }
                        }
                    }

                    this.audioFile = filePath;

                    Uri uri = new Uri(filePath, UriKind.RelativeOrAbsolute);
                    if (uri.IsAbsoluteUri)
                    {
                        this.player.Source = uri;
                    }
                    else
                    {
                        using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (!isoFile.FileExists(filePath))
                            {
                                // try to unpack it from the dll into isolated storage
                                StreamResourceInfo fileResourceStreamInfo = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
                                if (fileResourceStreamInfo != null)
                                {
                                    using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream))
                                    {
                                        byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length);

                                        string[] dirParts = filePath.Split('/');
                                        string   dirName  = "";
                                        for (int n = 0; n < dirParts.Length - 1; n++)
                                        {
                                            dirName += dirParts[n] + "/";
                                        }
                                        if (!isoFile.DirectoryExists(dirName))
                                        {
                                            isoFile.CreateDirectory(dirName);
                                        }

                                        using (IsolatedStorageFileStream outFile = isoFile.OpenFile(filePath, FileMode.Create))
                                        {
                                            using (BinaryWriter writer = new BinaryWriter(outFile))
                                            {
                                                writer.Write(data);
                                            }
                                        }
                                    }
                                }
                            }
                            if (isoFile.FileExists(filePath))
                            {
                                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, isoFile))
                                {
                                    this.player.SetSource(stream);
                                }
                            }
                            else
                            {
                                InvokeCallback(MediaError, MediaErrorPlayModeSet, false);
                                //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, 1), false);
                                return;
                            }
                        }
                    }
                    this.SetState(PlayerState_Starting);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error in AudioPlayer::startPlaying : " + e.Message);
                    InvokeCallback(MediaError, MediaErrorStartingPlayback, false);
                    //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStartingPlayback),false);
                }
            }
            else
            {
                if (this.state != PlayerState_Running)
                {
                    this.player.Play();
                    this.SetState(PlayerState_Running);
                }
                else
                {
                    InvokeCallback(MediaError, MediaErrorResumeState, false);
                    //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorResumeState),false);
                }
            }
        }
Exemplo n.º 27
0
        public bool DeserializeState()
        {
            // open up isolated storage
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // see if our saved state directory exists
                if (storage.DirectoryExists("ScreenManager"))
                {
                    try
                    {
                        // see if we have a screen list
                        if (storage.FileExists("ScreenManager\\ScreenList.dat"))
                        {
                            // load the list of screen types
                            using (IsolatedStorageFileStream stream =
                                       storage.OpenFile("ScreenManager\\ScreenList.dat", FileMode.Open,
                                                        FileAccess.Read))
                            {
                                using (BinaryReader reader = new BinaryReader(stream))
                                {
                                    while (reader.BaseStream.Position < reader.BaseStream.Length)
                                    {
                                        // read a line from our file
                                        string line = reader.ReadString();

                                        // if it isn't blank, we can create a screen from it
                                        if (!string.IsNullOrEmpty(line))
                                        {
                                            Type       screenType = Type.GetType(line);
                                            GameScreen screen     = Activator.CreateInstance(screenType) as GameScreen;
                                            AddScreen(screen, PlayerIndex.One);
                                        }
                                    }
                                }
                            }
                        }

                        // next we give each screen a chance to deserialize from the disk
                        for (int i = 0; i < screens.Count; i++)
                        {
                            string filename = string.Format("ScreenManager\\Screen{0}.dat", i);
                            using (IsolatedStorageFileStream stream = storage.OpenFile(filename,
                                                                                       FileMode.Open, FileAccess.Read))
                            {
                                screens[i].Deserialize(stream);
                            }
                        }

                        return(true);
                    }
                    catch (Exception)
                    {
                        // if an exception was thrown while reading, odds are we cannot recover
                        // from the saved state, so we will delete it so the game can correctly
                        // launch.
                        DeleteState(storage);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 28
0
        public void unzip(string srcFilePath, string destPath, int type)
        {
            using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // DEBUG here to copy file from dll to isostore ...
                // this is only really needed if you want to test with a file in your package/project
                StreamResourceInfo fileResourceStreamInfo = Application.GetResourceStream(new Uri(srcFilePath, UriKind.Relative));
                if (fileResourceStreamInfo != null)
                {
                    using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream))
                    {
                        byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length);
                        // This will truncate/overwrite an existing file, or
                        using (IsolatedStorageFileStream outFile = appStorage.OpenFile(srcFilePath, FileMode.Create))
                        {
                            using (var writer = new BinaryWriter(outFile))
                            {
                                writer.Write(data);
                            }
                        }
                    }
                }

                if (type == Replace)
                {
                    DeleteDirectoryRecursively(appStorage, destPath);
                }

                IsolatedStorageFileStream zipStream = null;
                ZipArchive zipArch = null;

                try
                {
                    zipStream = new IsolatedStorageFileStream(srcFilePath, FileMode.Open, FileAccess.Read, appStorage);
                }
                catch (Exception)
                {
                    Debug.WriteLine("File not found :: " + srcFilePath);
                    return;
                }

                if (zipStream != null)
                {
                    zipArch = new ZipArchive(zipStream);
                }

                if (zipArch != null)
                {
                    int totalFiles = zipArch.FileNames.Count();
                    int current    = 0;
                    try
                    {
                        foreach (string filename in zipArch.FileNames)
                        {
                            string destFilePath = destPath + "/" + filename;

                            string directoryName = getDirectoryName(destFilePath);

                            //Debug.WriteLine("upacking file : " + filename + " to : " + destFilePath);

                            if (!appStorage.DirectoryExists(directoryName))
                            {
                                appStorage.CreateDirectory(directoryName);
                            }



                            using (Stream readStream = zipArch.GetFileStream(filename))
                            {
                                if (readStream != null)
                                {
                                    if (type == Merge)
                                    {
                                        // only write file if it doesn't exist already
                                        if (!appStorage.FileExists(destFilePath))
                                        {
                                            using (FileStream outStream = new IsolatedStorageFileStream(destFilePath, FileMode.OpenOrCreate, FileAccess.Write, appStorage))
                                            {
                                                WriteStreamToPath(readStream, outStream);
                                            }
                                        }
                                        FileUnzipProgress progEvt = new FileUnzipProgress(totalFiles, current++);
                                    }
                                    else
                                    {
                                        using (FileStream outStream = new IsolatedStorageFileStream(destFilePath, FileMode.OpenOrCreate, FileAccess.Write, appStorage))
                                        {
                                            WriteStreamToPath(readStream, outStream);
                                            FileUnzipProgress progEvt = new FileUnzipProgress(totalFiles, current++);
                                        }
                                    }
                                }
                            }
                        }
                        zipStream.Close();
                    }
                    catch (Exception)
                    {
                        Debug.WriteLine("File not found :: " + srcFilePath);
                    }
                }
            }
        }
Exemplo n.º 29
0
        public bool DeserializeState()
        {
            try
            {
                // open up isolated storage
                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // see if our saved state directory exists
                    if (storage.DirectoryExists(m_sStorageDirName))
                    {
                        string saveFile = System.IO.Path.Combine(m_sStorageDirName, m_sSaveFileName);
                        try
                        {
                            CCLog.Log("Loading director data file: {0}", saveFile);
                            // see if we have a screen list
                            if (storage.FileExists(saveFile))
                            {
                                // load the list of screen types
                                using (IsolatedStorageFileStream stream = storage.OpenFile(saveFile, FileMode.Open, FileAccess.Read))
                                {
                                    using (StreamReader reader = new StreamReader(stream))
                                    {
                                        CCLog.Log("Director save file contains {0} bytes.", reader.BaseStream.Length);
                                        try
                                        {
                                            while (true)
                                            {
                                                // read a line from our file
                                                string line = reader.ReadLine();
                                                if (line == null)
                                                {
                                                    break;
                                                }
                                                CCLog.Log("Restoring: {0}", line);

                                                // if it isn't blank, we can create a screen from it
                                                if (!string.IsNullOrEmpty(line))
                                                {
                                                    if (line.StartsWith("[*]"))
                                                    {
                                                        // Reading my state
                                                        string s   = line.Substring(3);
                                                        int    idx = s.IndexOf('=');
                                                        if (idx > -1)
                                                        {
                                                            string name = s.Substring(0, idx);
                                                            string v    = s.Substring(idx + 1);
                                                            CCLog.Log("Restoring: {0} = {1}", name, v);
                                                            DeserializeMyState(name, v);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        Type    screenType = Type.GetType(line);
                                                        CCScene scene      = Activator.CreateInstance(screenType) as CCScene;
                                                        PushScene(scene);
                                                        //                                                    m_pobScenesStack.Add(scene);
                                                    }
                                                }
                                            }
                                        }
                                        catch (Exception)
                                        {
                                            // EndOfStreamException
                                            // this is OK here.
                                        }
                                    }
                                }
                                // Now we deserialize our own state.
                            }
                            else
                            {
                                CCLog.Log("save file does not exist.");
                            }

                            // next we give each screen a chance to deserialize from the disk
                            for (int i = 0; i < m_pobScenesStack.Count; i++)
                            {
                                string filename = System.IO.Path.Combine(m_sStorageDirName, string.Format(m_sSceneSaveFileName, i));
                                if (storage.FileExists(filename))
                                {
                                    using (IsolatedStorageFileStream stream = storage.OpenFile(filename, FileMode.Open, FileAccess.Read))
                                    {
                                        CCLog.Log("Restoring state for scene {0}", filename);
                                        m_pobScenesStack[i].Deserialize(stream);
                                    }
                                }
                            }
                            if (m_pobScenesStack.Count > 0)
                            {
                                CCLog.Log("Director is running with scene..");

                                RunWithScene(m_pobScenesStack[m_pobScenesStack.Count - 1]); // always at the top of the stack
                            }
                            return(m_pobScenesStack.Count > 0 && m_pRunningScene != null);
                        }
                        catch (Exception ex)
                        {
                            // if an exception was thrown while reading, odds are we cannot recover
                            // from the saved state, so we will delete it so the game can correctly
                            // launch.
                            DeleteState(storage);
                            CCLog.Log("Failed to deserialize the director state, removing old storage file.");
                            CCLog.Log(ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CCLog.Log("Failed to deserialize director state.");
                CCLog.Log(ex.ToString());
            }

            return(false);
        }
Exemplo n.º 30
0
 public FileClear()
 {
     if (!isf.DirectoryExists("Images"))
     {
         isf.CreateDirectory("Images");
         isf.CreateDirectory("Images\\icons");
         System.Windows.Resources.StreamResourceInfo res = Application.GetResourceStream(new Uri("Icon\\folder-pic.png", UriKind.Relative));
         using (IsolatedStorageFileStream isfs = isf.CreateFile("Images\\icons\\folder.png"))
         {
             int    chunkSize = 4096;
             byte[] bytes     = new byte[chunkSize];
             int    byteCount;
             int    count = 0;
             while ((byteCount = res.Stream.Read(bytes, 0, chunkSize)) > 0)
             {
                 count++;
                 isfs.Write(bytes, 0, byteCount);
             }
         }
         res.Stream.Close();
         res = Application.GetResourceStream(new Uri("Icon\\txt.png", UriKind.Relative));
         using (IsolatedStorageFileStream isfs = isf.CreateFile("Images\\icons\\file.png"))
         {
             int    chunkSize = 4096;
             byte[] bytes     = new byte[chunkSize];
             int    byteCount;
             int    count = 0;
             while ((byteCount = res.Stream.Read(bytes, 0, chunkSize)) > 0)
             {
                 count++;
                 isfs.Write(bytes, 0, byteCount);
             }
         }
         res.Stream.Close();
     }
     else if (!isf.DirectoryExists("Images\\icons"))
     {
         isf.CreateDirectory("Images\\icons");
         System.Windows.Resources.StreamResourceInfo res = Application.GetResourceStream(new Uri("Icon\\folder-pic.png", UriKind.Relative));
         using (IsolatedStorageFileStream isfs = isf.CreateFile("Images\\icons\\folder.png"))
         {
             int    chunkSize = 4096;
             byte[] bytes     = new byte[chunkSize];
             int    byteCount;
             int    count = 0;
             while ((byteCount = res.Stream.Read(bytes, 0, chunkSize)) > 0)
             {
                 count++;
                 isfs.Write(bytes, 0, byteCount);
             }
         }
         res.Stream.Close();
         res = Application.GetResourceStream(new Uri("Icon\\txt.png", UriKind.Relative));
         using (IsolatedStorageFileStream isfs = isf.CreateFile("Images\\icons\\file.png"))
         {
             int    chunkSize = 4096;
             byte[] bytes     = new byte[chunkSize];
             int    byteCount;
             int    count = 0;
             while ((byteCount = res.Stream.Read(bytes, 0, chunkSize)) > 0)
             {
                 count++;
                 isfs.Write(bytes, 0, byteCount);
             }
         }
         res.Stream.Close();
     }
     InitializeComponent();
     Microsoft.Phone.Controls.TiltEffect.TiltableItems.Add(typeof(Microsoft.Phone.Controls.MenuItem));
     if (!iss.Contains("mentioned"))
     {
         //MessageBox.Show("本功能仅供删除部分垃圾文件,比如未解压完成的temp.zip,或者删除游戏时删除失败的残留文件,请不要乱删东西,否则会丢失数据的说……");
         MessageBox.Show(UVEngine.Resources.UVEngine.aboutfileclear);
         iss.Add("mentioned", 0);
         iss.Save();
     }
 }