Esempio n. 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var config = new MongoDBConfig();

            Configuration.Bind(config);

            #region NoteCollecion
            var noteContext    = new NoteContext(config);
            var noteRepository = new NoteRepository(noteContext);
            services.AddSingleton(noteRepository);
            #endregion

            services.AddControllers();

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("http://localhost:4200")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });
        }
Esempio n. 2
0
        public Note GetLastNote()
        {
            int maxid = GetMaxId();

            using (db = new NoteContext())
                return(db.Notes.Where(p => p.Id == maxid).First());
        }
Esempio n. 3
0
        private void upload_Click(object sender, EventArgs e)
        {
            using (var localDb = new NoteContext())
            {
                // Find notes that are not uploaded
                var newNotes = localDb.Notes
                    .Where(n => !n.IsUploaded)
                    .ToList();

                // Upload to remote database
                using (var remoteDb = new NoteContext(_remoteDatabaseOptions))
                {
                    remoteDb.Database.EnsureCreated();
                    remoteDb.Notes.AddRange(newNotes);
                    remoteDb.SaveChanges();
                }

                // Mark as uploaded in local database
                newNotes.ForEach(n => n.IsUploaded = true);
                localDb.SaveChanges();

                MessageBox.Show($"Uploaded {newNotes.Count} notes.");
                LoadExistingNotes();
            }
        }
 public void Initialize(IServiceScopeFactory scopeFactory)
 {
     this.scopeFactory = scopeFactory;
     scope             = this.scopeFactory.CreateScope();
     noteContext       = scope.ServiceProvider.GetRequiredService <NoteContext>();
     random            = new Random();
 }
Esempio n. 5
0
        private void upload_Click(object sender, EventArgs e)
        {
            using (var localDb = new NoteContext())
            {
                // Find notes that are not uploaded
                var newNotes = localDb.Notes
                               .Where(n => !n.IsUploaded)
                               .ToList();

                // Upload to remote database
                using (var remoteDb = new NoteContext(_remoteDatabaseOptions))
                {
                    remoteDb.Database.EnsureCreated();
                    remoteDb.Notes.AddRange(newNotes);
                    remoteDb.SaveChanges();
                }

                // Mark as uploaded in local database
                newNotes.ForEach(n => n.IsUploaded = true);
                localDb.SaveChanges();

                MessageBox.Show($"Uploaded {newNotes.Count} notes.");
                LoadExistingNotes();
            }
        }
Esempio n. 6
0
 public ActionResult Save(Notes model)
 {
     if (User.Identity.IsAuthenticated)
     {
         ViewBag.Message = "Add Note.";
         try
         {
             string      user = User.Identity.GetUserName();
             NoteContext db   = new NoteContext();
             Notes       nt   = new Notes();
             nt.Name = user;
             nt.Date = DateTime.Now;
             nt.Note = model.Note;
             db.Note.Add(nt);
             db.SaveChanges();
         }
         catch (Exception ex)
         {
             throw ex;
         }
         return(RedirectToAction("Index"));
     }
     else
     {
         ViewBag.Message = "You must login to add a note.";
         return(View());
     }
 }
        public NotesController(NoteContext context)
        {
            _context = context;

            // Seed data
            _context.Database.EnsureCreated();
        }
Esempio n. 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            var config = new ServerConfig();

            Configuration.Bind(config);
            var noteContext = new NoteContext(config.MongoDB);
            var repository  = new NoteRepository(noteContext);

            services.AddSingleton <INoteRepository>(repository);

            var consumerConfig = new ConsumerConfig();

            Configuration.Bind("Kafka", consumerConfig);
            services.AddSingleton <ConsumerConfig>(consumerConfig);

            services.AddHostedService <UserConsumer>();

            services.AddControllers();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "Note API",
                    Version     = "v1",
                    Description = "Note API",
                });
            });
        }
