Inserte Registros Usando AA Web API Usando HttpClient en SQL Server

Introducción

WEB API es la mejor opción para crear un servicio orientado a recursos mediante HTTP/Restful y funciona bien con aplicaciones basadas en MVC. Para más detalles visita mi enlace.

Descripción

En esta sesión, le mostraré cómo insertar registros usando AA Web API usando HttpClient para publicar datos en SQL Server. En esta sesión, puede ver las operaciones de obtención y publicación de la API web. De otra manera, puedo decir que insertaremos y recuperaremos registros usando un evento de clic de botón.

Antes de pasar por esta sesión, visite mi sesión anterior.

Pasos a seguir,

Paso 1

Agregue una nueva acción a HomeController (en la aplicación de cliente MVC) para obtener una vista de Obtener datos mediante el cliente HTTP.

Referencia del código

public ActionResult Part4()   
        {  
            List<Employee> list = new List<Employee>();  
            HttpClient client = new HttpClient();  
            var result = client.GetAsync("http://localhost:47250/api/satya").Result;  
            if (result.IsSuccessStatusCode)  
            {  
                list = result.Content.ReadAsAsync<List<Employee>>().Result;  
                ViewBag.userdetails = list;  
            }  
            return View();  
        } 

Código Descripción


 

Durante la carga inicial de la página, se mostrarán los datos de la tabla, lo que significa que los datos se vincularán en la tabla con controles de entrada utilizando HttpClient. Este método de acción del controlador con [HttpGet].

Paso 2

Usando la misma acción para HomeController (en la aplicación MVC Client) para publicar datos usando HTTP Client.

Referencia del código

[HttpPost]  
    public ActionResult Part4(Employee emp)   
    {  
        if (ModelState.IsValid)  
        {  
            HttpClient client = new HttpClient();  
            var result = client.PostAsJsonAsync("http://localhost:47250/api/satya", emp).Result;  
            if (result.IsSuccessStatusCode)  
            {  
                emp = result.Content.ReadAsAsync<Employee>().Result;  
                ViewBag.Result = "Data Is Successfully Saved!";  
                List<Employee> list = new List<Employee>();  
                HttpClient client1 = new HttpClient();  
                var result1 = client1.GetAsync("http://localhost:47250/api/satya").Result;  
                if (result1.IsSuccessStatusCode)  
                {  
                    list = result1.Content.ReadAsAsync<List<Employee>>().Result;  
                    ViewBag.userdetails = list;  
                }  
                ModelState.Clear();  
                return View(new Employee());  
            }  
            else  
            {  
                ViewBag.Result = "Error! Please try with valid data.";  
            }  
        }  
        return View(emp);  
    } 

Código Descripción

En esta parte, después del método de publicación de formulario o del evento de clic de botón, se mostrarán datos de inserción y tablas. En la sección de publicación lateral, agregué algo para la recuperación de datos; de lo contrario, obtendrá un error sobre la referencia del objeto que no se establece en una instancia de un objeto. Describiré este problema en la sección Ver en Nota.

  1. Lista<Empleado> lista =  new  Lista<Empleado>();
                    HttpClient client1 = new HttpClient();  
                    var result1 = client1.GetAsync("http://localhost:47250/api/satya").Result;  
                    if (result1.IsSuccessStatusCode)  
                    {  
                        list = result1.Content.ReadAsAsync<List<Employee>>().Result;  
                        ViewBag.userdetails = list;  
                    } 

Objeto de diccionario de estado del modelo que contiene el estado del modelo y de la validación del enlace del modelo, elimina todos los elementos del diccionario de estado del modelo.

ModelState.Clear(); 

Paso 3

Haga clic con el botón derecho en Método de acción (aquí, haga clic con el botón derecho en el formulario Part4()) > Agregar vista... > Marque "Crear vista fuertemente tipada" > Seleccione Clase de modelo >> Agregar. Aquí Model Class es "Empleado (Entidades)".

 

Referencia del código

@model Entities.Employee  
  
@{  
    ViewBag.Title = "Satyaprakash - Post data to Web API using HTTPClient (in MVC client application) With Validation";  
}  
  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">  
  
</script>  
  
<style>  
    span.field-validation-error {  
        color: red;  
    }  
  
    table {  
        font-family: arial, sans-serif;  
        border-collapse: collapse;  
        width: 100%;  
    }  
  
    td, th {  
        border: 1px solid #dddddd;  
        text-align: left;  
        padding: 8px;  
    }  
  
    tr:nth-child(even) {  
        background-color: #dddddd;  
    }  
  
    .button {  
        background-color: #4CAF50;  
        border: none;  
        color: white;  
        padding: 15px 32px;  
        text-align: center;  
        text-decoration: none;  
        display: inline-block;  
        font-size: 16px;  
        margin: 4px 2px;  
        cursor: pointer;  
    }  
  
    .button4 {  
        border-radius: 9px;  
    }  
