c# – Logging to database in ASP.NET Core Entity Framework Core application

I have an ASP.NET Core Entity Framework Core application and I want to implement my own custom logger. I don’t want to use ready solutions like NLog or Serilog.

I added a new class library project (“Logger”) to my application and added classes that do the logging. Mostly they call the service provider to get the db context and add a log object to it and then save changes.

The problem is that my db context is located in another project of type class library (“Data”), so “Logger” references “Data” in order to use the db context class. However to be able to save logs in the database I also need the db context to have a db set of type “Log”, which would mean a circular dependency.

How do I remedy this situation?

Upload/Download de arquivos grandes com ASP.NET Core 2.2

Preciso realizar uploads e downlods de arquivos acima de 2GB usando ASP.NET Core 2.2, mas não sei qual a melhor forma de fazer isso. Para o download, to usando o seguinte método:

(HttpGet("id"))
public IActionResult Download(Guid id)
{
    // Recupero o caminho físico do arquivo com base no id aqui
    return PhysicalFile(path, MimeTypes.GetMimeType(path), Path.GetFileName(path));
}

Aparentemente funciona normal, mas tenho dúvidas quanto ao desempenho ou requisições paralelas. Existe uma abordagem melhor para fazer isso?

Já no upload eu pensei em separar o arquivo em pedaços no lado do cliente e enviar esses pedaços em várias requisições. No lado do servidor eu receberia cada pedaço, gravaria no final do arquivo e enviaria uma resposta para que fosse enviado um novo pedaço. Mas… Essa é realmente uma boa forma de fazer isso? Acho que poderei ter problemas de concorrência ao abrir/fechar o arquivo na hora escrita.

Qual a forma apropriada de realizar downloads/uploads?

asp.net – Insert selected Image into databse

I want to insert selected image into database

 public void BindImages()
    {
        try
        {
            string query = "select * from Images where Prod_id=@Id";
            SqlCommand cmd = new SqlCommand(query, EcomConString);
            cmd.Parameters.AddWithValue("@Id", SqlDbType.VarChar).Value = id;
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    strImages += @"<li>
                        <img src="https://webmasters.stackexchange.com/" + dr("Img") + @"'  class='img-thumbnail' alt=''  />
                    </li>";
                    strThumbImage += dr("Img").ToString() + ",";
                }
            }
        }
        catch (Exception ex)
        {

        }
    } 

asp.net – JQuery autocomplete não funciona no Chrome

criei uma pagina aspx (sim, asp.net, sistema antigo) para fazer um campo texto com autocomplete. O problema é que somente no Chrome ele não seta o valor selecionado, alguém tem uma ideia do que possa ser?

Segue o código aspx:

<script src="https://pt.stackoverflow.com/Scripts/jquery-3.5.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.12.1.min.js" type="text/javascript"></script>
<link href="Scripts/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        $("#txtProcurar").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Consulta.aspx/GetClientes") %>',
                    data: "{ 'prefixo': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')(0),
                                val: item.split('-')(1)
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            minLength: 1,
            select: function (e, i) {
                alert('AQUI');
                $("(id$=hfCustomerId)").val(i.item.val);
                $("(id$=txtProcurar)").val(item.label);
            }
        });
    });
</script>

Agora o .vb:

    (WebMethod)
    public static string() GetClientes(string prefixo)
    {
        List<string> clientes = new List<string>();

        clientes.Add(string.Format("{0}-{1}", "ContactName1", 1));
        clientes.Add(string.Format("{0}-{1}", "ContactName2", 2));
        clientes.Add(string.Format("{0}-{1}", "ContactName3", 3));
        clientes.Add(string.Format("{0}-{1}", "ContactName4", 4));
        clientes.Add(string.Format("{0}-{1}", "ContactName5", 5));

        return clientes.ToArray();
    }

javascript – Como duplicar ou clonar uma DIV em Java Script e ler todos os elementos em ASP.NET C#

Olá,

Tenho um formulário de convidados que preciso aumentar automaticamente os campos de acordo com o preenchimento.

O código é:

<div class="form-row" id="Guests">
<p><strong>Guests Forms</strong></p>
<div id="guest1">

    <div class="form-group col-md-3">
        <label for="labelGuestNumber" class="col-sm-1 col-form-label">1.</label>
        <label for="labelGuesName1" class="col-sm-2 col-form-label">Name: </label>
        <div class="col-sm-8" style="margin-left: 5px;">
            <input runat="server" class="form-control" id="inputGuestName1" placeholder="Guest Name" required>
        </div>
    </div>
    <div class="form-group col-md-4" style="margin-left: -40px;">
        <label for="labelCPFCNPJGuest1" class="col-sm-3 col-form-label" >CPF/CNPJ:</label>
        <div class="col-sm-7">
            <input runat="server" class="form-control" id="inputCPFCNPJGuest1" placeholder="CPF / CNPJ" onChange="newGuest()" required>
        </div>
    </div>
