Esempio n. 1
0
        public async Task<LocalAppData> LoadData()
        {
            var ObjectStorageHelper = new StorageHelper<LocalAppData>(StorageType.Local);
            LocalAppData LoadedData = await ObjectStorageHelper.LoadASync("AllAppData");

            return LoadedData;
        }
Esempio n. 2
0
        private async void LocalCacheInit()
        {
            // 拿头条新鲜事的缓存
            StorageHelper<ObservableCollection<ItemViewModel>> stHelper =
                new StorageHelper<ObservableCollection<ItemViewModel>>(StorageType.Local);
            try
            {
                ObservableCollection<ItemViewModel> result = await stHelper.LoadASync("TopItems");
                if (result != null)
                    MainViewModel.TopItems = result;
            }
            catch (System.Exception ex)
            {
                MainViewModel.TopItems = new ObservableCollection<ItemViewModel>();
            }

            // 拿图片列表缓存
            StorageHelper<ObservableCollection<PictureItemViewModel>> stPicHelper =
                 new StorageHelper<ObservableCollection<PictureItemViewModel>>(StorageType.Local);
            try
            {
                ObservableCollection<PictureItemViewModel> result = await stPicHelper.LoadASync("PicItems");
                if (result != null)
                    MainViewModel.PictureItems = result;
            }
            catch (System.Exception ex)
            {
                MainViewModel.PictureItems = new ObservableCollection<PictureItemViewModel>();
            }
        }
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            var person = new PersonModel(Name.Text, Email.Text, Phone.Text);
            var validation = new PersonBusiness();
            var validate = validation.ValidatePerson(person);

            if (validate.isValid)
            {
                var loadExistingData = await ApplicationUtilities.GetSavedUsers();
                var storageHelper = new StorageHelper<List<PersonModel>>(StorageType.Local);

                if (loadExistingData == null)
                {
                    var peopleList = new List<PersonModel> {person};
                    storageHelper.SaveASync(peopleList, "Settings");
                }
                else
                {
                    loadExistingData.Add(person);
                    storageHelper.SaveASync(loadExistingData, "Settings");
                }
                ErrorText.Text = "Saved...";
                ClearUserEntry();
            }
            else
            {
                ErrorText.Text = validate.errorMessage;                 
            }
                
        }
Esempio n. 4
0
 static StorageManager()
 {
     _leaderBoardStorageHelper = new StorageHelper<LeaderBoardStorageContainer>(StorageType.Local);
     _usersStorageHelper = new StorageHelper<UserStorageContainer>(StorageType.Local);
     _preferencesStorageHelper = new StorageHelper<GamePreferences>(StorageType.Local);
     
 }
        public void GetCollection_expect_correct_collection()
        {
            _storage.Stub(s => s.Get()).Return(FakeDocuments.SingleFakeObjectDocument);

            var agent = new StorageHelper<FakeObject>(_resolver, _storage);

            var result = agent.GetCollection();

            Assert.AreEqual(result.First(), FakeObject.Instance);
        }
        public void GetObject_expect_correct_object()
        {
            _storage.Stub(s => s.Get()).Return(FakeDocuments.SingleFakeObjectDocument);

            var agent = new StorageHelper<FakeObject>(_resolver, _storage);

            var result = agent.GetObject(FakeObject.InstanceIdentifier);

            Assert.AreEqual(result, FakeObject.Instance);
        }
        public void SaveObject_should_save_document()
        {
            _storage.Stub(s => s.Get()).Return(FakeDocuments.EmptyDocument);

            var agent = new StorageHelper<FakeObject>(_resolver, _storage);

            agent.SaveObject(FakeObject.Instance);

            _storage.AssertWasCalled(s => s.Save(Arg<XmlDocument>.Matches(d => d.InnerText.Equals(FakeDocuments.SingleFakeObjectDocument.InnerText))));
        }
        public async Task<List<GasQueryResult>> LoadResultsAsync()
        {
            var objectStorageHelper = new StorageHelper<List<GasQueryResult>>(StorageType.Local);
            List<GasQueryResult> ergebnisse = await objectStorageHelper.LoadAsync(StorageFileName);

            if (null == ergebnisse)
                ergebnisse = new List<GasQueryResult>();

            return ergebnisse;
        }
        public async Task<List<Favorite>> LoadAsync()
        {
            var objectStorageHelper = new StorageHelper<List<Favorite>>(StorageType.Local);
            List<Favorite> favorites = await objectStorageHelper.LoadAsync(StorageFileName);

            if (null == favorites)
                favorites = new List<Favorite>();

            return favorites;
        }
        public async Task StorageHelperDeleteNotExistingTest()
        {
            StorageHelper<MyModel> sh = new StorageHelper<MyModel>(StorageType.Local);

            //Delete non existing object
            await sh.DeleteAsync("myfile6526161651651");

            var loadedObject = await sh.LoadAsync("myfile6526161651651");
            Assert.IsNull(loadedObject);


        }
Esempio n. 11
0
        public async Task CreateAppLocalData()
        {
            var ObjectStorageHelper = new StorageHelper<LocalAppData>(StorageType.Local);
            LocalAppData LoadedData = await ObjectStorageHelper.LoadASync("AllAppData");

            //If file hasn't been created. Create it
            if (LoadedData == null)
            {
                //Never created this file, create it now
                LocalAppData NewAppDataStruct = new LocalAppData();
                await Task.Run(() => ObjectStorageHelper.SaveASync(NewAppDataStruct, "AllAppData"));
            }
        }
 public static async Task<List<PersonModel>> GetSavedUsers()
 {
     var peopleList = new List<PersonModel>();
     var storage = new StorageHelper<List<PersonModel>>(StorageType.Local);
     try
     {
         peopleList = await storage.LoadASync(@"Settings.xml");
     }
     catch (Exception)
     {
         peopleList = null;
     }
     return peopleList;
 }
Esempio n. 13
0
        async void ChatView_Loaded(object sender, RoutedEventArgs e)
        {
            if (m_bHaveInited)
            {
                return;
            }
            m_bHaveInited = true;


            StorageHelper<ObservableCollection<ChatItemViewModel>> stHelper =
               new StorageHelper<ObservableCollection<ChatItemViewModel>>(StorageType.Local);
            try
            {
                ObservableCollection<ChatItemViewModel> result = await stHelper.LoadASync("Global_ChatRecord");
                if (result != null)
                {
                    foreach (ChatItemViewModel model in result)
                    {
                        Items.Add(model);
                    }
                    var selectedIndex = MainList.Items.Count - 1;
                    if (selectedIndex >= 0)
                    {
                        MainList.SelectedIndex = selectedIndex;
                        MainList.UpdateLayout();
                        MainList.ScrollIntoView(MainList.SelectedItem);
                    }                    
                }
            }
            catch (System.Exception ex)
            {
                Items.Clear();
                ChatItemViewModel item1 = new ChatItemViewModel();
                item1.Icon = MiscTool.GetHerIconUrl();
                item1.Title = MiscTool.GetHerName();
                item1.Text = "^_^";
                item1.Type = "Her";
                Items.Add(item1);
            }

            if (Items.Count == 0)
            {
                ChatItemViewModel item1 = new ChatItemViewModel();
                item1.Icon = MiscTool.GetHerIconUrl();
                item1.Title = MiscTool.GetHerName();
                item1.Text = "^_^";
                item1.Type = "Her";
                Items.Add(item1);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Get index file
        /// </summary>
        /// <returns></returns>
        public async static Task<Dictionary<string, string>> GetIndexFile()
        {

            var folder = await GetFolderAsync().ConfigureAwait(false);

            IStorageHelper<Dictionary<string, string>> storage = new StorageHelper<Dictionary<string, string>>(_storageFolder, CacheFolder, StorageSerializer.JSON);

            //Get cache value
            var value = await storage.LoadAsync(IndexCacheFile).ConfigureAwait(false);

            if (value == null) { return default(Dictionary<string, string>); }
            else
                return value;

        }
 public static async Task<AppModel> GetAppSettings()
 {
     // ReSharper disable once RedundantAssignment
     var appModel = new AppModel();
     var storage = new StorageHelper<AppModel>(StorageType.Local);
     try
     {
         appModel = await storage.LoadASync(@"AppSetting.xml");
     }
     catch (Exception)
     {
         appModel = null;
     }
     return appModel;
 }
Esempio n. 16
0
    public async Task StorageHelperSaveTest(StorageSerializer serializerType)
    {
      var myObject = new MyModel() { Name = "Michiel", Age = 29 };

      IStorageHelper<MyModel> sh = new StorageHelper<MyModel>(StorageType.Local, serializerType: serializerType);

      await sh.SaveAsync(myObject, "myfile");

      var loadedObject = await sh.LoadAsync("myfile");

      Assert.AreEqual(myObject.Name, loadedObject.Name);
      Assert.AreEqual(myObject.Age, loadedObject.Age);

      await sh.DeleteAsync("myfile");

    }
        public async Task StorageHelperDeleteTest()
        {
            var myObject = new MyModel() { Name = "Michiel", Age = 29 };

            StorageHelper<MyModel> sh = new StorageHelper<MyModel>(StorageType.Local);

            await sh.SaveAsync(myObject, "myfile");

            //Delete saved object
            await sh.DeleteAsync("myfile");

            var loadedObject = await sh.LoadAsync("myfile");
            Assert.IsNull(loadedObject);


        }
Esempio n. 18
0
        private static async Task SaveIndexFile()
        {
            try
            {
                var folder = await GetFolderAsync().ConfigureAwait(false);

                IStorageHelper<Dictionary<string, string>> storage = new StorageHelper<Dictionary<string, string>>(_storageFolder, CacheFolder, StorageSerializer.JSON);

                await storage.SaveAsync(_files, IndexCacheFile);
            }
            catch (Exception)
            {

            }


        }
Esempio n. 19
0
    public async Task StorageHelperDifferentSerializerTest()
    {
        var myObject = new MyModel() { Name = "Michiel", Age = 29 };

        IStorageHelper<MyModel> sh = new StorageHelper<MyModel>(StorageType.Local);

        await sh.SaveAsync(myObject, "myfile");

        IStorageHelper<MyModel> shXml = new StorageHelper<MyModel>(StorageType.Local, serializerType:  StorageSerializer.XML);

        var loadedObject = await shXml.LoadAsync("myfile");

        Assert.IsNull(loadedObject);

        await sh.DeleteAsync("myfile");

    }
Esempio n. 20
0
        public MainPage()
        {
            InitializeComponent();
            PanoramaItem eventsPage = new PanoramaItem() { Name = "eventsPage", Header = "Upcoming" };
            PanoramaItem artistsPage = new PanoramaItem() { Name = "artistsPage", Header = "Artists" };
            PanoramaItem venuesPage = new PanoramaItem() { Name = "venuesPage", Header = "Venues" };
            mainView.Items.Add(eventsPage);
            mainView.Items.Add(artistsPage);
            mainView.Items.Add(venuesPage);

            AdControl concertsAd = new AdControl() { ApplicationId = "33c7fa47-c859-47f1-8903-f745bf749ce0", AdUnitId = "10016302", Width = 300, Height = 50, Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.White), Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Black) };
            LayoutRoot.Children.Add(concertsAd);
            Grid.SetRow(concertsAd, 1);

            ApplicationBar = new ApplicationBar();
            ApplicationBar.IsMenuEnabled = true;
            ApplicationBar.IsVisible = true;
            ApplicationBar.Opacity = 1.0;

            events = new List<Event>();
            artists = new List<Artist>();
            venues = new List<Venue>();

            eventsStorageHelper = new StorageHelper<Event>("Events.xml", "Stale.txt");
            artistsStorageHelper = new StorageHelper<Artist>("Artists.xml");
            venuesStorageHelper = new StorageHelper<Venue>("Venues.xml");

            ApplicationBarIconButton refresh = new ApplicationBarIconButton(new Uri("/Icons/appbar.refresh.rest.png", UriKind.Relative));
            refresh.Text = "refresh";
            refresh.Click += new EventHandler(refresh_Click);

            ApplicationBarIconButton settings = new ApplicationBarIconButton(new Uri("/Icons/appbar.feature.settings.rest.png", UriKind.Relative));
            settings.Text = "settings";
            settings.Click += new EventHandler(settings_Click);

            ApplicationBar.Buttons.Add(refresh);
            ApplicationBar.Buttons.Add(settings);

            ApplicationBar.BackgroundColor = System.Windows.Media.Colors.Black;
            ApplicationBar.ForegroundColor = System.Windows.Media.Colors.White;

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }
        public async Task StorageHelperSaveOverwriteTest()
        {
            var myObject = new MyModel() { Name = "Michiel", Age = 29 };

            StorageHelper<MyModel> sh = new StorageHelper<MyModel>(StorageType.Local);

            await sh.SaveAsync(myObject, "myfile");

            var newObject = new MyModel() { Name = "Simon", Age = 0 };

            //Save new object
            await sh.SaveAsync(newObject, "myfile");
            var loadedObject = await sh.LoadAsync("myfile");

            Assert.AreEqual(newObject.Name, loadedObject.Name);
            Assert.AreEqual(newObject.Age, loadedObject.Age);

            await sh.DeleteAsync("myfile");

        }
