c# – Asp.Net overall design pattern integrating REST, dependency injection, and Hosted Services (See full project at Github)

I’m new to C#, and want to conform as much as possible to good design patterns. This code is the beginning of a Microservice, running as Asp.Net. It is based on a Microsoft tutorial doing similar work.

It has three functional components currently:

  1. Converts a CSV file to JSON, for return via REST
  2. A REST controller to test the conversion of the CSV to JSON return
  3. A background service which monitors a directory looking for changed files. The file attributes (Path, Date, Checksum) are stored in a MongoDB database via a Repository.

Opinions/Recommendations regarding the design patterns welcomed.

The full code can be found at: https://github.com/BioComSoftware/unite-radimaging-source-n2m2.git

BONUS: Notice in FileSearchHostedService.cs, I instantiate the Repository objects explicitly. I think it would be more appropriate to have them as Dependency Injection – but I couldn’t get it to work. Notice the commented-out lines that would have done this. My understanding is; I would need to do this with IScopedProcessingService – but I have no idea how to do this with this specific code.

Structure

(Startup.cs)

using unite.radimaging.source.n2m2.Data;
using unite.radimaging.source.n2m2.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
//using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace unite.radimaging.source.n2m2 {
    public class Startup {
        public Startup(IConfiguration configuration) {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime.
        // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {

            services.AddControllers();

            services.AddScoped<IFoundFileContext, FoundFileContext>();
            services.AddScoped<IFoundFileRepository, FoundFileRepository>();
        }

        // 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.UseExceptionHandler("/error");
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => { 
                endpoints.MapControllers(); 
            });
        }
    }
}

(FoundFileRepository.cs)

using unite.radimaging.source.n2m2.Data;
using unite.radimaging.source.n2m2.Entities;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace unite.radimaging.source.n2m2.Repositories {
   public class FoundFileRepository : IFoundFileRepository {
       private readonly IFoundFileContext _context;
       public FoundFileRepository(IFoundFileContext context) {
           _context = context ?? throw new ArgumentNullException(nameof(context));
       }

       public async Task<IEnumerable<FoundFile>> GetFiles() {
       return await _context
           .FoundFiles
           .Find(p => true)
           .ToListAsync();
       }

       public async Task<FoundFile> GetFile(string id) {
           return await _context
                          .FoundFiles
                          .Find(p => p.Id == id)
                          .FirstOrDefaultAsync();
       }

       public async Task<FoundFile> GetFileByPath(string path) {
           return await _context
                          .FoundFiles
                          .Find(p => p.Path == path)
                          .FirstOrDefaultAsync();
       }

       public async Task<FoundFile> GetFileByChecksum(string checksum) {
           return await _context
                          .FoundFiles
                          .Find(p => p.Checksum == checksum)
                          .FirstOrDefaultAsync();
       }

       //public async Task<IEnumerable<FoundFile>> GetFileByMtime(string mtime) {
       //    FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.ElemMatch<DateTime>(p => p.Mtime, mtime);

       //    return await _context
       //                    .FoundFiles
       //                    .Find(filter)
       //                    .ToListAsync();
       //}

       //public async Task<IEnumerable<FoundFile>> GetFileBySize(long size) {
       //    FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.ElemMatch<long>(p => p.Size, size);

       //    return await _context
       //                    .FoundFiles
       //                    .Find(filter)
       //                    .ToListAsync();
       //}

       public async Task CreateFile(FoundFile foundFile) {
           await _context.FoundFiles.InsertOneAsync(foundFile);
       }

       public async Task<bool> UpdateFile(FoundFile foundFile) {
           var updateResult = await _context.FoundFiles.ReplaceOneAsync(
               filter: g => g.Path == foundFile.Path, replacement: foundFile);
           return updateResult.IsAcknowledged && updateResult.ModifiedCount > 0;
       }

       public async Task<bool> DeleteFile(string path) {
           FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.Eq(p => p.Path, path);

           DeleteResult deleteResult = await _context
                                               .FoundFiles
                                               .DeleteOneAsync(filter);

           return deleteResult.IsAcknowledged
               && deleteResult.DeletedCount > 0;
       }
   }
}

(FileSearchHostedService.cs)