</style>  
  
  
<div style="padding:10px ; align-content:center">  
    <fieldset>  
        <legend style="font-family:Arial Black;color:blue">Post data to Web API using HTTPClient (in MVC client application) With Validation</legend>  
    </fieldset>  
</div>  
  
  
<div style="max-width:600px;">  
    @using (Html.BeginForm("Part4", "Home", FormMethod.Post, new { role = "form" }))  
    {  
        @Html.ValidationSummary(true)  
  
        <div class="form-group">  
            @Html.LabelFor(a => a.FirstName)  
            @Html.TextBoxFor(a => a.FirstName, new { @class = "form-control" })  
            @Html.ValidationMessageFor(a => a.FirstName)  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(a => a.LastName)  
            @Html.TextBoxFor(a => a.LastName, new { @class = "form-control" })  
            @Html.ValidationMessageFor(a => a.LastName)  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(a => a.EmailID)  
            @Html.TextBoxFor(a => a.EmailID, new { @class = "form-control" })  
            @Html.ValidationMessageFor(a => a.EmailID)  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(a => a.City)  
            @Html.TextBoxFor(a => a.City, new { @class = "form-control" })  
            @Html.ValidationMessageFor(a => a.City)  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(a => a.Country)  
            @Html.TextBoxFor(a => a.Country, new { @class = "form-control" })  
            @Html.ValidationMessageFor(a => a.Country)  
        </div>  
        <input id="btn" type="submit" value="Create" class="button button4" />  
  
        <div style="width:90%; padding:10px; margin:0 auto;">  
            @if (ViewBag.Result != null)  
            {  
                @*<div style="color:red">@ViewBag.Result</div>*@  
  
                <script>  
                    $(document).ready(function () {  
                        $('#btn').click(function () {  
                            $('#tableshow').hide();  
                        });  
  
                        bootbox.alert('@ViewBag.Result');  
                        $('#tableshow').show();  
                    });  
                </script>  
            }  
        </div>  
    }  
</div>  
  
@*System.NullReferenceException , Object reference not set to an instance of an object. This error due to without added for data retrieve comment line code in Part4() in homecontroller in webapplication*@  
<div id="tableshow" style="width:90%; padding:10px; margin:0 auto;">  
    <table class="table table-responsive table-striped table-bordered">  
        <thead>  
            <tr>  
                <th style="background-color: Yellow;color: blue">Full Name</th>  
                <th style="background-color: Yellow;color: blue">Email</th>  
                <th style="background-color: Yellow;color: blue">City</th>  
                <th style="background-color: Yellow;color: blue">Country</th>  
            </tr>  
        </thead>  
        <tbody>  
            @foreach (var i in ViewBag.userdetails)   
            {  
                <tr>  
                    <td>@i.FirstName @i.LastName</td>  
                    <td>@i.EmailID</td>  
                    <td>@i.City</td>  
                    <td>@i.Country</td>  
                </tr>  
            }  
        </tbody>  
    </table>  
</div>  
@*System.NullReferenceException , Object reference not set to an instance of an object.*@  
  
@section Scripts{  
    @Scripts.Render("~/bundles/jqueryval")  
} 

Código Descripción

En esta sección de código dentro del método de publicación de formulario, se agregó una secuencia de comandos para que durante el clic del botón se muestren los datos de la tabla de eventos.

<div style="width:90%; padding:10px; margin:0 auto;">  
            @if (ViewBag.Result != null)  
            {  
                @*<div style="color:red">@ViewBag.Result</div>*@  
  
                <script>  
                    $(document).ready(function () {  
                        $('#btn').click(function () {  
                            $('#tableshow').hide();  
                        });  
  
                        bootbox.alert('@ViewBag.Result');  
                        $('#tableshow').show();  
                    });  
                </script>  
            }  
        </div> 

Aquí usé la biblioteca de bootbox para mostrar la notificación de alerta. ViewBag.Result contiene un mensaje en el método de acción del controlador.

bootbox.alert('@ViewBag.Result'); 

Nota 

Durante esta sesión, tuve un problema con System.NullReferenceException, la referencia del objeto no está configurada como una instancia de un objeto.