Esempio n. 22
0
    public async Task StorageHelperSaveOverwriteTest(StorageSerializer serializerType)
    {
      var myObject = new MyModel() { Name = "Michiel", Age = 29 };

      IStorageHelper<MyModel> sh = new StorageHelper<MyModel>(Windows.Storage.ApplicationData.Current.LocalFolder, serializerType: serializerType);

      await sh.SaveAsync(myObject, "myfile");

      var newObject = new MyModel() { Name = "Simon", Age = 0 };

      //Save new object
      await sh.SaveAsync(newObject, "myfile");
      var loadedObject = await sh.LoadAsync("myfile");

      Assert.AreEqual(newObject.Name, loadedObject.Name);
      Assert.AreEqual(newObject.Age, loadedObject.Age);

      await sh.DeleteAsync("myfile");

    }
        public async Task <IActionResult> Upload(ICollection <IFormFile> files)
        {
            bool isUploaded = false;

            try
            {
                if (files.Count == 0)
                {
                    return(BadRequest("No files received from the upload"));
                }

                if (storageConfig.AccountKey == string.Empty || storageConfig.AccountName == string.Empty)
                {
                    return(BadRequest("sorry, can't retrieve your azure storage details from appsettings.js, make sure that you add azure storage details there"));
                }

                if (storageConfig.ImageContainer == string.Empty)
                {
                    return(BadRequest("Please provide a name for your image container in the azure blob storage"));
                }

                foreach (var formFile in files)
                {
                    if (StorageHelper.IsImage(formFile))
                    {
                        if (formFile.Length > 0)
                        {
                            using (Stream stream = formFile.OpenReadStream())
                            {
                                isUploaded = await StorageHelper.UploadFileToStorage(stream, formFile.FileName, storageConfig);
                            }
                        }
                    }
                    else
                    {
                        return(new UnsupportedMediaTypeResult());
                    }
                }

                if (isUploaded)
                {
                    if (storageConfig.ThumbnailContainer != string.Empty)
                    {
                        return(new AcceptedAtActionResult("GetThumbNails", "Images", null, null));
                    }

                    else
                    {
                        return(new AcceptedResult());
                    }
                }
                else
                {
                    return(BadRequest("Look like the image couldnt upload to the storage"));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
 public async Task<bool> SaveResultsAsync(List<GasQueryResult> ergebnisse)
 {
     var objectStorageHelper = new StorageHelper<List<GasQueryResult>>(StorageType.Local);
     bool result = await objectStorageHelper.SaveAsync(ergebnisse, StorageFileName);
     return result;
 }
 // Static Helpers for Testing ONLY
 public static async Task ResetStorageAsync()
 {
     var objectStorageHelper = new StorageHelper<List<GasQueryResult>>(StorageType.Local);
     objectStorageHelper.DeleteAsync(StorageFileName);
 }
Esempio n. 26
0
        /// <summary>
        ///     Updates the id3 tags. WARNING, there needs to be more testing with lower end devices.
        /// </summary>
        /// <param name="song">The song.</param>
        /// <param name="file">The file.</param>
        private async Task <bool> UpdateId3TagsAsync(Song song, IStorageFile file)
        {
            using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false))
            {
                TagLib.File tagFile;

                try
                {
                    tagFile = TagLib.File.Create(new SimpleFileAbstraction(file.Name, fileStream, fileStream));
                }
                catch (CorruptFileException)
                {
                    await CollectionHelper.DeleteEntryAsync(song);

                    await file.DeleteAsync();

                    return(false);
                }

                catch
                {
                    return(false);
                }

                var newTags = tagFile.GetTag(TagTypes.Id3v2, true);

                newTags.Title = song.Name;

                if (song.Artist.ProviderId != "autc.unknown")
                {
                    newTags.Performers = song.ArtistName.Split(',').Select(p => p.Trim()).ToArray();
                }

                newTags.Album        = song.Album.Name;
                newTags.AlbumArtists = new[] { song.Album.PrimaryArtist.Name };

                if (!string.IsNullOrEmpty(song.Album.Genre))
                {
                    newTags.Genres = song.Album.Genre.Split(',').Select(p => p.Trim()).ToArray();
                }

                newTags.Track              = (uint)song.TrackNumber;
                newTags.MusicIpId          = song.RadioId.ToString();
                newTags.MusicBrainzTrackId = song.CloudId;
                newTags.Comment            = "Downloaded by airstem for Windows 10.";

                try
                {
                    if (song.Album.HasArtwork)
                    {
                        var albumFilePath = string.Format(AppConstant.ArtworkPath, song.Album.Id);
                        var artworkFile   = await StorageHelper.GetFileAsync(albumFilePath).ConfigureAwait(false);

                        using (var artworkStream = await artworkFile.OpenAsync(PCLStorage.FileAccess.Read))
                        {
                            using (var memStream = new MemoryStream())
                            {
                                await artworkStream.CopyToAsync(memStream);

                                newTags.Pictures = new IPicture[]
                                {
                                    new Picture(
                                        new ByteVector(
                                            memStream.ToArray(),
                                            (int)memStream.Length))
                                };
                            }
                        }
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    ToastManager.ShowError("UnauthorizedAccess Exception.");
                    // Should never happen, since we are opening the files in read mode and nothing is locking it.
                }

                await Task.Run(() => tagFile.Save());

                return(true);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Gets the List of Stores available  on the server within the current catalog asynchronously
        /// </summary>
        /// <param name="callback">Callback</param>
        /// <param name="state">State to pass to callback</param>
        public override void ListStores(AsyncStorageCallback callback, object state)
        {
            try
            {
                HttpWebRequest request = this.CreateRequest("repositories", "application/json", "GET", new Dictionary <string, string>());
                request.BeginGetResponse(r =>
                {
                    try
                    {
                        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r);
                        String data;
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            data = reader.ReadToEnd();
                            reader.Close();
                        }

                        JArray json          = JArray.Parse(data);
                        List <String> stores = new List <string>();
                        foreach (JToken token in json.Children())
                        {
                            JValue id = token["id"] as JValue;
                            if (id != null)
                            {
                                stores.Add(id.Value.ToString());
                            }
                        }
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListStores, stores), state);
                    }
                    catch (WebException webEx)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListStores, StorageHelper.HandleHttpError(webEx, "list Stores from")), state);
                    }
                    catch (Exception ex)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListStores, StorageHelper.HandleError(ex, "list Stores from")), state);
                    }
                }, state);
            }
            catch (WebException webEx)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListStores, StorageHelper.HandleHttpError(webEx, "list Stores from")), state);
            }
            catch (Exception ex)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListStores, StorageHelper.HandleError(ex, "list Stores from")), state);
            }
        }
Esempio n. 28
0
 public void ConstructBuilding(Building buildingPrefab)
 {
     StorageHelper.RemoveAll(ResourceManager.GetInstance, buildingPrefab.Stats.ConstructionCost);
     building = Instantiate(buildingPrefab, buildingPlacement, false);
 }
Esempio n. 29
0
 /// <summary>
 /// 将实例保存到JSON文件中。
 /// </summary>
 public Task SaveAsync() => StorageHelper.SaveTextAsync(_json, this.ToJsonString());