using unite.radimaging.source.n2m2.Repositories;
using unite.radimaging.source.n2m2.Entities;
using unite.radimaging.source.n2m2.Data;
using Serilog;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace unite.radimaging.source.n2m2.HostedServices {
    public class FileSearchHostedService : BackgroundService {
        private readonly IConfiguration _configuration;
        //private IFoundFileRepository _repository;

        public FileSearchHostedService(
            //IFoundFileRepository repository,
            IConfiguration configuration
            ) {
            //_repository = repository ?? throw new ArgumentNullException(nameof(repository));
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
        }

        protected override async Task ExecuteAsync(CancellationToken cancellationToken) {
            Log.Information("FileSearchHostedService: File searching started.");

            cancellationToken.Register(() => Log.Information("Processing service stopped"));

            //string checksum;
            string _current_path;
            FileInfo _current_file;
            FoundFile _foundFile;
            FoundFile _existingFile;
            FoundFile _addFoundFile;
            FoundFileContext FoundfileContext = new FoundFileContext(_configuration); // Normal instantiation, in leiu of injection
            FoundFileRepository _repository = new FoundFileRepository(FoundfileContext);  // Normal instantiation, in leiu of injection

            while (!cancellationToken.IsCancellationRequested) {
                Log.Information("Searching files...");
                string dir = _configuration.GetValue<string>("FileSearchSettings:SearchDir");
                string() files = Directory.GetFiles(dir);
                foreach (string filename in files) {
                    Log.Debug($"Parsing '{filename}'");

                    _current_file     = new FileInfo(filename);
                    _current_path = Path.GetFullPath(Path.Combine(_current_file.Directory.ToString(), _current_file.Name));

                    _foundFile = new FoundFile() {
                        Path = _current_path,
                        Size = _current_file.Length,
                        Mtime = _current_file.LastWriteTime,
                        Checksum = FileChecksum.getChecksum(filename)
                    };
                    Console.WriteLine("==========================");
                    _existingFile = await _repository.GetFileByPath (_current_path);
                    Console.WriteLine("past _repository.GetFileByPath");

                    try {
                        Console.WriteLine($"{_existingFile.Path} exists!!!");
                        Console.WriteLine($"     _existingFile.Checksum: {_existingFile.Checksum}");
                        Console.WriteLine($"     _existingFile.Length = {_existingFile.Size}");
                        Console.WriteLine($"     _existingFile.LastWriteTime = ({_existingFile.Mtime}");
                    }
                    catch {
                        Console.WriteLine($"Creating MongoDB for file {_foundFile.Path} ");
                        _addFoundFile = new FoundFile() {
                            Path = _foundFile.Path,
                            Size = _foundFile.Size,
                            Mtime = _foundFile.Mtime,
                            Checksum = _foundFile.Checksum
                        };
                        await _repository.CreateFile(_addFoundFile);
                    }
                }

                await Task.Delay(
                    _configuration.GetValue<int>("FileSearchSettings:Delay"),
                    cancellationToken
                    );
            }
        }
    }
}

sql server – Azure SQL Database throwing error 1132 “The elastic pool has reached its storage limit” error, even if it’s not full

I’m trying to execute the following (sample) batch in an Azure SQL Database inside an Elastic Pool:

drop table if exists (dbo).(InsertTest);
create table (dbo).(InsertTest) (
    (id) uniqueidentifier,
    (filler) nvarchar(max)
);

insert into (dbo).(InsertTest) ((id), (filler))
select top 1000 newid(), replicate('X', 2048)
from (sys).(objects) as (T1)
    cross join (sys).(objects) as (T2);

/* drop table if exists (dbo).(InsertTest); */

But the insert statement fails with the error message:

Msg 1132, Level 16, State 1, Line 1
The elastic pool has reached its storage limit. The storage used for the elastic pool cannot exceed (51200) MBs.

I tried to see if I ran out of space by running the query

select
    (type_desc)         as (file_type),
    (size) / 128        as (size_in_MB),
    (max_size) / 128    as (max_size_in_MB)
from (sys).(database_files);

but it seems that I still have space left.

file_type size_in_MB max_size_in_MB
ROWS 320 256000
LOG 584 1048576
FILESTREAM 0 0

What can I do about it? Am I missing something?

real analysis – Do we have full control the oscillation of a function by modifying it on a small set?

Definitions and some motivation:

Let $mathcal B$ be the set of bounded measurable functions from $(0, 1)$ to $mathbb R$. Denote by $mathcal N$ the set of measurable subsets of $(0, 1)$ with Lebesgue measure $0$.

Given a function $f in mathcal B$, define the function $mathcal Of$ by

$mathcal Of(x) := inf_{N in mathcal N} lim_{delta to 0} sup_{y, z in B_delta (x) setminus N} |f(y) – f(z)|$.

Thanks to Lusin’s theorem, we know that we can modify $f$ on an arbitrarily small set and get a continuous function, and so we force the oscillation to be $0$ everywhere. But can we force it to be whatever we want?

Question:

Does there exist, for any $f, g in mathcal B$ and $epsilon, varepsilon > 0$, a function $f’ in mathcal B$ such that the following conditions are satisfied?

i) $f = f’$ everywhere except for a set of measure at most $epsilon$.

ii) $Of’ = Og$ everywhere.

