public async Task <HttpResponseMessage> Post([FromBody] JToken jsonbody)//[FromBody] FormDocument form) //FormDocument form) { //FormDocument form = new FormDocument(); DocumentDBRepository.Initialize(); Document doc; //string c = await Request.Content.ReadAsStringAsync(); //Console.Write(c); JTokenReader jtReader = new JTokenReader(jsonbody); dynamic form = JObject.Parse(jsonbody.ToString()); //form.LoadFrom(jtReader); //form.formType = jsonbody.Value<string>("ftype"); //form.formVersion = jsonbody.Value<string>("ver"); form.timeStamp = DateTime.Now; //form.data = jsonbody.Value<string>("data"); form.creator = Request.GetRequestContext().Principal.Identity.Name; form.status = ConfigurationManager.AppSettings["defaultStatus"]; try { //doc = await DocumentDBRepository.CreateItemAsync(jsonbody); doc = await DocumentDBRepository.CreateItemAsync(form); } catch { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } HttpResponseMessage r = Request.CreateResponse(HttpStatusCode.OK, doc.Id); r.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); return(r); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app">IApplicationBuilder instance, which is a class that provides the mechanisms to configure an application's request pipeline.</param> /// <param name="env">IHostingEnvironment instance, which provides information about the web hosting environment an application is running in.</param> /// <param name="logger">Ilogger instance for logging the errors.</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger) { try { DocumentDBRepository.Initialize(); } catch (Exception e) { logger.LogError(e.Message + ' ' + e.StackTrace); } app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseRouting(); app.UseCors(AllowAnyOrigin); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.Options.StartupTimeout = TimeSpan.FromSeconds(120); spa.UseReactDevelopmentServer(npmScript: "start"); } }); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app">IApplicationBuilder instance.</param> /// <param name="env">IWebHostEnvironment instance.</param> /// <param name="logger">ILogger instance.</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger) { try { DocumentDBRepository.Initialize(); } catch (Exception e) { logger.LogError(e.Message + ' ' + e.StackTrace); } if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles() .UseWebSockets() .UseRouting() .UseAuthorization() .UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
static async Task MainAsync(string[] args) { DocumentDBRepository <SongRecord> .Initialize(); Console.WriteLine("Get songs out of CosmosDB"); var songsNoGenres = await DocumentDBRepository <SongRecord> .GetItemsAsync(x => true, -1); var httpclient = new HttpClient(); var apiKey = ConfigurationManager.AppSettings["LastfmAPIKey"]; foreach (var song in songsNoGenres.Where(s => !string.IsNullOrEmpty(s.Artist))) { // Strip out unwanted characters var artist = Regex.Replace(song.Artist.ToLowerInvariant(), @"[^a-z0-9\s-]", ""); artist = artist.Replace(' ', '+'); var title = Regex.Replace(song.Title.ToLowerInvariant(), @"[^a-z0-9\s-]", ""); title = title.Replace(' ', '+'); var request = $"http://ws.audioscrobbler.com/2.0/?method=track.gettoptags&artist={artist}&track={title}&api_key={apiKey}&format=json"; //Console.WriteLine($"Requesting {artist}: {title}"); var tagResponse = await httpclient.GetStringAsync(request); var tags = JsonConvert.DeserializeObject <LastFMTagResponse>(tagResponse); song.Genre = GetGenre(tags); var genres = string.Join(',', song.Genre); Console.WriteLine($"Artist:{artist} Title:{title} Genres:{genres}"); await DocumentDBRepository <SongRecord> .UpdateItemAsync(song.id, song); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); DocumentDBRepository <BasicUserInfoModel> .Initialize(); DocumentDBRepository <CVData> .Initialize(); DocumentDBRepository <LinkedInProfile> .Initialize(); DocumentDBRepository <LookupInfo> .Initialize(); DocumentDBRepository <DiscoverInfo> .Initialize(); DocumentDBRepository <RegisterBindingModel> .Initialize(); DocumentDBRepository <CVMatch> .Initialize(); DocumentDBRepository <CVChat> .Initialize(); DocumentDBRepository <CVComments> .Initialize(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); DocumentDBRepository <JObject> .Initialize(); }
private static async Task MainAsync(string[] args) { Console.WriteLine("Downloading eurovision songs"); var eurovisionRepo = new EurovisionSongRepository(); // Only get songs in English after 1998 var eurovisionSongs = await eurovisionRepo.GetItemsAsync(x => x.Language == "English" && x.Year > 1998, -1); var songs = new List <SongRecord>(); DocumentDBRepository <SongRecord> .Initialize(); foreach (var euroSong in eurovisionSongs) { var song = new SongRecord { id = euroSong.id, Artist = euroSong.Artist, Lyrics = euroSong.Lyrics, Genre = new List <string> { Genre.Eurovision.ToString(), Genre.Pop.ToString() }, LyricsDownloaded = true, Released = new DateTime(euroSong.Year, 5, 1), Title = euroSong.Title }; Console.WriteLine($"Saving {song.id}"); songs.Add(song); await DocumentDBRepository <SongRecord> .UpsertItemAsync(song.id, song); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); DocumentDBRepository <Passenger> .Initialize(); // Initialize DB Conversation.UpdateContainer( builder => { builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly())); // Using Azure Table Storage var store = new TableBotDataStore(ConfigurationManager.AppSettings["AzureWebJobsStorage"]); // requires Microsoft.BotBuilder.Azure Nuget package // To use CosmosDb or InMemory storage instead of the default table storage, uncomment the corresponding line below // var store = new DocumentDbBotDataStore("cosmos db uri", "cosmos db key"); // requires Microsoft.BotBuilder.Azure Nuget package // var store = new InMemoryDataStore(); // volatile in-memory store builder.Register(c => store) .Keyed <IBotDataStore <BotData> >(AzureModule.Key_DataStore) .AsSelf() .SingleInstance(); }); // GlobalConfiguration.Configure(WebApiConfig.Register); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("CorsPolicy"); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHub <ChartHub>("/chart"); endpoints.MapHub <CandidateHub>("/candidate"); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Cosmos API v1"); }); app.UseMvc(); DocumentDBRepository <Candidate> .Initialize(Configuration); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { // ASP.net core requires dependancy injection? /* * Service for file upload (using IFileProvider */ DocumentDBRepository <AdminViewModel> .Initialize(); client = new DocumentClient(new Uri(EndpointUri), PrimaryKey); this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = DatabaseName }); this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(DatabaseName), new DocumentCollection { Id = CollectionName }); services.AddSingleton(client); services.AddSingleton <IFileProvider>( new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"))); services.AddTransient <IMailService, SGMailService>(); services.AddSingleton <PenCommV1Callbacks, PenConnector>(); services.AddMvc(); }
public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { try { log.LogInformation("Getting song ids.."); var httpClient = new HttpClient(); var response = await httpClient.GetStringAsync("https://musicdemons.com/api/v1/song"); var songs = JsonConvert.DeserializeObject <List <Song> >(response); var songRecords = new List <SongRecord>(); songs.ForEach(s => songRecords.Add(new SongRecord(s))); DocumentDBRepository <SongRecord> .Initialize(); var tasks = new List <Task>(); songRecords.ForEach(s => tasks.Add(DocumentDBRepository <SongRecord> .UpsertItemAsync(s.id, s))); await Task.WhenAll(tasks); return(new OkObjectResult($"Done")); } catch (Exception ex) { return(new BadRequestObjectResult(ex.Message)); } }
protected void Application_Start() { this.RegisterBotModules(); GlobalConfiguration.Configure(WebApiConfig.Register); DocumentDBRepository <Models.Login> .Initialize(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. DocumentDBRepository <Integration> .Initialize(); services.AddMvc(); }
public void Initialize() { string endpoint = "https://localhost:8081"; string authKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="; Console.WriteLine("Using endpoint: ", endpoint); DocumentDBRepository <Item> .Initialize(endpoint, authKey); }
public void CosmosDBInitialize() { this._EndpointUrl = TestContext.Properties["endpoint"].ToString(); this._AuthKey = TestContext.Properties["authKey"].ToString(); this._DatabaseName = TestContext.Properties["database"].ToString(); this._CollectionName = TestContext.Properties["collection"].ToString(); DocumentDBRepository <Person> .Initialize(this._EndpointUrl, this._AuthKey, this._DatabaseName, this._CollectionName); }
public void Initialize() { string endpoint = TestContext.Properties["endpoint"].ToString(); string authKey = TestContext.Properties["authKey"].ToString(); Console.WriteLine("Using endpoint: ", endpoint); DocumentDBRepository <Item> .Initialize(endpoint, authKey); }
private static void init(ExecutionContext context) { if (config == null) { config = ConfigurationManager.GetConfiguration(context); } DocumentDBRepository <User> .Initialize(config); }
public Startup(IConfiguration configuration) { Configuration = configuration; StaticConfig = configuration; logger = new GraphLogger(typeof(Startup).Assembly.GetName().Name); observer = new SampleObserver(logger); DocumentDBRepository.Initialize(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); DocumentDBRepository <AppDev3A.Models.Student> .Initialize(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); UnityConfig.RegisterComponents(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); DocumentDBRepository <Models.ConversationInfo> .Initialize(); }
public async Task ShouldGetAllIncidentsTest() { await DocumentDBRepository <Incident> .Initialize(endpointUrl, authorizationKey, databaseId, collectionId); var incidents = await DocumentDBRepository <Incident> .GetItemsAsync(i => !i.Resolved); Assert.IsNotNull(incidents); Assert.AreNotEqual(0, incidents.ToList().Count); }
public async Task ShouldGetAllIncidentCountTest() { await DocumentDBRepository <Incident> .Initialize(endpointUrl, authorizationKey, databaseId, collectionId); var incidentCount = DocumentDBRepository <Incident> .GetItemsCount(true); Assert.AreNotEqual(0, incidentCount); Console.WriteLine($"Incident count is {incidentCount}"); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); DocumentDBRepository <Person> .Initialize(); }
public async Task ShouldCreateNewIncidentTest() { string methodName = System.Reflection.MethodInfo.GetCurrentMethod().Name; Incident testIncident = IncidentGenerator.GetTestIncident(methodName); await DocumentDBRepository <Incident> .Initialize(endpointUrl, authorizationKey, databaseId, collectionId); Document newIncident = await DocumentDBRepository <Incident> .CreateItemAsync(testIncident); Assert.IsNotNull(newIncident); }
public DocumentDBRepositoryTests() { var endPoint = Environment.GetEnvironmentVariable("endPoint"); var authKey = Environment.GetEnvironmentVariable("authKey"); var databaseId = Environment.GetEnvironmentVariable("databaseId"); var collectionId = Environment.GetEnvironmentVariable("collectionId"); _documentDBRepository = new DocumentDBRepository <Dummy>(); _documentDBRepository.Initialize(endPoint, authKey, databaseId, collectionId); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); DocumentDBRepository <Client> .Initialize(); }
public void ConnectionToDocumentDBSucceeds() { // relies on App.config values try { DocumentDBRepository <TodoItem> .Initialize(); } catch (Exception ex) { Assert.Fail(ex.Message, ex); } }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); string endpoint = ConfigurationManager.AppSettings["CosmosDbEndpoint"]; string authKey = ConfigurationManager.AppSettings["CosmosDbKey"]; DocumentDBRepository.Initialize(endpoint, authKey); var results = await DocumentDBRepository.GetUsersAsync(); return(req.CreateResponse(HttpStatusCode.OK, results)); }
static private async Task DoWork() { DocumentDBRepository <produce.Models.Feed> .Initialize(); DocumentDBRepository <produce.Models.Item> .Initialize(); //process video to audo, upload to blob, get file properties (length, size) ProcessAndUploadVideo(); //write this new record to DocDB await WriteToDocDB(); //use DocDB to write the RSS Feed await GetRssFeed(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); DocumentDBRepository <WOModel> .Initialize(); }