Esempio n. 30
0
    /// <summary>
    /// Handles actions related to the folders.
    /// </summary>
    /// <param name="argument">Argument related to the folder action</param>
    /// <param name="forceReload">Indicates if load should be forced</param>
    private void HandleFolderAction(string argument, bool forceReload)
    {
        SelectedNodePath = ValidationHelper.GetString(argument, string.Empty);

        // Reload content tree if necessary
        if (forceReload)
        {
            InitializeFileSystemTree();

            // Fill with new info
            treeFileSystem.DefaultPath       = SelectedNodePath;
            treeFileSystem.ExpandDefaultPath = true;

            treeFileSystem.ReloadData();
            pnlUpdateTree.Update();

            ScriptManager.RegisterStartupScript(Page, typeof(Page), "EnsureTopWindow", "if (self.focus) { self.focus(); }", true);
        }

        ColorizeLastSelectedRow();

        // Get parent node ID info
        string parentPath = string.Empty;

        if (!string.Equals(FullStartingPath, SelectedNodePath, StringComparison.InvariantCultureIgnoreCase))
        {
            try
            {
                parentPath = DirectoryInfo.New(SelectedNodePath).Parent.FullName;
            }
            // Access denied to parent
            catch (SecurityException)
            {
            }
        }

        menuElem.ShowParentButton = !String.IsNullOrEmpty(parentPath);
        menuElem.NodeParentPath   = parentPath;

        fileSystemView.Config = Config;

        // Load new data
        if ((Config.ShowFolders) && (SelectedNodePath.LastIndexOf("\\", StringComparison.Ordinal) != -1))
        {
            fileSystemView.StartingPath = SelectedNodePath.Substring(0, argument.LastIndexOf("\\", StringComparison.Ordinal) + 1);
        }

        fileSystemView.StartingPath = SelectedNodePath;

        // Set the editing possibilities
        var canEdit = !StorageHelper.IsZippedFilePath(fileSystemView.StartingPath);

        if (!canEdit)
        {
            fileSystemView.AllowEdit = false;
        }

        menuElem.AllowNew = canEdit;

        // Reload view control's content
        fileSystemView.Reload();
        pnlUpdateView.Update();

        InitializeMenuElem();
        menuElem.UpdateActionsMenu();
        folderActions.Update();
        pnlUpdateMenu.Update();

        ClearActionElems();
    }
Esempio n. 31
0
        public TorrentStartItem(TorrentProvider torrentProvider, Magnet magnet, Torrent torrent = null)
        {
            Progress         = float.PositiveInfinity;
            _torrentProvider = torrentProvider;
            Magnet           = magnet;
            var ml = new MagnetLink(magnet.ToString());

            // find or create torrent
            _manager = _torrentProvider.Torrents.FirstOrDefault(t => t.InfoHash == ml.InfoHash);
            if (_manager == null)
            {
                if (torrent != null)
                {
                    var cacheFolder = torrentProvider.Client.ReserveCacheSpace(magnet.Size);

                    if (cacheFolder == null)
                    {
                        MessageBox.Show("Недостаточно свободного места на диске.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Closed = true;
                        return;
                    }

                    _manager = new TorrentManager(torrent, cacheFolder, _torrentProvider.TorrentDefaults);

                    foreach (var torrentFile in _manager.Torrent.Files)
                    {
                        torrentFile.Priority = Priority.DoNotDownload;
                    }
                }
                else
                {
                    _manager = new TorrentManager(ml, StorageHelper.GetBestSaveDirectory(), _torrentProvider.TorrentDefaults, _torrentProvider.TorrentsFolder);
                }

                _torrentProvider.RegisterTorrent(_manager);
                _manager.Start();
            }
            else
            {
                if (!string.IsNullOrEmpty(magnet.FileName))
                {
                    _file = _manager.Torrent.Files.FirstOrDefault(f => f.Path == magnet.FileName);

                    // check if the file is downloaded completely
                    if (_file != null && _file.BitField.TrueCount == _file.BitField.Length)
                    {
                        Closed = true;
                        ShellHelper.Start(_file.FullPath);
                        return;
                    }
                }

                if (_manager.State == TorrentState.Stopped)
                {
                    _manager.Start();
                }
            }

            var switcher = _manager.PieceManager.GetPicker <EndGameSwitcher>();

            switcher.Reset();

#if DEBUG
            if (_torrentProvider.FrmDebug != null)
            {
                _torrentProvider.FrmDebug.SegementsControl.Manager = _manager;
            }
#endif

            new ThreadStart(FormThread).BeginInvoke(null, null);
        }
Esempio n. 32
0
        private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            this.gdRoot.Width = this.gdRoot.ActualWidth;
            var def = args.GetDeferral();

            this.PrimaryButtonText   = "";
            this.SecondaryButtonText = "";
            this.CloseButtonText     = "";
            FindName(nameof(this.rpDownload));

            var folder = await DownloadsFolder.CreateFolderAsync(StorageHelper.ToValidFileName(this.release.tag_name), CreationCollisionOption.GenerateUniqueName);

            try
            {
                var arch = Package.Current.Id.Architecture.ToString();
                if (this.release.assets.IsNullOrEmpty())
                {
                    throw new InvalidOperationException("Find appx file failed.");
                }

                var assets = (from asset in this.release.assets
                              where asset.name.IndexOf(arch, StringComparison.OrdinalIgnoreCase) > 0 && downloadExt.Any(e => asset.name.EndsWith(e))
                              select asset).ToList();

                if (assets.IsEmpty())
                {
                    throw new InvalidOperationException("Find appx file failed.");
                }
                var files        = new List <StorageFile>();
                var fileLaunched = false;
                using (var client = new HttpClient())
                {
                    try
                    {
                        this.totalDownloaded = assets.Sum(a => (long)a.size);
                        foreach (var item in assets)
                        {
                            var op = client.GetBufferAsync(new Uri(item.browser_download_url));
                            ReportProgress(op, default);
                            op.Progress = ReportProgress;
                            var buf  = await op;
                            var file = await folder.CreateFileAsync(item.name, CreationCollisionOption.ReplaceExisting);

                            await FileIO.WriteBufferAsync(file, buf);

                            this.currentDownloaded += item.size;
                            files.Add(file);
                        }
                        foreach (var item in files)
                        {
                            fileLaunched = fileLaunched || await Launcher.LaunchFileAsync(item);
                        }
                    }
                    finally
                    {
                        if ((assets.Count > 1 || !fileLaunched) && !await Launcher.LaunchFolderAsync(folder))
                        {
                            throw new InvalidOperationException("Launch download folder failed.");
                        }
                    }
                }
            }
            catch
            {
                await Launcher.LaunchUriAsync(new Uri(this.release.html_url));
            }
            finally
            {
                def.Complete();
                Application.Current.Exit();
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Gets classID from querystring
        documentTypeId = QueryHelper.GetInteger("documenttypeid", 0);

        // Initializes labels
        lblFullCodeName.Text          = GetString("DocumentType_Edit_General.FullCodeName");
        lblCodeName.Text              = GetString("DocumentType_Edit_General.CodeName");
        lblNamespaceName.Text         = GetString("DocumentType_Edit_General.Namespace");
        lblDisplayName.Text           = GetString("DocumentType_Edit_General.DisplayName");
        lblEditingPage.Text           = GetString("DocumentType_Edit_General.EditingPage");
        lblNewPage.Text               = GetString("DocumentType_Edit_General.NewPage");
        lblListPage.Text              = GetString("DocumentType_Edit_General.ListPage");
        lblTemplateSelection.Text     = GetString("DocumentType_Edit_General.TemplateSelection");
        lblRootTemplate.Text          = GetString("DocumentType_Edit_General.TemplateCategorySelection");
        lblViewPage.Text              = GetString("DocumentType_Edit_General.ViewPage");
        lblPreviewPage.Text           = GetString("DocumentType_Edit_General.PreviewPage");
        lblClassUsePublishFromTo.Text = GetString("DocumentType_Edit_General.UsePublishFromTo");
        lblIsMenuItem.Text            = GetString("DocumentType_Edit_General.IsMenuItem");
        lblDefaultTemplate.Text       = GetString("DocumentType_Edit_General.DefaultTemplate");
        lblTableName.Text             = GetString("class.TableName");

        // Initializes validators
        RequiredFieldValidatorDisplayName.ErrorMessage       = GetString("DocumentType_Edit_General.DisplayNameRequired");
        RequiredFieldValidatorNamespaceName.ErrorMessage     = GetString("DocumentType_Edit_General.NamespaceNameRequired");
        RequiredFieldValidatorCodeName.ErrorMessage          = GetString("DocumentType_Edit_General.CodeNameRequired");
        RegularExpressionValidatorNameSpaceName.ErrorMessage = GetString("DocumentType_Edit_General.NamespaceNameIdentifier");
        RegularExpressionValidatorCodeName.ErrorMessage      = GetString("DocumentType_Edit_General.CodeNameIdentifier");

        lblLoadGeneration.Text    = GetString("LoadGeneration.Title");
        plcLoadGeneration.Visible = SettingsKeyProvider.DevelopmentMode;

        btnOk.Text = GetString("general.ok");

        if (documentTypeId > 0)
        {
            classInfo    = DataClassInfoProvider.GetDataClass(documentTypeId);
            EditedObject = classInfo;

            if (classInfo != null)
            {
                plcFields.Visible = classInfo.ClassIsCoupledClass;

                selInherits.WhereCondition = "ClassIsCoupledClass = 1 AND ClassID <> " + documentTypeId + " AND (ClassInheritsFromClassID IS NULL OR ClassInheritsFromClassID <> " + documentTypeId + ")";

                className = classInfo.ClassName;

                // Setup the icons
                dfuSmall.TargetFileName = className.Replace('.', '_').ToLowerCSafe();
                dfuLarge.TargetFileName = className.Replace('.', '_').ToLowerCSafe();

                if (SettingsKeyProvider.DevelopmentMode)
                {
                    // Only 'gif' images in development mode
                    dfuSmall.AllowedExtensions = "gif;png";
                    dfuLarge.AllowedExtensions = "gif;png";
                }

                // Hide direct file uploader for external storage
                if (StorageHelper.IsExternalStorage("~/App_Themes/Default/Images/DocumentTypeIcons"))
                {
                    dfuLarge.Visible = false;
                    dfuSmall.Visible = false;
                }

                // Sets regular expression for identifier validation
                RegularExpressionValidatorNameSpaceName.ValidationExpression = ValidationHelper.IdentifierRegExp.ToString();
                RegularExpressionValidatorCodeName.ValidationExpression      = ValidationHelper.IdentifierRegExp.ToString();

                if (!RequestHelper.IsPostBack())
                {
                    // Loads data to the form
                    LoadData();
                }
            }
        }

        templateDefault.RootCategoryID = categorySelector.SelectedCategoryID;
    }
Esempio n. 34
0
        public async void Login()
        {
            IsDataLoaded       = false;
            LoginButtonEnabled = false;
            if (!IsInputsValid())
            {
                IsTaskbarVisible = false;
                IsDataLoaded     = true;
                dialogService.ShowDialog(AppResources.UnauthorizedMessage, AppResources.LoginFailedMessage);
                IsTaskbarVisible   = true;
                LoginButtonEnabled = true;
                return;
            }

            if (!ValidateUrl(ServerUrl))
            {
                IsDataLoaded     = true;
                IsTaskbarVisible = false;
                dialogService.ShowDialog(AppResources.InvalidServerUrlMessage, AppResources.LoginFailedMessage);
                IsTaskbarVisible   = true;
                LoginButtonEnabled = true;
                return;
            }
            try
            {
                //Create new cancellation token source
                cancellationTokenSource = new CancellationTokenSource();

                //Set base url for rest api
                App.BaseUrl = string.Format("{0}/rest/api/latest/", App.ServerUrl);
                var isLoginSuccess = await jiraService.LoginAsync(ServerUrl, UserName, Password, cancellationTokenSource);

                if (isLoginSuccess)
                {
                    App.IsLoggedIn = true;
                    StorageHelper.SaveUserCredential(ServerUrl, UserName, Password);
                    navigationService.Navigate <ProjectListViewModel>();
                }
            }
            catch (HttpRequestStatusCodeException exception)
            {
                IsTaskbarVisible = false;
                if (exception.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    dialogService.ShowDialog(AppResources.UnauthorizedMessage, AppResources.LoginFailedMessage);
                }
                else if (exception.StatusCode == System.Net.HttpStatusCode.Forbidden)
                {
                    dialogService.ShowDialog(AppResources.ForbiddenMessage, AppResources.LoginFailedMessage);
                }
                else
                {
                    dialogService.ShowDialog(AppResources.ConnectionErrorMessage, AppResources.LoginFailedMessage);
                }
                IsTaskbarVisible = true;
            }
            catch (Exception ex)
            {
                IsTaskbarVisible = false;
                dialogService.ShowDialog(string.Format(AppResources.FormattedErrorMessage, ex.Message), AppResources.LoginFailedMessage);
                IsTaskbarVisible = true;
            }

            IsDataLoaded       = true;
            LoginButtonEnabled = true;
        }
Esempio n. 35
0
        public static async Task Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req,
            // Establecemos el hub de conexión
            [SignalR(HubName = "chat")] IAsyncCollector <SignalRMessage> signalRMessages,
            ILogger log)
        {
            // Se obtiene el contenido del Request Body
            var serializeObject = new JsonSerializer().Deserialize(new JsonTextReader(new StreamReader(req.Body)));

            // Se deserializa el mensaje obtenido del body
            var message = JsonConvert.DeserializeObject <ChatMessage>(serializeObject.ToString());

            // Verificamos que tipo de mensaje es acorde a la clase y asi poder procesarlo
            if (message.TypeInfo.Name == nameof(UserConnectedMessage))
            {
                // Se deserializa el tipo obtenido
                message = JsonConvert.DeserializeObject <UserConnectedMessage>(serializeObject.ToString());

                // Se agrega la funcion de signalR
                await signalRMessages.AddAsync(new SignalRMessage
                {
                    GroupName = message.GroupName,
                    Target    = "ReceiveMessage",
                    Arguments = new[] { message }
                });
            }
            else if (message.TypeInfo.Name == nameof(SimpleTextMessage))
            {
                // Se deserializa el tipo obtenido
                message = JsonConvert.DeserializeObject <SimpleTextMessage>(serializeObject.ToString());

                var signalRMessage = new SignalRMessage
                {
                    // Nombre del metodo que agregara el mensaje al chat
                    Target = "ReceiveMessage",
                    // Es el mensaje a enviar por Signal R
                    Arguments = new[] { message }
                };
                // Unicamente se pueden configurar estas propiedades una a la vez
                if (message.GroupName != null)
                {
                    signalRMessage.GroupName = message.GroupName;
                }
                else if (message.Recipient != null)
                {
                    signalRMessage.UserId = message.Recipient;
                }

                // Se agrega a la función a signalR
                await signalRMessages.AddAsync(signalRMessage);
            }
            else if (message.TypeInfo.Name == nameof(PhotoMessage))
            {
                // Se deserializa el tipo obtenido
                var photoMessage = JsonConvert.DeserializeObject <PhotoMessage>(serializeObject.ToString());

                // se convierte a bytes la propiedad de Photo
                var bytes = Convert.FromBase64String(photoMessage.Base64Photo);

                var url = await StorageHelper.Upload(bytes, photoMessage.FileEnding);

                // Se establecen las propiedades del mesaje
                message = new PhotoUrlMessage(photoMessage.Sender)
                {
                    Id        = photoMessage.Id,
                    Timestamp = photoMessage.Timestamp,
                    Url       = url,
                    GroupName = photoMessage.GroupName
                };

                // Se agrega a la función de signalR
                await signalRMessages.AddAsync(new SignalRMessage {
                    GroupName = message.GroupName,
                    Target    = "ReceiveMessage",
                    Arguments = new[] { message }
                });
            }
        }