Por lo tanto, creé una identificación div y la puse dentro de la sección de script como se describe en el método de publicación del método de acción del controlador Part4(). Este error se debió a la falta de datos agregados para el código de línea de comentario de recuperación de datos en Part4() en homecontroller en la aplicación cliente MVC.

<div id="tableshow" style="width:90%; padding:10px; margin:0 auto;">  
    <table class="table table-responsive table-striped table-bordered">  
        <thead>  
            <tr>  
                <th style="background-color: Yellow;color: blue">Full Name</th>  
                <th style="background-color: Yellow;color: blue">Email</th>  
                <th style="background-color: Yellow;color: blue">City</th>  
                <th style="background-color: Yellow;color: blue">Country</th>  
            </tr>  
        </thead>  
        <tbody>  
            @foreach (var i in ViewBag.userdetails)   
            {  
                <tr>  
                    <td>@i.FirstName @i.LastName</td>  
                    <td>@i.EmailID</td>  
                    <td>@i.City</td>  
                    <td>@i.Country</td>  
                </tr>  
            }  
        </tbody>  
    </table>  
</div> 

PRODUCCIÓN

Durante el evento de carga de la página.

 

Soporte de vista móvil.

 

Imagen gif para una mejor comprensión de la salida.

 

Verifique el servidor sql para insertar registros como se muestra en la imagen de arriba.

 

Enlace al código fuente

RESUMEN

  • Obtenga y publique datos con validación de control de formulario utilizando HTTP Client.
     
  • Biblioteca javascript de Bootbox para mensajes de alerta.
  • Soporte de respuesta móvil.

Partes anteriores -

Parte 1: API web ASP.NET usando MVC y Entity Framework

Parte 2: ASP.NET Web API usando MVC, Entity Framework y jQuery para recuperar datos 

Parte 3: reutilice las clases de modelo del modelo de datos de entidad (.edmx) para múltiples proyectos usando la biblioteca de clases en ASP.NET Web API

Parte 4 - 

ASP.NET Web API usando MVC, Entity Framework y HttpClient para recuperar datos

Parte 5: ASP.NET Web API usando MVC, Entity Framework y jQuery para obtener y publicar con validación  

Fuente: https://www.c-sharpcorner.com/article/asp-net-web-api-using-mvc-entity-framework-and-httpclient-for-get-and-post-with/

#aspdotnet #mvc #entity-framework 

What is GEEK

Buddha Community

Inserte Registros Usando AA Web API Usando HttpClient en SQL Server
Cayla  Erdman

Cayla Erdman

1594369800

Introduction to Structured Query Language SQL pdf

SQL stands for Structured Query Language. SQL is a scripting language expected to store, control, and inquiry information put away in social databases. The main manifestation of SQL showed up in 1974, when a gathering in IBM built up the principal model of a social database. The primary business social database was discharged by Relational Software later turning out to be Oracle.

Models for SQL exist. In any case, the SQL that can be utilized on every last one of the major RDBMS today is in various flavors. This is because of two reasons:

1. The SQL order standard is genuinely intricate, and it isn’t handy to actualize the whole standard.

2. Every database seller needs an approach to separate its item from others.

Right now, contrasts are noted where fitting.

#programming books #beginning sql pdf #commands sql #download free sql full book pdf #introduction to sql pdf #introduction to sql ppt #introduction to sql #practical sql pdf #sql commands pdf with examples free download #sql commands #sql free bool download #sql guide #sql language #sql pdf #sql ppt #sql programming language #sql tutorial for beginners #sql tutorial pdf #sql #structured query language pdf #structured query language ppt #structured query language

Ray  Patel

Ray Patel

1625843760

Python Packages in SQL Server – Get Started with SQL Server Machine Learning Services

Introduction

When installing Machine Learning Services in SQL Server by default few Python Packages are installed. In this article, we will have a look on how to get those installed python package information.

Python Packages

When we choose Python as Machine Learning Service during installation, the following packages are installed in SQL Server,

  • revoscalepy – This Microsoft Python package is used for remote compute contexts, streaming, parallel execution of rx functions for data import and transformation, modeling, visualization, and analysis.
  • microsoftml – This is another Microsoft Python package which adds machine learning algorithms in Python.
  • Anaconda 4.2 – Anaconda is an opensource Python package

#machine learning #sql server #executing python in sql server #machine learning using python #machine learning with sql server #ml in sql server using python #python in sql server ml #python packages #python packages for machine learning services #sql server machine learning services

Brain  Crist

Brain Crist

1600347600

SCHEMAS in SQL Server -MS SQL Server – Zero to Hero Query Master

Introduction