Esempio n. 9
0
 private void Page_Loaded(object sender, RoutedEventArgs e)
 {
     using (var db = new NoteContext())
     {
         notes.ItemsSource = db.notes.ToList();
     }
 }
        public async Task <ActionResult> ConfigureDeliveryProvider(string providerAssemblyQualifiedName, bool isEnabled,
                                                                   FormCollection form)
        {
            var provider = GetProvider(providerAssemblyQualifiedName);
            var settings = GetOrCreatePushNotificationDeliveryProviderSettings(provider);

            if (ModelState.IsValid)
            {
                if (settings == null)
                {
                    return(RedirectToAction("Index"));
                }
                // reflection to get the TryUpdateMethod
                var method =
                    GetType()
                    .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy)
                    .First(m => m.Name == "TryUpdateModel" && m.IsGenericMethod && m.GetParameters().Count() == 1)
                    .MakeGenericMethod(provider.Configuration.GetType());

                if ((bool)method.Invoke(this, new[] { provider.Configuration }))//TryUpdateModel call
                {
                    settings.ProviderConfigurationData = JObject.FromObject(provider.Configuration);
                    settings.IsEnabled = isEnabled;
                    await NoteContext.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
            }
            return(View(settings));
        }
Esempio n. 11
0
        private async Task TryConnect(NoteContext context)
        {
            var connectionString = context.Database.GetDbConnection().ConnectionString;
            var builder          = new NpgsqlConnectionStringBuilder(connectionString)
            {
                Database = null
            };

            connectionString = builder.ConnectionString;

            try
            {
                await Policy
                .Handle <NpgsqlException>((ex) =>
                {
                    _logger.LogWarning(EventIds.MigrationTestConnectFailed, ex, "TryMigrate test connect failed, retrying.");
                    return(true);
                })
                .WaitAndRetryAsync(5, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)))
                .ExecuteAsync(async() =>
                {
                    using (var connection = new NpgsqlConnection(connectionString))
                    {
                        await connection.OpenAsync();
                        Console.WriteLine($"Connected: {connectionString}");
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(EventIds.MigrationTestConnectFailed, ex, "TryMigrate could not connect to database.");
                throw;
            }
        }
Esempio n. 12
0
        private void AddDataToMemory()
        {
            using (var context = new NoteContext(ContextOptions))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                var note = new List <Note>()
                {
                    new Note()
                    {
                        Id = 1, Title = "Dog", Body = "Afternoon walk", IsComplete = true
                    },
                    new Note()
                    {
                        Id = 2, Title = "School", Body = "Do homework", IsComplete = true
                    },
                    new Note()
                    {
                        Id = 3, Title = "Errands", Body = "Grocery shop", IsComplete = false
                    },
                    new Note()
                    {
                        Id = 4, Title = "Work", Body = "Code new app", IsComplete = false
                    }
                };

                context.AddRange(note);
                context.SaveChanges();
            }
        }
Esempio n. 13
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,Title,DateCreated,DateModified,Details")] NoteContext noteContext)
        {
            if (id != noteContext.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(noteContext);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!NoteContextExists(noteContext.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(noteContext));
        }
Esempio n. 14
0
        private static NoteContext CreateContext()
        {
            var name    = Guid.NewGuid().ToString();
            var builder = new DbContextOptionsBuilder <NoteContext>().UseInMemoryDatabase(name);
            var context = new NoteContext(builder.Options);

            return(context);
        }
Esempio n. 15
0
 public void SQL(string query)
 {
     using (db = new NoteContext())
     {
         var ids = db.Database.SqlQuery <int>(query).ToList();
         Notes = db.Notes.Where(n => ids.Contains(n.Id)).Include(n => n.Location).OrderBy(n => n.Date).ToList();
     }
 }
Esempio n. 16
0
        public async Task TryMigrate(NoteContext context)
        {
            using (context)
            {
                await TryConnect(context);

                await TryRunMigration(context);
            }
        }
Esempio n. 17
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            using (var db = new NoteContext())
            {
                db.Database.EnsureCreated();
            }

            LoadExistingNotes();
        }
Esempio n. 18
0
 public void Refresh()
 {
     using (db = new NoteContext())
     {
         db.Notes.Include(n => n.Location).Load();
         Notes = db.Notes.Local.ToBindingList();
     }
     SelectedNote = Notes.FirstOrDefault();
 }
Esempio n. 19
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            using (var db = new NoteContext())
            {
                db.Database.EnsureCreated();
            }

            LoadExistingNotes();
        }
 public void Refresh()
 {
     using (var db = new NoteContext())
     {
         Notes.ItemsSource = db.Notes
                             .OrderByDescending(n => n.Created)
                             .ToList();
     }
 }
 public void Refresh()
 {
     using (var db = new NoteContext())
     {
         Notes.ItemsSource = db.Notes
             .OrderByDescending(n => n.Created)
             .ToList();
     }
 }
Esempio n. 22
0
 private void LoadExistingNotes()
 {
     using (var db = new NoteContext())
     {
         noteBindingSource.DataSource = db.Notes
             .OrderByDescending(n => n.Created)
             .ToList();
     }
 }