Esempio n. 36
0
    public async Task StorageHelperNotExistingTest(StorageSerializer serializerType)
    {
        IStorageHelper<MyModel> sh = new StorageHelper<MyModel>(Windows.Storage.ApplicationData.Current.LocalFolder, serializerType: serializerType);

      var loadedObject = await sh.LoadAsync("myfile561616516");

      Assert.IsNull(loadedObject);

    }
Esempio n. 37
0
    public async Task StorageHelperDeleteTest(StorageSerializer serializerType)
    {
      var myObject = new MyModel() { Name = "Michiel", Age = 29 };

      IStorageHelper<MyModel> sh = new StorageHelper<MyModel>(Windows.Storage.ApplicationData.Current.LocalFolder, serializerType: serializerType);

      await sh.SaveAsync(myObject, "myfile");

      //Delete saved object
      await sh.DeleteAsync("myfile");

      var loadedObject = await sh.LoadAsync("myfile");
      Assert.IsNull(loadedObject);


    }
        private void cmbStorage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            lblError.Content = null;
            if (dbIf != null)
            {
                dbIf.Dispose();
            }
            dbIf   = null;
            dbView = null;

            lblDataCount.Content         = null;
            grdDatasetFields.ItemsSource = null;

            datasetConfig = cmbStorage.SelectedItem as DatasetConfig;
            dbIf          = StorageHelper.GetStorage(ProtokollerConfiguration.ActualConfigInstance, datasetConfig.Storage, null);
            dbIf.Connect_To_Database(datasetConfig.Storage);
            dbView    = dbIf as IDBViewable;
            dbViewSQL = dbIf as IDBViewableSQL;

            txtSQL.IsEnabled    = false;
            cmdSQL.IsEnabled    = false;
            txtSearch.IsEnabled = false;
            cmdSearch.IsEnabled = false;

            try
            {
                if (dbView != null)
                {
                    txtSQL.Text   = "";
                    CurrentNumber = 0;
                    DataTable tbl = dbView.ReadData(datasetConfig, null, CurrentNumber, 1000, null, null);
                    if (tbl != null)
                    {
                        grdDatasetFields.ItemsSource = tbl.DefaultView;
                    }
                    lblDataCount.Content = dbView.ReadCount(datasetConfig);
                }

                if (!string.IsNullOrEmpty(datasetConfig.DateTimeDatabaseField))
                {
                    /*dbFieldNames = datasetConfig.DateTimeDatabaseField;
                     * foreach (var datasetConfigRow in datasetConfig.DatasetConfigRows)
                     * {
                     *  if (datasetConfigRow.DatabaseField.ToLower().Trim() != datasetConfig.DateTimeDatabaseField.ToLower().Trim())
                     *      dbFieldNames += ", " + datasetConfigRow.DatabaseField;
                     * }*/
                    dbFieldNames = datasetConfig.DateTimeDatabaseField + ",*";
                }

                if (dbViewSQL != null)
                {
                    string table;
                    if (datasetConfig.DatasetTableName != "")
                    {
                        table = datasetConfig.DatasetTableName;
                    }
                    else
                    {
                        table = datasetConfig.Name;
                    }

                    txtSQL.Text         = "SELECT " + dbFieldNames + " FROM " + table + " ORDER BY id DESC LIMIT " + 1000.ToString();
                    txtSQL.IsEnabled    = true;
                    cmdSQL.IsEnabled    = true;
                    txtSearch.IsEnabled = true;
                    cmdSearch.IsEnabled = true;
                }
            }
            catch (Exception ex)
            {
                lblError.Content = ex.Message;
            }
        }