This is part 3 of “MS SQL Server- Zero to Hero” and in this article, we will be discussing about the SCHEMAS in SQL SERVER. Before getting into this article, please consider to visit previous articles in this series from below,

A glimpse of previous articles
Part 1

In part one, we learned the basics of data, database, database management system, and types of DBMS and SQL.

Part 2
  • We learned to create a database and maintain it using SQL statements.
  • Best practice methods were also mentioned.

#sql server #benefits of schemas #create schema in sql #database schemas #how to create schema in sql server #schemas #schemas in sql server #sql server schemas #what is schema in sql server

Cayla  Erdman

Cayla Erdman

1596441660

Welcome Back the T-SQL Debugger with SQL Complete – SQL Debugger

When you develop large chunks of T-SQL code with the help of the SQL Server Management Studio tool, it is essential to test the “Live” behavior of your code by making sure that each small piece of code works fine and being able to allocate any error message that may cause a failure within that code.

The easiest way to perform that would be to use the T-SQL debugger feature, which used to be built-in over the SQL Server Management Studio tool. But since the T-SQL debugger feature was removed completely from SQL Server Management Studio 18 and later editions, we need a replacement for that feature. This is because we cannot keep using the old versions of SSMS just to support the T-SQL Debugger feature without “enjoying” the new features and bug fixes that are released in the new SSMS versions.

If you plan to wait for SSMS to bring back the T-SQL Debugger feature, vote in the Put Debugger back into SSMS 18 to ask Microsoft to reintroduce it.

As for me, I searched for an alternative tool for a T-SQL Debugger SSMS built-in feature and found that Devart company rolled out a new T-SQL Debugger feature to version 6.4 of SQL – Complete tool. SQL Complete is an add-in for Visual Studio and SSMS that offers scripts autocompletion capabilities, which help develop and debug your SQL database project.

The SQL Debugger feature of SQL Complete allows you to check the execution of your scripts, procedures, functions, and triggers step by step by adding breakpoints to the lines where you plan to start, suspend, evaluate, step through, and then to continue the execution of your script.

You can download SQL Complete from the dbForge Download page and install it on your machine using a straight-forward installation wizard. The wizard will ask you to specify the installation path for the SQL Complete tool and the versions of SSMS and Visual Studio that you plan to install the SQL Complete on, as an add-in, from the versions that are installed on your machine, as shown below:

Once SQL Complete is fully installed on your machine, the dbForge SQL Complete installation wizard will notify you of whether the installation was completed successfully or the wizard faced any specific issue that you can troubleshoot and fix easily. If there are no issues, the wizard will provide you with an option to open the SSMS tool and start using the SQL Complete tool, as displayed below:

When you open SSMS, you will see a new “Debug” tools menu, under which you can navigate the SQL Debugger feature options. Besides, you will see a list of icons that will be used to control the debug mode of the T-SQL query at the leftmost side of the SSMS tool. If you cannot see the list, you can go to View -> Toolbars -> Debugger to make these icons visible.

During the debugging session, the SQL Debugger icons will be as follows:

The functionality of these icons within the SQL Debugger can be summarized as:

  • Adding Breakpoints to control the execution pause of the T-SQL script at a specific statement allows you to check the debugging information of the T-SQL statements such as the values for the parameters and the variables.
  • Step Into is “navigate” through the script statements one by one, allowing you to check how each statement behaves.
  • Step Over is “execute” a specific stored procedure if you are sure that it contains no error.
  • Step Out is “return” from the stored procedure, function, or trigger to the main debugging window.
  • Continue executing the script until reaching the next breakpoint.
  • Stop Debugging is “terminate” the debugging session.
  • Restart “stop and start” the current debugging session.

#sql server #sql #sql debugger #sql server #sql server stored procedure #ssms #t-sql queries

Karlee  Will

Karlee Will

1620516240

Key Differences between SQL Server 2019 for Windows and Linux

Since the release of SQL Server 2017 for Linux, Microsoft has pretty much changed the entire game. It enabled a whole new world of possibilities for their famous relational database, offering what was only available in the Windows space until then.

I know that a purist DBA would tell me right away that the out of the box SQL Server 2019 Linux version has several differences, in terms of features, in regards to its Windows counterpart, such as:

  • No SQL Server Agent
  • No FileStream
  • No System Extended Stored Procedures (e.g. xp_cmdshell)

However, I got curious enough to think “what if they can be compared, at least to some extent, against things that both can do?” So, I pulled the trigger on a couple of VMs, prepared some simple tests, and collected data to present to you. Let’s see how things turn out!

#sql server #sql server 2019 #sql server linux #sql server windows #sql