</div>

Ou seja, toda vez que preencher o CPF/CNPJ ele pode abrir mais uma linha para preencher outro convidado. Quando enviar esse formulário, preciso que seja lido em ASP.NET C# para ser inserido no banco de dados.

Não tenho ideia de como resolver.

javascript – Tengo problemas al grabar un archivo de imagen en servidor asp.net

Tengo una aplicación web que necesita grabar una foto tomada desde una tablet. El javascript funciona bien hasta tomar la foto, pero al enviarla al servidor utilizando ajax se va por la opción de error y me dice que hay un “parseerror”.

El javacript funciona bien hasta el $ajax. Cuando entra a ejecutar esta parte se va por la parte de error. El error me dice que el JSON tiene un error de formato en la linea 3 columna 1.

Aquí adjunto el código de lo que estoy haciendo:

    var width = 320;
    var height = 0;
    var dispositivos = ();
    var streaming = false;
    var video = null;
    var canvas = null;
    var photo = null;
    var startbutton = null;
    var videoSelect = null;
    var contador = 0;

    video = document.getElementById('video');
    canvas = document.getElementById('canvas');
    photo = document.getElementById('photo');
    startbutton = document.getElementById('startbutton');
    videoSelect = document.getElementById('select_video');

    video.addEventListener('canplay', function (ev) {
       if (!streaming) {
           height = video.videoHeight / (video.videoWidth / width);

           if (isNaN(height)) {
              height = width / (4 / 3);
           }

           video.setAttribute('width', width);
           video.setAttribute('height', height);
           canvas.setAttribute('width', width);
           canvas.setAttribute('height', height);
           streaming = true;
      }
   }, false);

   startbutton.addEventListener('click', function (ev) {
       takepicture();
       ev.preventDefault();
   }, false);

   clearphoto();

   function clearphoto() {
        var context = canvas.getContext('2d');
        context.fillStyle = "#AAA";
        context.fillRect(0, 0, canvas.width, canvas.height);
        var data = canvas.toDataURL('image/png');
        photo.setAttribute('src', data);
   }

   function takepicture() {
         var context = canvas.getContext('2d');
         if (width && height) {
            canvas.width = width;
            canvas.height = height;
            context.drawImage(video, 0, 0, width, height);
            var imagen = canvas.toDataURL('image/png');
            var data = canvas.toDataURL();
            data = data.replace('data:image/png;base64,', '');
            photo.setAttribute('src', imagen);
            $.ajax({
                type: "POST",
                url: "video.aspx/GrabaFoto",
                data: '{"data" : "' + data + '"}',
                dataType: "json",
                contentType: 'aplication/json; charset=utf-8',
                success: function (respuesta) {
                      //alert('Imagen grabada en el disco');
                      console.log(respuesta);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                      alert("Status: " + textStatus);
                      alert("Error: " + errorThrown);
                }
          });
          } else {
                clearphoto()
          }
      }

   $(document).ready(function () {
       $("button.cargar").click(function () {
           navigator.mediaDevices.enumerateDevices().then(function (devices) {
               for (var i = 0; i !== devices.length; ++i) {
                   if (devices(i).kind === 'videoinput') {
                       dispositivos.push(devices(i));
                    };
               };
               if (dispositivos.length > 0) {
                   for (var i = 0; i !== dispositivos.length; ++i) {
                       const option = document.createElement('option');
                       option.value = dispositivos(i).deviceId;
                       option.text = dispositivos(i).label;
                   };
               };
                const camera = dispositivos(dispositivos.length - 1);
                navigator.mediaDevices.getUserMedia({
                video: {
                     deviceId: camera.deviceId,
                     facingMode: ('user', 'environment'),
                     height: { ideal: 1080 },
                     width: { ideal: 1920 }
                }
               }).then(function (stream) {
                  video.srcObject = stream;
                  video.play();
               })
          });
      });
    });