Esempio n. 39
0
        public async Task DownFileAsync()
        {
            var folder = await StorageHelper.OpenFolderAsync();

            if (folder == null)
            {
                return;
            }
            //开启一个异步线程
            await Task.Run(async() =>
            {
                //异步操作UI元素
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    Status = FileStatus.Doning;
                });
                using (var http = new HttpClient())
                {
                    var _httpProgressDownload = new Progress <HttpProgress>(_progressDownloadHandler);
                    var response = await http.GetAsync(Url, HttpCompletionOption.ResponseHeadersRead).AsTask(_cts.Token, _httpProgressDownload);//发送请求
                    if (response.StatusCode != Windows.Web.Http.HttpStatusCode.Ok)
                    {
                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            Status = FileStatus.Failure;
                        });
                        Toast.ShowInfo("网址有误...");
                        return;
                    }
                    var httpFileName = response.Content.Headers.ContentDisposition.FileName;
                    if (!string.IsNullOrWhiteSpace(httpFileName))
                    {
                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            Name = httpFileName;
                        });
                    }
                    else if (string.IsNullOrWhiteSpace(Name))
                    {
                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            Name = "新下载文件.txt";
                        });
                    }

                    _length = response.Content.Headers.ContentLength;   //文件大小
                    Toast.ShowInfo(Name + " 正在下载...");
                    var file = await folder.CreateFileAsync(Name, CreationCollisionOption.ReplaceExisting);

                    var streamResponse = response.Content.ReadAsInputStreamAsync();
                    _cts.Token.ThrowIfCancellationRequested();
                    using (var stream = await streamResponse)
                    {
                        using (var inputStream = stream.AsStreamForRead())
                            using (var fileStream = await file.OpenStreamForWriteAsync())
                            {
                                await inputStream.CopyToAsync(fileStream);
                                Toast.ShowInfo(Name + " 下载完成!");
                                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                                {
                                    Status = FileStatus.Success;
                                });
                            }
                    }
                }
            });
        }
        public static async Task Run(
            [BlobTrigger("images/{name}.{extension}")] CloudBlockBlob blobImage, string name, string extension, TraceWriter log)
        {
            var tc = new TelemetryClient();

            tc.InstrumentationKey = Settings.APPINSIGHTS_INSTRUMENTATIONKEY;

            Person p = new Person();
            string notificationMessage = "Error";
            bool   hasError            = true;;
            string json       = string.Empty;
            string deviceId   = string.Empty;
            var    collection = await client_document.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Settings.DatabaseId), new DocumentCollection { Id = Settings.PersonCollectionId }, new RequestOptions { OfferThroughput = 1000 });

            //get json file from storage
            CloudBlockBlob blobJson = await StorageHelper.GetBlockBlob($"{name}.json", Settings.AzureWebJobsStorage, "metadata", false);

            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    blobJson.DownloadToStream(memoryStream);
                    json = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
                    p    = JsonConvert.DeserializeObject <Person>(json);
                }

                deviceId = p.ReportedByDeviceId;
                await NotificationsHelper.AddToRequest(deviceId, name);

                //validate record has not been processed before
                var query = client_document.CreateDocumentQuery <Person>(collection.Resource.SelfLink, new SqlQuerySpec()
                {
                    QueryText = $"SELECT * FROM Person p WHERE p.picture = '{name}.{extension}'"
                });
                int count = query.ToList().Count;
                if (count > 0)
                {
                    return;
                }
                log.Info(blobImage.Uri.AbsoluteUri);
                //determine if image has a face
                List <JObject> list = await client_face.DetectFaces(blobImage.Uri.AbsoluteUri);

                //validate image extension
                if (blobImage.Properties.ContentType != "image/jpeg")
                {
                    log.Info($"no valid content type for: {name}.{extension}");
                    await blobImage.DeleteAsync();

                    await blobJson.DeleteAsync();

                    notificationMessage = "Formato de fotografía incorrecto";
                    hasError            = true;
                    await NotificationsHelper.SendNotification(hasError, notificationMessage, name, deviceId);

                    return;
                }

                //if image has no faces
                if (list.Count == 0)
                {
                    log.Info($"there are no faces in the image: {name}.{extension}");
                    await blobImage.DeleteAsync();

                    await blobJson.DeleteAsync();

                    notificationMessage = $"La fotografía de {p.Name} {p.Lastname} no contiene rostros";
                    hasError            = true;
                    await NotificationsHelper.SendNotification(hasError, notificationMessage, name, deviceId);

                    return;
                }

                //if image has more than one face
                if (list.Count > 1)
                {
                    log.Info($"multiple faces detected in the image: {name}.{extension}");
                    await blobImage.DeleteAsync();

                    await blobJson.DeleteAsync();

                    notificationMessage = $"La fotografía de {p.Name} {p.Lastname} contiene mas de un rostro";
                    hasError            = true;
                    await NotificationsHelper.SendNotification(hasError, notificationMessage, name, deviceId);

                    return;
                }



                //register person in Face API
                CreatePerson resultCreatePerson = await client_face.AddPersonToGroup(p.Name + " " + p.Lastname);

                AddPersonFace resultPersonFace = await client_face.AddPersonFace(blobImage.Uri.AbsoluteUri, resultCreatePerson.personId);

                AddFaceToList resultFaceToList = await client_face.AddFaceToList(blobImage.Uri.AbsoluteUri);

                //Add custom settings
                p.IsActive        = 1;
                p.IsFound         = 0;
                p.FaceAPIFaceId   = resultFaceToList.persistedFaceId;
                p.FaceAPIPersonId = resultCreatePerson.personId;
                p.Picture         = $"{name}.jpg";

                await client_document.CreateDatabaseIfNotExistsAsync(new Database { Id = Settings.DatabaseId });

                var result = await client_document.CreateDocumentAsync(collection.Resource.SelfLink, p);

                var document = result.Resource;
            }
            catch (Exception ex)
            {
                tc.TrackException(ex);
                await blobImage.DeleteAsync();

                await blobJson.DeleteAsync();

                log.Info($"Error in file: {name}.{extension} - {ex.Message} {ex.StackTrace}");
                notificationMessage = $"Ocurrió un error durante el registro de {p.Name} {p.Lastname}";
                hasError            = true;
                await NotificationsHelper.SendNotification(hasError, notificationMessage, name, deviceId);

                return;
            }

            await blobJson.DeleteAsync();

            log.Info("person registered successfully");
            notificationMessage = $"El registro de {p.Name} {p.Lastname} se realizo correctamente";
            hasError            = false;
            await NotificationsHelper.SendNotification(hasError, notificationMessage, name, deviceId);
        }
Esempio n. 41
0
        /// <summary>
        /// Deletes a Store from the server within the current catalog asynchronously
        /// </summary>
        /// <param name="storeID">Store ID</param>
        /// <param name="callback">Callback</param>
        /// <param name="state">State to pass to callback</param>
        public override void DeleteStore(string storeID, AsyncStorageCallback callback, object state)
        {
            try
            {
                HttpWebRequest request = this.CreateRequest("repositories/" + storeID, "*/*", "DELETE", new Dictionary <string, string>());

                Tools.HttpDebugRequest(request);

                request.BeginGetResponse(r =>
                {
                    try
                    {
                        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r);
                        Tools.HttpDebugResponse(response);

                        //If we get here then the operation completed OK
                        response.Close();
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteStore, storeID), state);
                    }
                    catch (WebException webEx)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteStore, storeID, StorageHelper.HandleHttpError(webEx, "delete the Store '" + storeID + "; from")), state);
                    }
                    catch (Exception ex)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteStore, storeID, StorageHelper.HandleError(ex, "delete the Store '" + storeID + "' from")), state);
                    }
                }, state);
            }
            catch (WebException webEx)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteStore, storeID, StorageHelper.HandleHttpError(webEx, "delete the Store '" + storeID + "; from")), state);
            }
            catch (Exception ex)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteStore, storeID, StorageHelper.HandleError(ex, "delete the Store '" + storeID + "' from")), state);
            }
        }
Esempio n. 42
0
        /// <summary>
        /// Creates a new store based on the given template
        /// </summary>
        /// <param name="template">Template</param>
        /// <param name="callback">Callback</param>
        /// <param name="state">State to pass to the callback</param>
        /// <remarks>
        /// <para>
        /// Template must inherit from <see cref="BaseSesameTemplate"/>
        /// </para>
        /// </remarks>
        public virtual void CreateStore(IStoreTemplate template, AsyncStorageCallback callback, object state)
        {
            if (template is BaseSesameTemplate)
            {
                //First we need to store the template as a new context in the SYSTEM repository
                Dictionary <String, String> createParams   = new Dictionary <string, string>();
                BaseSesameTemplate          sesameTemplate = (BaseSesameTemplate)template;

                if (template.Validate().Any())
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, new RdfStorageException("Template is not valid, call Validate() on the template to see the list of errors")), state);
                    return;
                }

                IGraph g = sesameTemplate.GetTemplateGraph();
                createParams.Add("context", sesameTemplate.ContextNode.ToString());
                HttpWebRequest request = this.CreateRequest(this._repositoriesPrefix + SesameServer.SystemRepositoryID + "/statements", "*/*", "POST", createParams);

                request.ContentType = MimeTypesHelper.NTriples[0];
                NTriplesWriter ntwriter = new NTriplesWriter();

                this.EnsureSystemConnection();
                this._sysConnection.SaveGraphAsync(request, ntwriter, g, (sender, args, st) =>
                {
                    if (args.WasSuccessful)
                    {
                        //Then we need to declare that said Context is of type rep:RepositoryContext
                        Triple repoType = new Triple(sesameTemplate.ContextNode, g.CreateUriNode("rdf:type"), g.CreateUriNode("rep:RepositoryContext"));
                        this._sysConnection.UpdateGraph(String.Empty, repoType.AsEnumerable(), null, (sender2, args2, st2) =>
                        {
                            if (args.WasSuccessful)
                            {
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, template), state);
                            }
                            else
                            {
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleError(args.Error, "creating a new Store in")), state);
                            }
                        }, st);
                    }
                    else
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, template, StorageHelper.HandleError(args.Error, "creating a new Store in")), state);
                    }
                }, state);
            }
            else
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, template, new RdfStorageException("Invalid template, templates must derive from BaseSesameTemplate")), state);
            }
        }