iii) $int_{(0, 1)} |f’ – f’| dmu < int_{(0, 1)} |Of – Og| dmu + epsilon$

Note: All functions are genuine functions and not equivalence classes modulo null sets of such.

SSD KVM VPS (From 1.75$)- 30% Lifetime OFF (🌎USA,NL)- ⚡️DDOS Protected⚡️ Full root access. | Proxies123.com

Host Mayo offers SSD KVM VPS with advance features like instant upgrades, DDOS protection, Gigabit Uplink and 24/7 Support. We have been in business since 2015. Over the span of last few years we have expanded our products range to cover simple web hosting to enterprise level VPS & dedicated servers. We offer exceptional customer support and guarantee 99% uptime. Today we bring exclusive vps plans with 30% recurring discount using coupon “coco”.

☁ 512MB RAM VPS – 2.5$/mo or 30$/year 1.75$/mo or 21$/year

  • 5 GB SSD Disk Space
  • 512 GB Bandwidth
  • 512 MB RAM
  • 256MB Swap
  • 0.5 CPU Core
  • 1 IPV4
  • VPS Plans | Order Now

☁ 1GM RAM VPS – 5$/mo or 60$/year 3.5$/mo or 42$/year

  • 20 GB SSD Disk Space
  • 1 TB Bandwidth
  • 1 GB RAM
  • 512MB Swap
  • 1 CPU Core
  • 1 IPV4
  • VPS Plans | Order Now

☁ 2GM RAM – 10$/mo or 120$/year 7$/mo or 84$/year

  • 40 GB SSD Disk Space
  • 2 TB Bandwidth
  • 2 GB RAM
  • 1GB Swap
  • 2 CPU Core
  • 1 IPV4
  • VPS Plans | Order Now

☁ 3GM RAM VPS – 15$/mo or 180$/year 10.5$/mo or 126$/year

  • 60 GB SSD Disk Space
  • 3 TB Bandwidth
  • 3 GB RAM
  • 1.5 GB Swap
  • 2 CPU Core
  • 1 IPV4
  • VPS Plans | Order Now

☁ 4GM RAM VPS – 20$/mo or 240$/year 14$/mo or 168$/year

  • 80 GB SSD Disk Space
  • 4 TB Bandwidth
  • 4 GB RAM
  • 2 GB Swap
  • 4 CPU Core
  • 1 IPV4
  • VPS Plans | Order Now

☁ 8GM RAM VPS – 35$/mo or 420$/year 24.5$/mo or 294$/year

  • 100 GB SSD Disk Space
  • 8 TB Bandwidth
  • 8 GB RAM
  • 4 GB Swap
  • 4 CPU Core
  • 1 IPV4
  • VPS Plans | Order Now

Payment Methods
We accept PayPal, Credit Card, BitCoins, LTC, BCH, ETH & TRON other cryptocurrencies.

Frequently Asked Questions
1. Is RDNS Supported? Yes
2. Custom ISO Allowed? Yes
3. Unlimited Reboot and Installations? Yes
4. Additional IP Allowed? Yes
5. User ISO allowed? Yes

Server Features

  • Intel Xeon CPU
  • All Ports Open
  • DDOS Protected
  • Pure SSD storage
  • KVM Virtualization
  • Test IP NL: 169.239.130.2
  • Test IP USA: 92.118.234.83
  • Unlimited OS reinstall
  • Virtualizor Control Panel
  • Popular Operating System Choices including Centos 8, Ubuntu 20 & Debian 10

Reviews & Awards
Hosting Reviews: https://hostmayo.com/reviews-awards

Connect with US
If you have any questions, please feel free to contact us at admin@hostmayo.com || Skype @hostmayo|| Tweeter @hostmayo|| Facebook HostMayoServers

 

plotting – “Mesh -> Full” Disables MeshFunction in ParametricPlot3D

Here’s my code