El codigo HTML es el siguiente:

   <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Fotos.aspx.cs" 
       Inherits="TomarFoto.Fotos" %>

   <!DOCTYPE html>

   <html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
   </head>
   <body>
        <section class="content">

             <div class="row">
             <div class="col-md-6">
                  <video id="video">Video no habilitado</video>
                  <button class="cargar" type="button">Reproducir video</button>
                  <canvas id="canvas"></canvas>
             </div>
                <div class="col-md-6">
                    <img id="photo" alt="La pantalla capturada aparecerá aquí">
                    <button class="btn btn-primary" id="startbutton">Tomar Foto</button>
                </div>

             </div>
       </section>
       <script type="text/javascript" src="https://es.stackoverflow.com/js/jquery-3.3.1.min.js"></script>
       <script src="script.js"></script>
   </body>
   </html>

asp.net – Publish a dynamic form on sharepoint

I have to create a form (a request for adding a new user to our active directory) and publish it on the share point.
At first I tought, that I could do this using Microsoft Forms, but it is not complex enough.
There Should be a DropDown control and depending on the selected item (company name) the next DropDown contorl (occupation) should offer specific items. At the end the form should be send by mail to our helpdesk.

My question is, which tool should I use to build the form?
Could you recommend me something? I am new to sharepoint, and I am not sure if I can use PHP or ASP.net?
And I am not sure if this is economically usefull for a simple form.
Maybe there is something lile Microsoft Forms, just a little bit more complex.
Thank you!

architecture – Separation of concerns and other best practices between controllers, services, suppliers and stores in ASP.NET when creating a REST Web API

I have traditionally been a developer of desktop applications, but circumstances have driven me to make the web client and the corresponding REST API logic for a project in which I am involved. Unfortunately, I am a one-man show, so my opportunities to learn new models or techniques from colleagues are somewhat limited. When I was ramping up, I had the opportunity to work (briefly) with an entrepreneur who exposed me to the idea that my server REST logic should be separated into one Controller (where the actual GET / PUT / POST / DELETE methods live) and a A service who does most of the work. As I was told, the A service could still interact with one or more Suppliers or Stores.

My understanding is that a Provider would encapsulate the logic that interacts with another system, maybe another web API, or a little weird legacy code, or maybe a little bit of proprietary hardware (like a temperature gauge, for example). In addition, a Shop would pack CRUD logic for real data objects in SQL, NoSQL, text files, whatever.

Assuming all of this makes sense, and this is actually the way the pros do it, he further advised me to incorporate the denomination into my lessons, like this:

PizzaController can proxy received web API calls to the PizzaService, who in turn could speak to both PizzaProvider and the RefridgeratorStore.

I'm not 100% positive, that's how the real world does things – but it made enough sense for me to appear believable and I have generally adopted this model and up to now it has worked well enough to organize my logic.

But this is where some questions arise:

First, is this vision of class separation really the way others structure their code? And if I am close, but not quite, what corrections should I make?

Second, is it legitimate for a A service to instance and take advantage of a second A service? For example, if my PizzaService must decide if we want delivery or if we're going to make pizza from scratch – he may want to invoke the PizzaProvider -or- he might just want to defer to the PizzaMakerService. If the PizzaService does not make this decision, so the logic of decision should live earlier in the food chain (no pun intended). It would infer my PizzaController will have to decide whether to use the PizzaService -or there PizzaMakerService; and it doesn't feel right to me.

And finally, (following the model that was shown to me) my Services frequently return a data object to my Controller, where the Controller will map one or more properties to a ViewModel who returned to my client. I discovered that I could just as easily map the relevant data bits into an anonymous object (C #) on the fly and return it to my client. The JSON returned is the same, so why introduce the class definition for a ViewModel at all? Is there a taboo against creating an anonymous object in the Controller and return it?

I realize (in my situation) that I can pretty much do whatever I want – how I name the classes, how I separate the logic, if I use anonymous objects – it's really entirely my code. But these questions have been pestering me for quite some time and I would like to make things as close as possible to "properly". It is likely that these questions (or a variation) have been asked and answered before, so I apologize now for any duplication – but for the life of me, I can't seem to find direct answers.

Thank you!

sql – I have my system on asp.net 3.1 I have a connection to the database in SqlServer but I have to query the data from a database in Oracle

I need to list data from a database in Oracle with Asp.Net 3.1, currently I have connected it to a database in SQLServer, how could I do that so that both databases can run on the same system. I don't know how to connect it, i need to connect it first and then list what i need from oracle

asp.net – Why does my webapp only serve the css file when it is run as iis express?

So I have this web application which works great when I debug it with IIS Express, it uses the correct CSS files and what is not.

But if I try to run it as a project exe, it doesn't seem to find this way


And I’m my startup.cs I’m using

app.UseStaticFiles();

When i run the executable inside

binDebugnetcoreapp3.1

Then should i change this path href="https://stackoverflow.com/~/assets/css/dark_theme.css" to something else?