Esempio n. 43
0
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            StorageHelper<MeasurementUnit> measurementUnitsFile = new StorageHelper<MeasurementUnit>("MeasurementUnits.xml");
            if (!measurementUnitsFile.Exists())
            {
                measurementUnitsFile.Save(
                        new List<MeasurementUnit>()
                        {
                            new MeasurementUnit(MeasurementType.Mass, "Milligram", 1),
                            new MeasurementUnit(MeasurementType.Mass,"Milligram", 1),
                            new MeasurementUnit(MeasurementType.Mass,"Centigram", 10),
                            new MeasurementUnit(MeasurementType.Mass,"Decigram", 100),
                            new MeasurementUnit(MeasurementType.Mass,"Gram", 1000),
                            new MeasurementUnit(MeasurementType.Mass,"Dekagram", 10000),
                            new MeasurementUnit(MeasurementType.Mass,"Hectogram", 100000),
                            new MeasurementUnit(MeasurementType.Mass,"Kilogram", 1000000),
                            new MeasurementUnit(MeasurementType.Mass,"Megagram", 1000000000),
                            new MeasurementUnit(MeasurementType.Mass,"Grain", 64.79891),
                            new MeasurementUnit(MeasurementType.Mass,"Pennyweight", 1555.17384),
                            new MeasurementUnit(MeasurementType.Mass,"Ounce", 28349.5231),
                            new MeasurementUnit(MeasurementType.Mass,"Pound", 453592.37),
                            new MeasurementUnit(MeasurementType.Mass,"Dram", 1771.8452),
                            new MeasurementUnit(MeasurementType.Mass,"Ton", 907184740),
                            new MeasurementUnit(MeasurementType.Mass,"LongTon", 1016046910),
                            new MeasurementUnit(MeasurementType.Mass,"Carat", 200),
                            new MeasurementUnit(MeasurementType.Length,"Millimeter",1),
                            new MeasurementUnit(MeasurementType.Length,"Centimeter",10),
                            new MeasurementUnit(MeasurementType.Length,"Decimeter",100),
                            new MeasurementUnit(MeasurementType.Length,"Meter",1000),
                            new MeasurementUnit(MeasurementType.Length,"Dekameter",10000),
                            new MeasurementUnit(MeasurementType.Length,"Hectometer",100000),
                            new MeasurementUnit(MeasurementType.Length,"Kilometer",1000000),
                            new MeasurementUnit(MeasurementType.Length,"Angstrom",.0000001),
                            new MeasurementUnit(MeasurementType.Length,"Inch",25.4),
                            new MeasurementUnit(MeasurementType.Length,"Feet",304.8),
                            new MeasurementUnit(MeasurementType.Length,"Yard",914.4),
                            new MeasurementUnit(MeasurementType.Length,"Rod",5029.2),
                            new MeasurementUnit(MeasurementType.Length,"Chain",20116.8),
                            new MeasurementUnit(MeasurementType.Length,"Furlong",201168),
                            new MeasurementUnit(MeasurementType.Length,"Mile",1609344),
                            new MeasurementUnit(MeasurementType.Length,"Hand",101.6),
                            new MeasurementUnit(MeasurementType.Length,"Fathom",1828.8),
                            new MeasurementUnit(MeasurementType.Length,"Nautical Mile",1852000),
                            new MeasurementUnit(MeasurementType.Length,"League",5556000),
                            new MeasurementUnit(MeasurementType.Volume,"Milliliter",1),
                            new MeasurementUnit(MeasurementType.Volume,"Cubic Centimeter",1),
                            new MeasurementUnit(MeasurementType.Volume,"Cubic Decimeter",1000),
                            new MeasurementUnit(MeasurementType.Volume,"Cubic Meter",1000000),
                            new MeasurementUnit(MeasurementType.Volume,"Liter",1000),
                            new MeasurementUnit(MeasurementType.Volume,"Deciliter",100),
                            new MeasurementUnit(MeasurementType.Volume,"Centiliter",10),
                            new MeasurementUnit(MeasurementType.Volume,"Cubic Foot",28316.8466),
                            new MeasurementUnit(MeasurementType.Volume,"Cubic Yard",764554.858),
                            new MeasurementUnit(MeasurementType.Volume,"Fluid Ounce",29.5735296),
                            new MeasurementUnit(MeasurementType.Volume,"Pint",473.176473),
                            new MeasurementUnit(MeasurementType.Volume,"Quart",946.352946),
                            new MeasurementUnit(MeasurementType.Volume,"Gallon",3785.41178),
                            new MeasurementUnit(MeasurementType.Volume,"Oil Barrel",158987.295),
                            new MeasurementUnit(MeasurementType.Volume,"Peck",8809.768),
                            new MeasurementUnit(MeasurementType.Volume,"Bushel",35239.072),
                            new MeasurementUnit(MeasurementType.Volume,"Teaspoon",4.92892159),
                            new MeasurementUnit(MeasurementType.Volume,"Tablespoon",14.7867648),
                            new MeasurementUnit(MeasurementType.Volume,"Cup",236.588237)
                        }
                    );
            }
            measurementUnits = measurementUnitsFile.Load();

            StorageHelper<MeasurementObject> measurementObjectsFile = new StorageHelper<MeasurementObject>("MeasurementObjects.xml");
            if (!measurementObjectsFile.Exists())
            {
                measurementObjectsFile.Save(
                        new List<MeasurementObject>()
                        {
                            new MeasurementObject(MeasurementType.Mass,"Paper", 5000),
                            new MeasurementObject(MeasurementType.Mass,"Quarter", 5670),
                            new MeasurementObject(MeasurementType.Mass,"Pencil", 10000),
                            new MeasurementObject(MeasurementType.Mass,"CD", 60951.4747),
                            new MeasurementObject(MeasurementType.Mass,"Toothbrush", 90718),
                            new MeasurementObject(MeasurementType.Mass,"Soda", 240796),
                            new MeasurementObject(MeasurementType.Mass,"Brick", 2721554.22),
                            new MeasurementObject(MeasurementType.Mass,"Xbox360", 3492661.25),
                            new MeasurementObject(MeasurementType.Mass,"Bicycle", 13607771.1),
                            new MeasurementObject(MeasurementType.Mass,"Car", 1814369480),
                            new MeasurementObject(MeasurementType.Length,"Quarter",24.26),
                            new MeasurementObject(MeasurementType.Length,"Dollar",155.95600),
                            new MeasurementObject(MeasurementType.Length,"Pencil",177.8),
                            new MeasurementObject(MeasurementType.Length,"Paper",297),
                            new MeasurementObject(MeasurementType.Length,"Ruler",304.8),
                            new MeasurementObject(MeasurementType.Length,"Door",2032 ),
                            new MeasurementObject(MeasurementType.Length,"Bus",14630.4),
                            new MeasurementObject(MeasurementType.Length,"Storey",3657.6 ),
                            new MeasurementObject(MeasurementType.Length,"Football Field",91440),
                            new MeasurementObject(MeasurementType.Volume,"Drop",.05),
                            new MeasurementObject(MeasurementType.Volume,"Coffee Mug",177.42),
                            new MeasurementObject(MeasurementType.Volume,"Soda Can",355),
                            new MeasurementObject(MeasurementType.Volume,"Pitcher",1000),
                            new MeasurementObject(MeasurementType.Volume,"Sink",5000),
                            new MeasurementObject(MeasurementType.Volume,"Tub",200000),
                            new MeasurementObject(MeasurementType.Volume,"Pool",83358552.9 ),
                            new MeasurementObject(MeasurementType.Volume,"Lake",483509092000000000)
                        }
                    );
            }
            measurementObjects = measurementObjectsFile.Load();

            updateUi();
        }
Esempio n. 44
0
        /// <summary>
        /// Lists the available stores asynchronously
        /// </summary>
        /// <param name="callback">Callback</param>
        /// <param name="state">State to pass to the callback</param>
        public virtual void ListStores(AsyncStorageCallback callback, Object state)
        {
            HttpWebRequest     request = CreateRequest("repositories", MimeTypesHelper.SparqlResultsXml[0], "GET", new Dictionary <string, string>());
            ListStringsHandler handler = new ListStringsHandler("id");

            try
            {
                request.BeginGetResponse(r =>
                {
                    try
                    {
                        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r);
                        SparqlXmlParser parser   = new SparqlXmlParser();
                        parser.Load(handler, new StreamReader(response.GetResponseStream()));
                        response.Close();
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListStores, handler.Strings), state);
                    }
                    catch (WebException webEx)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListStores, StorageHelper.HandleHttpError(webEx, "listing Stores from")), state);
                    }
                    catch (Exception ex)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListStores, StorageHelper.HandleError(ex, "listing Stores from")), state);
                    }
                }, state);
            }
            catch (WebException webEx)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListStores, StorageHelper.HandleHttpError(webEx, "listing Stores from")), state);
            }
            catch (Exception ex)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListStores, StorageHelper.HandleError(ex, "listing Stores from")), state);
            }
        }