a := -2
q := 1/Sqrt(Abs(a))
r(u_) = Cosh(q*u)^-a
h(u_) = -(1/q) Integrate(Cosh(q*u)^(-a - 1), u)
m(u_, v_) := r(u) *Cos(v)
k(u_, v_) := r(u)* Sin(v)
FSurface(u_, v_) := {m(u, v), k(u, v), h(u)} 
GGP = ParametricPlot3D(FSurface(u, v), {u, -2 , 2 }, {v, 0, 2 (Pi)}, 
  BoxRatios -> {3, 3, 3}, PlotPoints -> 50, MaxRecursion -> 0, 
  Mesh -> Full, MeshFunctions -> {#4 + #5 &, #4 - #5 &}, 
  Method -> "BoundaryOffset" -> False, PerformanceGoal -> "Quality")
GGPT := DeleteCases(GGP, _Polygon, (Infinity))
DiscretizeGraphics(GGPT)

My goal is to plot the surface and then get different meshes of it. Here’s the plot and mesh Mathematica generates.

Mesh Along iso-parameter lines

I would like a mesh on the surface that cuts this mesh diagonally. This mean we can just rotate the mesh by 45 degrees. When I do so using MeshFunctions -> {#4 + #5 &, #4 - #5 &}, I get the following:
Desired Mesh but with weird behavior around 0, where lines don't meet

The problem with this mesh is that the lines don’t meet around 0. Using Mesh -> 50 or any number doesn’t fix it because the problem persists and it creates point that aren’t vertices.

ugly mesh

This can be fixed using Mesh -> All. However, when I do so, DiscretizeGraphics doesn’t work.

A method that I found that generates a good mesh is using Mesh -> Full. It creates a mesh where all the points are vertices as bellow.

nice mesh where the only points are vertices

Basically, I want to DiscretizeGraphics of a mesh which has points only on the vertices. I wish i can use Mesh -> Full and MeshFunctions -> {#4 + #5 &, #4 - #5 &} together and then discretized graphics but they seem to negate each other.

Thank you in advanced for your help

Full" Disables MeshFunction in ParametricPlot3D" />

8 – Current page link is not adding in my custom theme full pager links

I have created a view page showing products with full pager and full pager links are showing currently but current page link is not been added in the pagination links and because of this pagination links are showing home page and adding the parameters to home page links.
I have checked using Bartik Theme and other Contributed Themes available on drupal.org and full pager is working correctly as it should be(by adding current page links in the pager links) but it is not working only in custom theme.
I request, please help me with this as, I am beginner with Drupal and full pager is needed in almost all the projects.

Note: I am also using better exposed filters with exposed block.

Pager Links same in other themes also

Current page link is not adding in pager links in other themes current page link not showing in html but it is being added after page load

icloud – system storage full after migrating to new iPhone, old phone has plenty of free storage

I have an iPhone 11 128GB with around 30GB of used storage.
Most of the photos are uploaded up into 200GB iCloud which is full at the moment.

I got an iPhone 12 and transferred data & settings over from iPhone 11, device to device as described here https://support.apple.com/en-us/HT210216. The transfer itself took around ~30min.

What I ended up with, is an iPhone 12 with 122GB of storage is use, photo library taking around 90GB of it. My assumption is that for whatever reason a LOT of the photos from iCloud got stored locally on iPhone 12. The phones have same amount of photos in the libraries.

My questions:

  1. how can I get rid of the photos that that are currently LOCAL on iPhone 12, while they are living in the iCloud (uploaded from iPhone 11).
  2. iPhone 11 128GB has ~90GB of free space, iCloud somehow decided it still needs to upload the photos into the cloud, filling it up completely and making my phone backups impossible. Is there a way “back” to fix this?

Thank you

permissions – Full control, Limited Access given through a group where the user does not exist?

I have a SharePoint site where, when searching for a user at site level (using check permissions) it comes back saying the user has “Full control, limited access – Given through the ‘Site Name’ Owners Group.

However, the user is not an Owner of the site and when I click into the Owners group, they are not listed in there either.

How is this user being provided with access at site level from the specified group when they don’t appear to be in that group and how would I go about visualising and removing these user permissions?

I should add that when I click the “There are limited access users on this site. Users may have limited access if an item or document under the site has been shared with them. Show users”. It doesn’t show any additional users, but instead replaces ‘Full Control’ with ‘Full Control, Limited Access’ against the Site Owners group.

WordPress Full Responsive Website for $30

WordPress Full Responsive Website

I will design, revamp/redesign, customize or develop a modern, creative & responsive WordPress website for your business/blog.

Thank you so much for visiting my GIG. Are you looking for a WordPress Expert to design your Website? I am specialized in modern results-driven WordPress websites. After working on successful projects with 100% client’s satisfaction, I have earned a lot of experience in WordPress.

Includes

– Modern website

– Responsive

– Loads Fast

– Call to Action Buttons

– Contact Forms

– Social Media Integration

– Site submitted to search engines

– Modern Logo

So, Are you Ready? Price and time depend on pages content complexity and functionality.

.

8 – Menu link Converting full URL to local

When I save a menu link pointing to a node (nid 5, alias /woohoo/magic/test, it’s value in the database is: entity:node/5

I’m trying to convert fully formed user inputs such as “http://127.0.0.1:42080/woohoo/magic/test” to the path stored in menu in the databse.

I’ve tried the following:

$local_path = url::fromUserInput($possibly_local_path);

// $local_path->getRouteName() returns "entity.node.canonical"
// $local_path->toString() returns "/woohoo/magic/test"
// $local_path->getInternalPath() returns "node/5"

Please note I can’t just do string concatenations. I don’t always know that the path is to an entity, such as when I am using group module group content entities.

Any ideas?