Esempio n. 23
0
        public SubjectDTO(Subject s)
        {
            subjectId = s.SubjectId;
            name      = s.Name;

            var db = new NoteContext();

            documentCount = db.Documents.Where(d => d.SubjectId == s.SubjectId).ToList().Count;
        }
Esempio n. 24
0
 private void LoadExistingNotes()
 {
     using (var db = new NoteContext())
     {
         noteBindingSource.DataSource = db.Notes
                                        .OrderByDescending(n => n.Created)
                                        .ToList();
     }
 }
Esempio n. 25
0
        public NoteController(NoteContext context)
        {
            _context = context;

            /* if(_context.NoteItems.Count() == 0)
             * {
             *  _context.NoteItems.Add(new NoteItem { Title = "Test" });
             *  _context.SaveChanges();
             * } */
        }
Esempio n. 26
0
        public async Task DeleteNote()
        {
            using (var context = new NoteContext(ContextOptions))
            {
                var controller = new NotesController(context);
                var response   = await controller.DeleteNote(1);

                Assert.False(context.Set <Note>().Any(e => e.Id == 1));
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;

            // TODO Ensure the local database is created
            using (var db = new NoteContext())
            {
            }
        }
Esempio n. 28
0
        private void TagDelete_Click(object sender, RoutedEventArgs e)
        {
            if (_noteElmList.Count + _promptElmList.Count != 0)
            {
                var result = MessageBox.Show("Удалить все элементы, соответствующие тегу?", "notes", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    using (NoteContext db = new NoteContext())
                    {
                        var noteElmList   = db.Notes.ToList();
                        var promptElmList = db.Prompts.ToList();

                        foreach (var note in _noteElmList)
                        {
                            db.Notes.Remove(db.Notes.Where(n => n.ID == note.ID).FirstOrDefault());
                        }

                        foreach (var prompt in _promptElmList)
                        {
                            db.Prompts.Remove(db.Prompts.Where(n => n.ID == prompt.ID).FirstOrDefault());
                        }

                        db.SaveChanges();
                    }
                }
                else
                {
                    using (NoteContext db = new NoteContext())
                    {
                        var noteElmList   = db.Notes.ToList();
                        var promptElmList = db.Prompts.ToList();

                        foreach (var note in _noteElmList)
                        {
                            var noteModel = db.Notes.Where(n => n.ID == note.ID).FirstOrDefault();
                            noteModel.TagsNote = "";
                        }

                        foreach (var prompt in _promptElmList)
                        {
                            var promptModel = db.Prompts.Where(n => n.ID == prompt.ID).FirstOrDefault();
                            promptModel.TagsPrompt = "";
                        }

                        db.SaveChanges();
                    }
                }
            }
            using (NoteContext db = new NoteContext())
            {
                db.Tags.Remove(db.Tags.Where(n => n.ID == elmTag.ID).FirstOrDefault());
                db.SaveChanges();
            }
            Content = new HomePage(2);
        }
Esempio n. 29
0
        private void CreateNewPrompt_Click(object sender, RoutedEventArgs e)
        {
            DateTime date;
            bool     push;

            if (tbTextPrompt.Text == "")
            {
                MessageBox.Show("Попытка создать пустое напоминание.", "notes", MessageBoxButton.OK);
            }
            else if (!DateTime.TryParse(tbExpirationDate.Text, out _) && tbExpirationDate.Text != "")
            {
                MessageBox.Show("Неверный формат ввода времени.", "notes", MessageBoxButton.OK);
            }
            else if (tbExpirationDate.Text != "" && DateTime.Parse(tbExpirationDate.Text) < DateTime.Now)
            {
                MessageBox.Show("Напоминание не может быть задано в прошедшем времени.", "notes", MessageBoxButton.OK);
            }
            else
            {
                if (rbPush.IsChecked == true)
                {
                    push = true;
                }
                else
                {
                    push = false;
                }
                if (tbExpirationDate.Text == "")
                {
                    date = DateTime.Now.AddMinutes(10);
                }
                else
                {
                    date = DateTime.Parse(tbExpirationDate.Text);
                }
                using (NoteContext db = new NoteContext())
                {
                    PromptModels promptModels = new PromptModels {
                        CreationDate = DateTime.Now, ExpirationDate = date, Push = push, TextPrompt = tbTextPrompt.Text, TagsPrompt = cbTagsPrompt.Text
                    };
                    db.Prompts.Add(promptModels);
                    db.SaveChanges();

                    if (push)
                    {
                        new ToastContentBuilder()
                        .AddText("Напоминание")
                        .AddText(promptModels.TextPrompt)
                        .AddText(promptModels.CreationDate.ToString())
                        .Schedule(promptModels.ExpirationDate);
                    }
                }
                Content = new HomePage(1);
            }
        }
Esempio n. 30
0
        private void addNote_Click(object sender, RoutedEventArgs e)
        {
            using (var db = new NoteContext())
            {
                var note = new Note { text = noteText.Text, created = DateTime.Now };
                db.notes.Add(note);
                db.SaveChanges();

                notes.ItemsSource = db.notes.ToList();
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;

            // TODO Ensure the local database is created
            using (var db = new NoteContext())
            {

            }
        }
Esempio n. 32
0
        public void ReturnNothingIfNoNotesConfigured()
        {
            var options = new DbContextOptionsBuilder <NoteContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;

            using (var context = new NoteContext(options))
            {
                var controller = new NotesController(context);
                Assert.Empty(controller.Get().Value);
            }
        }
Esempio n. 33
0
        public async Task <IActionResult> Create([Bind("ID,Title,DateCreated,DateModified,Details")] NoteContext noteContext)
        {
            if (ModelState.IsValid)
            {
                _context.Add(noteContext);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(noteContext));
        }
Esempio n. 34
0
 public Note GetNote(int noteId)
 {
     using (var context = new NoteContext())
     {
         context.Notes.Where(n => n.Id == noteId)
         .Include(n => n.Location)
         .Load();
         var note = context.Notes.Local.ToBindingList().FirstOrDefault();
         return(note);
     }
 }
Esempio n. 35
0
 public NoteController(NoteContext context,
                       ILogger <NoteContext> logger)
 {
     _context = context;
     _logger  = logger;
     //if (_context.Notes.Count() == 0)
     //{
     //    _context.Notes.Add(new Note() { Frequency = 333, NoteName = "E" });
     //    _context.SaveChanges();
     //}
 }
Esempio n. 36
0
 private async Task TryRunMigration(NoteContext context)
 {
     try
     {
         await context.Database.MigrateAsync();
     }
     catch (Exception ex)
     {
         // Ignored
         _logger.LogError(EventIds.MigrationFailed, ex, "Migration failed to run: {message}", ex.Message);
     }
 }
        public Integrate_testing()
        {
            var optionBuilder = new DbContextOptionsBuilder <NoteContext>();

            optionBuilder.UseInMemoryDatabase("any string");
            notecontext = new NoteContext(optionBuilder.Options);
            notecontext.Note.AddRange(notebyid);
            notecontext.SaveChanges();


            _controller = new NotesController(notecontext);
        }
Esempio n. 38
0
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            var note = new Note { Created = DateTime.Now, Text = Note.Text };

            using (var db = new NoteContext())
            {
                db.Notes.Add(note);
                db.SaveChanges();
            }

            Note.Text = string.Empty;
        }
Esempio n. 39
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
                Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
                Microsoft.ApplicationInsights.WindowsCollectors.Session);
            this.InitializeComponent();
            this.Suspending += OnSuspending;

            using (var db = new NoteContext())
            {
                db.Database.ApplyMigrations();
            }
        }
Esempio n. 40
0
        private void save_Click(object sender, EventArgs e)
        {
            var note = new Note { Created = DateTime.Now, Text = this.note.Text };

            using (var db = new NoteContext())
            {
                db.Notes.Add(note);
                db.SaveChanges();
            }

            noteBindingSource.Insert(0, note);
            this.note.Text = string.Empty;
        }
Esempio n. 41
0
        private void upload_Click(object sender, EventArgs e)
        {
            using (var localDb = new NoteContext())
            {
                // Find notes that are not uploaded
                var newNotes = localDb.Notes
                    .Where(n => !n.IsUploaded)
                    .ToList();

                // TODO Upload to remote database
                var connectionString = ConfigurationManager.ConnectionStrings["RemoteDatabase"].ConnectionString;


                // Mark as uploaded in local database
                newNotes.ForEach(n => n.IsUploaded = true);
                localDb.SaveChanges();

                MessageBox.Show($"Uploaded {newNotes.Count} notes.");
                LoadExistingNotes();
            }
        }
Esempio n. 42
0
 public NoteController(NoteContext context)
 {
     this.context = context;
 }