Esempio n. 45
0
        /// <summary>
        ///     Clear the complete cache
        /// </summary>
        /// <returns></returns>
        public static Task ClearAll()
        {
            IStorageHelper <object> storage = new StorageHelper <object>(_storageFolder, CacheFolder);

            return(storage.DeleteAllFiles());
        }
        // ARM
        private async Task <ResourceGroup> ActivateResourceGroup(TryWebsitesIdentity userIdentity, AppService appService, DeploymentType deploymentType, Func <ResourceGroup, InProgressOperation, Task <ResourceGroup> > func, BaseTemplate template = null)
        {
            ResourceGroup resourceGroup = null;

            if (userIdentity == null)
            {
                throw new InvalidUserIdentityException();
            }

            var userId = userIdentity.Name;

            try
            {
                if (await StorageHelper.GetAssignedResourceGroup(userId) != null)
                {
                    throw new MoreThanOneResourceGroupException();
                }
                bool resourceGroupFound = false;
                SimpleTrace.TraceInformation($"Searching vscodequeue for template '{template.QueueName}': Count of templates:{await StorageHelper.GetQueueCount(template.QueueName)} ");

                if (await StorageHelper.GetQueueCount(template.QueueName) > 0)
                {
                    var totalTries = 3;
                    var tries      = 0;
                    //bool siteFound = false;
                    while (tries++ < totalTries && !resourceGroupFound)
                    {
                        resourceGroup = await StorageHelper.GetQueueMessage(template.QueueName);

                        resourceGroupFound = (resourceGroup != null);
                        if (resourceGroupFound)
                        {
                            //    try
                            //    {
                            //        var a = Dns.GetHostEntry(resourceGroup.Sites.FirstOrDefault().HostName);
                            //        if (a != null)
                            //        {
                            //            siteFound = true;
                            //        }
                            //    }
                            //    catch
                            //    {
                            //        resourceGroupFound = false;
                            //        SimpleTrace.TraceInformation($"Found ResourceGroup but HostName isnt active '{resourceGroup.ResourceGroupName}' with template {resourceGroup.DeployedTemplateName}");
                            //    }
                            SimpleTrace.TraceInformation($"Found ResourceGroup '{resourceGroup.ResourceGroupName}' with template {resourceGroup.DeployedTemplateName}");
                        }
                        else
                        {
                            SimpleTrace.TraceInformation($"No resource found in free queue for '{template.Name}' ");
                        }
                    }
                }
                if (resourceGroupFound)
                {
                    //mark site in use as soon as it's checked out so that if there is a reload it will be sorted out to the used queue.
                    await resourceGroup.MarkInUse(userId, appService);

                    //var rbacTask = Task.FromResult(false); //RbacHelper.AddRbacUser(userIdentity.Puid, userIdentity.Email, resourceGroup);
                    var process = new InProgressOperation(resourceGroup, deploymentType);
                    _backgroundQueueManager.ResourceGroupsInProgress.AddOrUpdate(userId, s => process, (s, task) => process);
                    SimpleTrace.Diagnostics.Information("site {siteId} is now in use", String.Concat(resourceGroup.CsmId, "/", resourceGroup.Site.SiteName));

                    resourceGroup = await func(resourceGroup, process);

                    var addedResourceGroup = await StorageHelper.AssignResourceGroup(userId, resourceGroup);

                    if (addedResourceGroup)
                    {
                        //this means we just added the resourceGroup for the user.
                        //Removing this line since we have already marked the resourcegroup as in use by the user
                        //await addedResourceGroup.MarkInUse(userId, appService);
                        return(resourceGroup);
                    }
                    else
                    {
                        //this means the user is trying to add more than 1 site.
                        //delete the new site that's not yet added to the used list
                        SimpleTrace.Diagnostics.Information("User asked for more than 1 site. Replacing {resourceGroup.CsmId}", resourceGroup.CsmId);
                        await resourceGroup.DeleteAndCreateReplacement();

                        throw new MoreThanOneResourceGroupException();
                    }
                }
                else
                {
                    SimpleTrace.Diagnostics.Information("No resource group found yet. Shouldnt be here");
                    throw new NoFreeResourceGroupsException();
                }
                // End site specific stuff
            }
            catch (MoreThanOneResourceGroupException)
            {
                throw;
            }
            catch (NoFreeResourceGroupsException)
            {
                throw;
            }
            catch (InvalidGithubRepoException)
            {
                throw;
            }
            catch (Exception e)
            {
                //unknown exception, log it
                SimpleTrace.Diagnostics.Fatal(e, "Unknown error during UserCreate, Count {Count}", Interlocked.Increment(ref _unknownErrorInCreateErrorCount));
            }
            finally
            {
                InProgressOperation temp;
                if (_backgroundQueueManager.ResourceGroupsInProgress.TryRemove(userId, out temp))
                {
                    temp.Complete();
                    LogQueueStatistics();
                }
            }
            //if we are here that means a bad exception happened above, but we might leak a site if we don't remove the site and replace it correctly.
            if (resourceGroup != null)
            {
                DeleteResourceGroup(resourceGroup);
            }
            throw new Exception(Resources.Server.Error_GeneralErrorMessage);
        }
        private async void SubmitPlace()
        {
            try
            {
                UserDialogs.Instance.Loading(title: "Add place...").Show();
                var client = new HttpClient()
                {
                    Timeout = TimeSpan.FromSeconds(30)
                };

                var AuthService = DependencyService.Get <IAuthService>();

                JObject jsonAuth = new JObject
                {
                    { "login", AuthService.UserName },
                    { "password", AuthService.Password },
                    { "db", ServerAuth.DB }
                };
                string imageBase64 = "";
                if (imagefile != null)
                {
                    byte[] imageBytes = await StorageHelper.LoadImage(imagefile.Path);

                    imageBase64 = Convert.ToBase64String(imageBytes);
                }

                JObject jsonReview = new JObject
                {
                    { "title", txtName.Text?.Trim() ?? "" },
                    { "text", txtContent.Text?.Trim() ?? "" },
                    { "image", imageBase64 },
                    { "rating", rating.Rating }
                };

                var location = await LocationHelper.GetCurrentPosition(50);

                JObject jsonPlace = new JObject
                {
                    { "name", txtName.Text?.Trim() ?? "" },
                    { "place_id", typePlace == null? "" : typePlace.id + "" },
                    { "latitude", location == null? 0 : location.Latitude },
                    { "longitude", location == null? 0 : location.Longitude }
                };

                JObject jsonDataObject = new JObject
                {
                    { "auth", jsonAuth },
                    { "review", jsonReview },
                    { "place", jsonPlace }
                };

                JObject jsonData = new JObject
                {
                    { "params", jsonDataObject }
                };


                var data     = jsonData.ToString();
                var content  = new StringContent(data, Encoding.UTF8, "application/json");
                var response = await client.PostAsync(ApiUri.BASE_URL + ApiUri.CREATE_PLACE, content);

                string responseContent = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    SuccessResponse successResponse = JsonConvert.DeserializeObject <SuccessResponse>(responseContent, App.DefaultSerializerSettings);

                    if (successResponse != null && successResponse.Result != null)
                    {
                        if (successResponse.Result.Success)
                        {
                            DependencyService.Get <IToast>().LongAlert("Add new place success!");
                            await Navigation.PopAsync(true);

                            if (this._updateResultListener != null)
                            {
                                this._updateResultListener.OnUpdate(true);
                            }
                        }
                        else if (!string.IsNullOrWhiteSpace(successResponse.Result.Message))
                        {
                            UserDialogs.Instance.Toast(new ToastConfig(successResponse.Result.Message));
                        }
                    }
                    else
                    {
                        Internal.ServerError();
                    }
                }
                else
                {
                    Internal.ServerError();
                }
            }
            catch (TaskCanceledException e)
            {
                UserDialogs.Instance.Toast(new ToastConfig("Bad Connection Error. Try Again"));
            }
            catch (Exception e)
            {
                Internal.ServerError();
            }
            finally
            {
                UserDialogs.Instance.Loading().Hide();
            }
        }
 // ARM
 public async Task <IReadOnlyCollection <ResourceGroup> > GetAllInUseResourceGroups()
 {
     return((await StorageHelper.GetInUseResourceGroups()).Select(s => s.Value).ToList());
 }
 private void Initialize(string dataSourceID)
 {
     _productRepository = StorageHelper.GetTable <Product>(dataSourceID);
     _contentRepository = StorageHelper.GetTable <Content>(dataSourceID);
     _ex = new ServiceException();
 }
 public async Task <IReadOnlyCollection <ResourceGroup> > GetAllFreeResourceGroups()
 {
     return(await StorageHelper.GetAllFreeResources());
 }
 public async Task<bool> SaveAsync(List<Favorite> favorites)
 {
     var objectStorageHelper = new StorageHelper<List<Favorite>>(StorageType.Local);
     bool result = await objectStorageHelper.SaveAsync(favorites, StorageFileName);
     return result;
 }
Esempio n. 52
0
 private async Task <string> SavePhoto(IFormFile file)
 {
     return(await StorageHelper.BlobStorage(file));
 }
Esempio n. 53
0
        /// <summary>
        /// Initializes the sample.
        /// </summary>
        /// <returns>
        /// Returns a task.
        /// </returns>
        public async Task InitializeAsync()
        {
            if (string.IsNullOrWhiteSpace(this.BindingFileSource))
            {
                return;
            }

            if (this.BindingSource == null)
            {
                using (var stream = await StorageHelper.GetPackagedFileAsStreamAsync($"Samples/{this.GroupName}/{this.Name}/{this.BindingFileSource}"))
                {
                    var bindingSource = await stream.ReadAsStringAsync();

                    var regex = new Regex(@"@\[(?<name>.+?):(?<type>.+?):(?<value>.+?)(:(?<parameters>.*))*\]");

                    this.BindingSource = new SampleProperties();
                    var bindings = (IDictionary <string, object>) this.BindingSource.Bindings;

                    foreach (Match match in regex.Matches(bindingSource))
                    {
                        var propertyName       = match.Groups["name"].Value;
                        var propertyTypeString = match.Groups["type"].Value;
                        var defaultValueString = match.Groups["value"].Value;

                        var propertyType = ParseHelper.SafeParseEnum <SamplePropertyType>(propertyTypeString);

                        SampleProperty property;

                        switch (propertyType)
                        {
                        case SamplePropertyType.Enum:
                            try
                            {
                                property = new SampleProperty();
                                var split      = defaultValueString.Split('.');
                                var typeString = string.Join(".", split.Take(split.Length - 1));
                                var enumType   = typeString.GetTypeByName(true, true);
                                property.DefaultValue = Enum.Parse(enumType, split.Last());
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                            break;

                        case SamplePropertyType.Boolean:
                            property = new SampleProperty
                            {
                                DefaultValue = ParseHelper.SafeParseBool(defaultValueString)
                            };
                            break;

                        case SamplePropertyType.Integer:
                            try
                            {
                                var integerProperty = new IntegerSampleProperty
                                {
                                    DefaultValue =
                                        ParseHelper.SafeParseDouble(defaultValueString)
                                };

                                var parameters = match.Groups["parameters"].Value;
                                var split      = parameters.Split('-');

                                integerProperty.MinValue = ParseHelper.SafeParseDouble(split[0]);
                                integerProperty.MaxValue = ParseHelper.SafeParseDouble(split[1]);

                                property = integerProperty;
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                            break;

                        default:
                            property = new SampleProperty()
                            {
                                DefaultValue = defaultValueString
                            };
                            break;
                        }

                        property.Name          = propertyName;
                        property.Code          = match.Value;
                        property.Type          = propertyType;
                        bindings[propertyName] = new SamplePropertyValue(property.DefaultValue);

                        this.BindingSource.Properties.Add(property);
                    }
                }
            }
        }
        public static async Task Run(
            [BlobTrigger("images/{name}.{extension}")] CloudBlockBlob blobImage, string name, string extension, TraceWriter log)
        {
            Person p          = new Person();
            string json       = string.Empty;
            var    collection = await client_document.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Settings.DatabaseId), new DocumentCollection { Id = Settings.PersonCollectionId }, new RequestOptions { OfferThroughput = 1000 });

            //get json file from storage
            CloudBlockBlob blobJson = await StorageHelper.GetBlockBlob($"{name}.json", Settings.AzureWebJobsStorage, "metadata", false);

            using (var memoryStream = new MemoryStream())
            {
                blobJson.DownloadToStream(memoryStream);
                json = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
                p    = JsonConvert.DeserializeObject <Person>(json);
            }

            //validate record has not been processed before
            var query = client_document.CreateDocumentQuery <Person>(collection.Resource.SelfLink, new SqlQuerySpec()
            {
                QueryText = $"SELECT * FROM Person p WHERE p.picture = '{name}.{extension}'"
            });
            int count = query.ToList().Count;

            if (count > 0)
            {
                await MailManager.RegistrationMail(p.ReportedBy, "Person processed before", "There was an exception. The person has been processed before.", p);

                return;
            }

            //determine if image has a face
            List <JObject> list = await client_face.DetectFaces(blobImage.Uri.AbsoluteUri);

            //validate image extension
            if (blobImage.Properties.ContentType != "image/jpeg")
            {
                log.Info($"no valid content type for: {name}.{extension}");
                await blobImage.DeleteAsync();

                await blobJson.DeleteAsync();

                await MailManager.RegistrationMail(p.ReportedBy, "No valid format", "There was an exception. The person image has not a valid format.", p);

                return;
            }

            //if image has no faces
            if (list.Count == 0)
            {
                log.Info($"there are no faces in the image: {name}.{extension}");
                await blobImage.DeleteAsync();

                await blobJson.DeleteAsync();

                await MailManager.RegistrationMail(p.ReportedBy, "No face in the image", "There was an exception. The person face was not identified, ensure the image is correct and clear.", p);

                return;
            }

            //if image has more than one face
            if (list.Count > 1)
            {
                log.Info($"multiple faces detected in the image: {name}.{extension}");
                await blobImage.DeleteAsync();

                await blobJson.DeleteAsync();

                await MailManager.RegistrationMail(p.ReportedBy, "Multiple faces in the image", "There was an exception. The person face was not identified because there are multiple faces in the image, ensure the image has one single face.", p);

                return;
            }

            try
            {
                //register person in Face API
                CreatePerson resultCreatePerson = await client_face.AddPersonToGroup(p.Name + " " + p.Lastname);

                AddPersonFace resultPersonFace = await client_face.AddPersonFace(blobImage.Uri.AbsoluteUri, resultCreatePerson.personId);

                AddFaceToList resultFaceToList = await client_face.AddFaceToList(blobImage.Uri.AbsoluteUri);

                //Add custom settings
                p.IsActive        = 1;
                p.IsFound         = 0;
                p.FaceAPIFaceId   = resultFaceToList.persistedFaceId;
                p.FaceAPIPersonId = resultCreatePerson.personId;
                p.Picture         = $"{name}.jpg";

                await client_document.CreateDatabaseIfNotExistsAsync(new Database { Id = Settings.DatabaseId });

                var result = await client_document.CreateDocumentAsync(collection.Resource.SelfLink, p);

                var document = result.Resource;
            }
            catch (Exception ex)
            {
                await blobImage.DeleteAsync();

                await blobJson.DeleteAsync();

                log.Info($"Error in file: {name}.{extension} - {ex.Message}");
                await MailManager.RegistrationMail(p.ReportedBy, "Internal error", "There was an exception processing the image. Please contact the support.", p);

                return;
            }

            await blobJson.DeleteAsync();

            log.Info("person registered successfully");
            await MailManager.RegistrationMail(p.ReportedBy, "Successfully registration", "The person was successfully registered in the database.", p);
        }
Esempio n. 55
0
 private static void SavePicItemToLocalCache()
 {
     StorageHelper<ObservableCollection<PictureItemViewModel>> stHelper =
         new StorageHelper<ObservableCollection<PictureItemViewModel>>(StorageType.Local);
     stHelper.SaveASync(App.MainViewModel.PictureItems, "PicItems");
 }
Esempio n. 56
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "nearby/{latitude}/{longitude}")] HttpRequest req,
            double latitude,
            double longitude,
            ILogger log)
        {
            List <Location> locationResults = new List <Location>();
            string          BingMapsAPIKey  = Environment.GetEnvironmentVariable("BingMapKey");
            string          point           = $"{latitude},{longitude}";

            // Each Entity Type should be separated by comma ','
            // Type Ids are here: https://docs.microsoft.com/en-us/bingmaps/rest-services/common-parameters-and-types/type-identifiers/
            string entityTypes = "Hospitals";

            string bingEntitySearchTemaplate = $"https://dev.virtualearth.net/REST/v1/LocalSearch/?type={entityTypes}&userLocation={point}&key={BingMapsAPIKey}";

            // Image With Route
            string wp0               = $"{latitude},{longitude}";
            string wp1               = "{0},{1}";
            string bingMapTemplate   = "http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/Routes/?wp.0={0};26;1&wp.1={1};28;2&key={2}";
            string bingRouteTemplate = "http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0={0}&wp.1={1}&du=mi&key={2}";

            try
            {
                HttpClient client  = new HttpClient();
                string     results = await client.GetStringAsync(bingEntitySearchTemaplate);

                BingResponse bingresults = JsonConvert.DeserializeObject <BingResponse>(results);

                if (bingresults.StatusCode == 200)
                {
                    ResourceSet     bingLocationSet = bingresults.ResourceSets.FirstOrDefault();
                    List <Resource> bingLocations   = bingLocationSet.Resources.Take(3).ToList();

                    Location l;
                    // Get the Map for the top 3 items
                    foreach (Resource r in bingLocations)
                    {
                        l = new Location
                        {
                            Name      = r.Name,
                            Telephone = r.PhoneNumber,
                            Address   = r.Address.FormattedAddress,
                            Point     = r.Point,
                            Url       = r.WebSite
                        };

                        #region Get Map Image
                        //TODO: Ensure to deal with failures/errors.
                        string requestedMapUri = string.Format(bingMapTemplate, wp0, string.Format(wp1, l.Point.Coordinates[0], l.Point.Coordinates[1]), BingMapsAPIKey);

                        var map = await client.GetStreamAsync(requestedMapUri);

                        //Upload file to the container
                        AzureStorageConfig asc = new AzureStorageConfig
                        {
                            AccountKey     = Environment.GetEnvironmentVariable("BlobAccountKey"),
                            AccountName    = Environment.GetEnvironmentVariable("BlobAccountName"),
                            ImageContainer = Environment.GetEnvironmentVariable("BlobImageContainer")
                        };

                        string fileName = Guid.NewGuid().ToString() + ".png";

                        string blobUrl = await StorageHelper.UploadFileToStorage(map, fileName, asc);

                        //Write to the blob and get URI
                        l.MapUri = blobUrl;
                        #endregion

                        #region Get Route Details
                        string requestedRouteUri = string.Format(bingRouteTemplate, wp0, string.Format(wp1, l.Point.Coordinates[0], l.Point.Coordinates[1]), BingMapsAPIKey);

                        string routeData = await client.GetStringAsync(requestedRouteUri);

                        BingResponse bingRouteResults = JsonConvert.DeserializeObject <BingResponse>(routeData);
                        ResourceSet  routeResourceSet = bingRouteResults.ResourceSets.FirstOrDefault();

                        if (routeResourceSet != null)
                        {
                            Resource routeResource = routeResourceSet.Resources.FirstOrDefault();
                            if (routeResource != null)
                            {
                                l.Distance = $"{routeResource.TravelDistance:0.0} mi.";
                            }
                        }
                        #endregion

                        locationResults.Add(l);
                    }
                }
                else
                {
                    return(new BadRequestResult());
                }
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(ex));
            }


            return(new OkObjectResult(locationResults));
        }
Esempio n. 57
0
    public async Task StorageHelperNotExistingTest(StorageSerializer serializerType)
    {
        IStorageHelper<MyModel> sh = new StorageHelper<MyModel>(StorageType.Local, serializerType: serializerType);

      var loadedObject = await sh.LoadAsync("myfile561616516");

      Assert.IsNull(loadedObject);

    }
Esempio n. 58
0
 public ConfigBaseViewModel(StorageHelper s)
 {
     storage = s;
 }
Esempio n. 59
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "ImageVerification/")] HttpRequestMessage req, TraceWriter log)
        {
            Domain.ImageVerificationRequest request = await req.Content.ReadAsAsync <Domain.ImageVerificationRequest>();

            var decrypted_token = SecurityHelper.Decrypt(request.Token, Settings.CryptographyKey);

            byte[]   data = Convert.FromBase64String(decrypted_token);
            DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));

            if (when < DateTime.UtcNow.AddMinutes(-5))
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest));
            }

            if (string.IsNullOrEmpty(request.ImageName))
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "Image is required to perform the search"));
            }

            //get json file from storage
            CloudBlockBlob blobImage = await StorageHelper.GetBlockBlob(request.ImageName, Settings.AzureWebJobsStorage, "verification", false);

            List <Person> result = new List <Person>();

            if (blobImage.Exists())
            {
                //determine if image has a face
                List <JObject> list = await client_face.DetectFaces(blobImage.Uri.AbsoluteUri);

                //validate image extension
                if (blobImage.Properties.ContentType != "image/jpeg")
                {
                    log.Info($"no valid content type for: {blobImage.Name}");
                    await blobImage.DeleteAsync();

                    return(req.CreateResponse(HttpStatusCode.BadRequest, result));
                }

                //if image has no faces
                if (list.Count == 0)
                {
                    log.Info($"there are no faces in the image: {blobImage.Name}");
                    await blobImage.DeleteAsync();

                    return(req.CreateResponse(HttpStatusCode.BadRequest, result));
                }

                //if image has more than one face
                if (list.Count > 1)
                {
                    log.Info($"multiple faces detected in the image: {blobImage.Name}");
                    await blobImage.DeleteAsync();

                    return(req.CreateResponse(HttpStatusCode.BadRequest, result));
                }

                //verificate person in Face API
                string             detectFaceId = list.First()["faceId"].ToString();
                List <FindSimilar> similarFaces = await client_face.FindSimilarFaces(detectFaceId);

                foreach (var i in similarFaces)
                {
                    var collection = await client_document.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Settings.DatabaseId), new DocumentCollection { Id = Settings.PersonCollectionId }, new RequestOptions { OfferThroughput = 1000 });

                    var query = client_document.CreateDocumentQuery <Person>(collection.Resource.SelfLink, new SqlQuerySpec()
                    {
                        QueryText  = "SELECT * FROM Person p WHERE (p.faceapifaceid = @id)",
                        Parameters = new SqlParameterCollection()
                        {
                            new SqlParameter("@id", i.persistedFaceId)
                        }
                    });

                    List <Person> personsInDocuments = query.ToList();
                    if (personsInDocuments.Count != 0)
                    {
                        foreach (Person pe in personsInDocuments)
                        {
                            result.Add(pe);
                        }
                    }
                }
            }

            await blobImage.DeleteAsync();

            log.Info("person verified successfully");

            // Fetching the name from the path parameter in the request URL
            return(req.CreateResponse(HttpStatusCode.OK, result));
        }
Esempio n. 60
0
        private void SaveButton_Click(object sender, EventArgs e)
        {
            // get the name of the list
            listCopy.Name = ListName.Text;
            var itemType = ItemTypePicker.SelectedItem as ItemType;
            listCopy.ItemTypeID = itemType != null ? itemType.ID : SystemItemTypes.Task;

            // check for appropriate values
            if (listCopy.Name == "")
            {
                MessageBox.Show("list name cannot be empty");
                return;
            }

            // if this is a new list, create it
            if (list == null)
            {
                // figure out the sort value 
                float sortOrder = 1000f;
                var listItems = folder.Items.Where(it => it.ParentID == listCopy.ParentID).ToList();
                if (listItems.Count > 0)
                    sortOrder += listItems.Max(it => it.SortOrder);
                listCopy.SortOrder = sortOrder;

                // enqueue the Web Request Record (with a new copy of the list)
                // need to create a copy because otherwise other items may be added to it
                // and we want the record to have exactly one operation in it (create the list)
                RequestQueue.EnqueueRequestRecord(RequestQueue.UserQueue,
                    new RequestQueue.RequestRecord()
                    {
                        ReqType = RequestQueue.RequestRecord.RequestType.Insert,
                        Body = new Item(listCopy)
                    });

                // add the item to the local itemType
                folder.Items.Add(listCopy);
            }
            else // this is an update
            {
                // enqueue the Web Request Record
                RequestQueue.EnqueueRequestRecord(RequestQueue.UserQueue,
                    new RequestQueue.RequestRecord()
                    {
                        ReqType = RequestQueue.RequestRecord.RequestType.Update,
                        Body = new List<Item>() { list, listCopy },
                        BodyTypeName = "Item",
                        ID = list.ID
                    });

                // save the changes to the existing list (make a deep copy)
                list.Copy(listCopy, true);

                // save the new list properties back to the item in the folder
                var item = folder.Items.Single(i => i.ID == list.ID);
                item.Name = list.Name;
                item.ItemTypeID = list.ItemTypeID;
            }

            // save the changes to local storage
            StorageHelper.WriteFolder(folder);

            // trigger a sync with the Service 
            App.ViewModel.SyncWithService();

            // trace page navigation
            TraceHelper.StartMessage("ListEditor: Navigate back");

            // Navigate back to the main page
            NavigationService.GoBack();
        }