pu

Buscar este blog

lunes, 20 de septiembre de 2021

Top 50 Asp.Net Web API Interview Questions & Answers (2021)

 1) What is Web API?

WebAPI is a framework which helps you to build/develop HTTP services.


2) Why is Web API required? Is it possible to use RESTful services using WCF?

Yes, we can still develop RESTful services with WCF. However, there are two main reasons that prompt users to use Web API instead of RESTful services.

  • Web API increases TDD (Test Data Driven) approach in the development of RESTful services.
  • If we want to develop RESTful services in WCF, you surely need a lot of config settings, URI templates, contracts & endpoints for developing RESTful services using web API.


3) Why select Web API?

  • It is used to create simple, non-SOAP-based HTTP Services
  • It is also an easy method for creation with Web API. With WCF REST Services
  • It is based on HTTP and easy to define, expose and consume in a REST-ful way.
  • It is lightweight architecture and ideal for devices that have limited bandwidth like smartphones.


4) Is it right that ASP.NET Web API has replaced WCF?

It’s a not at all true that ASP.NET Web API has replaced WCF. In fact, it is another way of building non-SOAP based services, i.e., plain XML or JSON string.


5) What are the advantages of Web API?

Advantages of Web API are:

  • OData
  • Filters
  • Content Negotiation
  • Self-Hosting
  • Routing
  • Model Bindings

Asp.Net Web API Interview Questions


6) What are main return types supported in Web API?

A Web API controller action can return following values:

  • Void – It will return empty content
  • HttpResponseMessage – It will convert the response to an HTTP message.
  • IHttpActionResult – internally calls ExecuteAsync to create an HttpResponseMessage
  • Other types – You can write the serialized return value into the response body


7) Web API supports which protocol?

Web App supports HTTP protocol.


8) Which .NET framework supports Web API?

NET 4.0 and above version supports web API.


9) Web API uses which of the following open-source library for JSON serialization?

Web API uses Json.NET library for JSON serialization.


10) By default, Web API sends HTTP response with which of the following status code for all uncaught exception?

500 – Internal Server Error


11) What is the biggest disadvantage of “Other Return Types” in Web API?

The biggest disadvantage of this approach is that you cannot directly return an error code like 404 error.



12) How do you construct HtmlResponseMessage?

Following is the way to construct to do so,

public class TestController : ApiController

{

public HttpResponseMessage Get()

{

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");

response.Content = new StringContent("Testing", Encoding.Unicode);

response.Headers.CacheControl = new CacheControlHeaderValue()

{

MaxAge = TimeSpan.FromMinutes(20)

};

return response;

}

}


13) What is Web API Routing?

Routing is pattern matching like in MVC.

All routes are registered in Route Tables.

For example:

Routes.MapHttpRoute(

Name: "ExampleWebAPIRoute",

routeTemplate: “api/{controller}/{id}

defaults: new { id = RouteParameter.Optional}


14) What is SOAP?

SOAP is an XML message format used in web service interactions. It allows to send messages over HTTP or JMS, but other transport protocols can be used. It is also an XML-based messaging protocol for exchanging information among computers.


15) What is the benefit of using REST in Web API?

REST is used to make fewer data transfers between client and server which make it an ideal for using it in mobile apps. Web API also supports HTTP protocol. Therefore, it reintroduces the traditional way of the HTTP verbs for communication.


16) How can we use Web API with ASP.NET Web Form?

Web API can be used with ASP.NET Web Form

It can be performed in three simple steps:

  1. Create a Web API Controller,
  2. Add a routing table to Application_Start method of Global.asax
  3. Then you need to make a jQuery AJAX Call to Web API method and get data.


17) How to you can limit Access to Web API to Specific HTTP Verb?

Attribute programming plays a important role. It is easy to restrict access to an ASP.NET Web API method to be called using a particular HTTP method.


18) Can you use Web API with ASP.NET Web Form?

Yes, It is possible to use Web API with ASP.Net web form. As it is bundled with ASP.NET MVC framework. However, it can be used with ASP.NET Web Form.


19) How Can assign alias name for ASP.NET Web API Action?

We can give alias name for Web API action same as in case of ASP.NET MVC by using “ActionName” attribute as follows:

[HttpPost]

[ActionName("SaveStudentInfo")]

public void UpdateStudent(Student aStudent)
{
StudentRepository.AddStudent(aStudent);
}

20) What is the meaning of TestApi?

TestApi is a utility library of APIs. Using this library tester developer can create testing tools and automated tests for a .NET application using data-structure and algorithms.


21) Explain exception filters?

It will be executed when exceptions are unhandled and thrown from a controller method. The reason for the exception can be anything. Exception filters will implement “IExceptionFilter” interface.


22) How can we register exception filter from the action?

We can register exception filter from action using following code:

[NotImplExceptionFilter]

public TestCustomer GetMyTestCustomer(int custid)

{

//write the code

}

23) How you can return View from ASP.NET Web API method?

No, we can’t return a view from ASP.NET Web API Method. Web API creates HTTP services that render raw data. However, it’s also possible in ASP.NET MVC application.


24) How to register exception filter globally?

It is possible to register exception filter globally using following code-

GlobalConfiguration.Configuration.Filters.Add(new

MyTestCustomerStore.NotImplExceptionFilterAttribute());


25) Explain what is REST and RESTFUL?

REST represents REpresentational State Transfer; it is entirely a new aspect of writing a web app.

RESTFUL: It is term written by applying REST architectural concepts is called RESTful services. It focuses on system resources and how the state of the resource should be transported over HTTP protocol.


26) Give me one example of Web API Routing?

Config.Routes.MapHttpRoute(

name: "MyRoute,"//route name

routeTemplate: "api/{controller}/{action}/{id}",//as you can see "API" is at the beginning.

defaults: new { id = RouteParameter.Optional }

);

27) How can you handle errors in Web API?

Several classes are available in Web API to handle errors. They are HttpError, Exception Filters, HttpResponseException, and Registering Exception Filters.


28) What New Features comes with ASP.NET Web API 2.0?

The latest features of ASP.NET Web API framework v2.0 are as follows:

  • Attribute Routing
  • Cross-Origin Resource Sharing
  • External Authentication
  • Open Web Interface NET
  • HttpActionResult
  • Web API OData


29) How can you restrict access methods to specific HTTP verbs in Web API?

With the help of Attributes (like HTTP verbs), It is possible to implement access restrictions in Web API.

It is possible to define HTTP verbs as an attribute to restrict access.

Example:

[HttpPost]

public void Method1(Class obj)

{

//logic


30) How can you pass multiple complex types in Web API?

Two methods to pass the complex types in Web API –

Using ArrayList and Newtonsoft array


31) Write a code for passing ArrayList in Web API?

ArrayList paramList = new ArrayList();

Category c = new Category { CategoryId = 1, CategoryName =“MobilePhones”};

Product p = new Product { Productcode = 1, Name = “MotoG”, Price = 15500, CategoryID = 1 };

paramList.Add(c);

paramList.Add(p);


32) Name the tools or API for developing or testing web api?

Testing tools for web services for REST APIs include:

  1. Jersey API
  2. CFX
  3. Axis
  4. Restlet


33) What is REST?

REST is architectural style. It has defined guidelines for creating services which are scalable. REST used with HTTP protocol using its verbs GET, PUT, POST and DELETE.


34) How to unit test Web API?

We can perform a Unit test using Web API tools like Fiddler.

Here, are some setting to be done if you are using

Fiddler –Compose Tab -> Enter Request Headers -> Enter the Request Body and execute


35) How can we restrict access to methods with specific HTTP verbs in Web API?

Attribute programming is widely used for this functionality. Web API also allows restricting access of calling methods with the help of specific HTTP verbs. It is also possible to define HTTP verbs as attribute over method.


36) What is the usage of DelegatingHandler?

DelegatingHandler is used in the Web API to represent Message Handlers before routing.


37) How can we register exception filter from the action?

We can register exception filter from action using following code

[NotImplExceptionFilter]

public TestCust GetMyTestCust (int custno)

{

//write the code

}

38) Tell me the code snippet to show how we can return 404 errors from HttpError?

Code for returning 404 error from HttpError

string message = string.Format(“TestCustomer id = {0} not found”, customerid);

return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);


39) Explain code snippet to register exception filters from controller?

[NotImplExceptionFilter]

public class TestCustController : Controller

{

//Your code goes here

}

40) Web API supports which protocol?

Web App support HTTP protocol


41) Which of the following .NET framework supports Web API?

Web API is supported by NET 4.0 version


42) Web API uses which library for JSON serialization?

Web API uses Json.NET library for JSON serialization.


43) By default, Web API sends HTTP response with which of the following status code for all uncaught exception?

500 – Internal Server Error


44) Explain method to handle error using HttpError in Web API?

In WEB API HttpError used to throw the error info in the response body. “CreateErrorResponse” method is can also use along with this, which is an extension method defined in “HttpRequestMessageExtension.”


45) How can we register exception filter globally?

We can register exception filter globally using following code:

GlobalConfiguration.Configuration.Filters.Add (new MyTestCustomerStore.NotImplExceptionFilterAttribute());

46) How to handle errors in Web API?

Several classes are available in Web API to handle errors. They are HttpError, HttpResponseException, Exception Filters, Registering Exception Filters.


47) What is the benefit of WebAPI over WCF?

WCF services use the SOAP protocol while HTTP never use SOAP protocol. That’s why WebAPI services are lightweight since SOAP is not used. It also reduces the data which is transferred to resume service. Moreover, it never needs too much configuration. Therefore, the client can interact with the service by using the HTTP verbs.


48) State differences between MVC and WebAPI

MVC framework is used for developing applications which have User Interface. For that, views can be used for building a user interface.

WebAPI is used for developing HTTP services. Other apps can also be called the WebAPI methods to fetch that data.


49) Who can consume WebAPI?

WebAPI can be consumed by any client which supports HTTP verbs such as GET, PUT, DELETE, POST. As WebAPI services don’t need any configuration, they are very easy to consume by any client. Infract, even portable devices like Mobile devices can easily consume WebAPI which is certainly the biggest advantages of this technology.


50) How can we make sure that Web API returns JSON data only?

To make Web API serialize the returning object to JSON format and returns JSON data only. For that you should add the following code in WebApiConfig.cs class in any MVC Web API Project:

//JsonFormatter

//MediaTypeHeaderValue

Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

1

2

3

//JsonFormatter

//MediaTypeHeaderValue

Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"))

Top 24 Microservices Interview Questions and Answers (2021)

 1) Explain microservices architecture

Microservice Architecture is an architectural development style which builds an application as a collection of small autonomous services developed for a business domain.

2) Name three commonly used tools for Microservices

  • 1.) Wiremock, 2.) Docker and 3.) Hysrix are important Microservices tool.


3) What is Monolithic Architecture?

Monolithic architecture is like a big container in which all the software components of an application are clubbed inside a single package.


4) What are the advantages of microservices?

Here, are some significant advantages of using Microservices:

  • Technology diversity, e., Microservices can mix easily with other frameworks, libraries,  and databases
  • Fault isolation, e., a process failure should not bring the whole system down.
  • Greater support for smaller and parallel team
  • Independent deployment
  • Deployment time reduce


5) What is Spring Cloud?

Spring cloud is an Integration software that integrates with external systems. It allows microservices framework to build applications which perform restricted amounts of data processing.

Microservice Interview Question And Answers

6) Discuss uses of reports and dashboards in the environment of Microservices

Reports and dashboards help in monitoring and upkeep of Microservices. Tons of Application Monitoring Tools assist in this.


7) What are main differences between Microservices and Monolithic Architecture?

MicroservicesMonolithic Architecture
Service Startup is fastService startup takes time
Microservices are loosely coupled architecture.Monolithic architecture is mostly tightly coupled.
Changes done in a single data model does not affect other Microservices.Any changes in the data model affect the entire database
Microservices  focuses  on products, not projectsMonolithic put emphasize over the whole project

8) What are the challenges faced while using Microservices?

  • Microservices always rely on each other. Therefore, they need to communicate with each other.
  • As it is distributed system, it is a heavily involved model.
  • If you are using Microservice architecture, you need to ready for operations overhead.
  • You need skilled professionals to support heterogeneously distributed microservices.


9) In which cases microservice architecture best suited?

Microservice architecture is best suited for desktop, web, mobile devices, Smart TVs, Wearable, etc.


10) Tell me the name of some famous companies which are using Microservice architecture

Most large-scale websites like Twitter, Netflix, Amazon, have advanced from a monolithic architecture to a microservices architecture.


11) What are the characteristics of Microservices?

  • Essential messaging frameworks
  • Decentralized Governance
  • Easy Infrastructure automation
  • Design for failure
  • Infrastructure automation


12) What is RESTful?

Representational State Transfer (REST)/RESTful web services is an architectural style that helps computer systems to communicate over the internet. These web services make microservices easier to understand and implement.


13) Explain three types of Tests for Microservices?

In Microservice architecture tests are divided into three broad categories:

  • At the bottom level test, we can perform a general test like performance and unit tests. These kinds of tests are entirely automated.
  • At the middle level, we can perform exploratory tests like the stress tests and usability tests.
  • At the top level, we can conduct acceptance tests which are mostly fewer in numbers. It also helps stakeholders to know about different software features.


14) What are Client certificates?

Client certificates is a digital certificate used to make authenticated requests to a remote server. It is termed as a client certificate.


15) Explain the use of PACT in Microservices architecture?

It is an open source tool which allows testing interactions between service providers and consumers. However, it is separated from the contract made. This increases the reliability of the Microservices applications.


16) What is the meaning of OAuth?

OAuth means open authorization protocol. This protocol allows you to access the client applications on HTTP for third-party providers GitHub, Facebook, etc. It helps you to share resources stored on one site with another site without the need for their credentials.


17) What is End to End Microservices Testing?

End-to-end testing validates every process in the workflow is functioning correctly. It also ensures that the system works together as a whole and satisfies all requirements.


18) Why are Container used in Microservices?

Containers are easiest and effective method to manage the microservice based application. It also helps you to develop and deploy individually. Docker also allows you to encapsulate your microservice in a container image along with its dependencies. Microservice can use these elements without additional efforts.


19) What is the meaning of Semantic monitoring in Microservices architecture?

Semantic monitoring combines automated tests with monitoring of the application. It allows you to find out reasons why your business is not getting more profits.


20) What is a CDC?

CDC is Consumer-Driven Contract. It is a pattern for developing Microservices so that external systems can use them.


21) What is the use of Docker?

Docker offers a container environment which can be used to host any application. This software application and the dependencies that support it which are tightly-packaged together.


22) What are Reactive Extensions in Microservices?

Reactive Extensions is also called Rx. It is a design pattern which allows collecting results by calling multiple services and then compile a combined response. Rx is a popular tool in distributed systems which works exactly opposite to legacy flows.


23) Explain the term ‘Continuous Monitoring.’

Continuous monitoring is a method which is used for searching compliance and risk issues associated with a company’s operational and financial environment. It contains human, processes, and working systems which support efficient and actual operations.


24) How independent micro-services communicate with each other?

It depends upon your project needs. However, in most cases, developers use HTTP/REST with JSON or Binary protocol. However, they can use any communication protocol.

lunes, 8 de febrero de 2021

Subir multiples imagenes html php

En este momento revisaremos la forma de subir múltiples imágenes desde un control html hacia programación php y algunas pequeñas reglas que merecen tener al momento de solo subir imágenes.





pagina subir.html

<form method="post" action="proceso.php" enctype="multipart/form-data">
    Subir imagen: <input type="file" name="file[]" multiple>
    <input type="submit" value="Subir imágenes" />
 </form>

pagina cargar_archivos.php

<?php

if (isset($_FILES["file"]))
{
   $reporte = null;
     for($x=0; $x<count($_FILES["file"]["name"]); $x++)
    {
      $file = $_FILES["file"];
      $nombre = $file["name"][$x];
      $tipo = $file["type"][$x];
      $ruta_provisional = $file["tmp_name"][$x];
      $size = $file["size"][$x];
      $dimensiones = getimagesize($ruta_provisional);
      $width = $dimensiones[0];
      $height = $dimensiones[1];
      $carpeta = "tu_ruta/";

      if ($tipo != 'image/jpeg' && $tipo != 'image/jpg' && $tipo != 'image/png' && $tipo != 'image/gif')
      {
          $reporte .= "<p style='color: red'>Error $nombre, el archivo no es una imagen.</p>";
      }
      else if($size > 1024*1024)
      {
          $reporte .= "<p style='color: red'>Error $nombre, el tamaño máximo permitido es 1mb</p>";
      }
      else if($width > 500 || $height > 500)
      {
          $reporte .= "<p style='color: red'>Error $nombre, la anchura y la altura máxima permitida es de 500px</p>";
      }
      else if($width < 60 || $height < 60)
      {
          $reporte .= "<p style='color: red'>Error $nombre, la anchura y la altura mínima permitida es de 60px</p>";
      }
      else
      {
          $src = $carpeta.$nombre;

          //Caragamos imagenes al servidor
          move_uploaded_file($ruta_provisional, $src);       

          //Codigo para insertar imagenes a tu Base de datos.
          //Sentencia SQL

          echo "<p style='color: blue'>La imagen $nombre ha sido subida con éxito</p>";
      }
    }

    echo $reporte;
}

jueves, 3 de diciembre de 2020

¿Qué tipo de servicios de hosting son los más indicados para tu sitio web?


 


Un hosting se trata de un servicio de alojamiento para sitios web, esto permite a las empresas, negocios o usuarios, tener un espacio en el que poder almacenar información de forma segura, además de tener una carga rápida de su página y diferenciarlo de la competencia dentro de internet. Hoy día es posible contar con proveedores de hosting que ofrecen diferentes opciones de alojamiento, rápidas y con el mejor rendimiento, para cada tipo de sitio web.

Proveedores de alojamiento

El proveedor de hosting TITANHOSTING.CL se trata de una agencia en la que encontrarás una gran variedad de paquetes de alojamiento, cada uno con sus propias características, espacio de almacenamiento o velocidad, para que puedas elegir el mejor para tu sitio web.

Esta agencia ofrece sus servicios utilizando LiteSpeed, un software instalado en el servidor web que se encarga de procesar un sitio web para que se pueda visualizar de forma rápida, segura y con el mejor rendimiento.

El hecho de que esta agencia comenzase a utilizar LiteSpeed en vez de Apache, uno de los servidores web más antiguos y conocidos, se debe a que este último comenzó a presentar problemas, provocando fallos en su rendimiento y, por lo tanto, en la experiencia de navegación de los usuarios. El tráfico en Apache se desbordaba constantemente, debido a que su arquitectura estaba desactualizada, resultando ineficiente para ofrecer un buen rendimiento a los usuarios.

Es aquí cuando nacen otras alternativas, como LiteSpeed, un servidor más moderno, con una mejor eficiencia y una mayor robustez, que terminaría por convertirse en la opción preferida entre los usuarios, ya que permite soportar una gran cantidad de trabajo, ofreciendo un buen rendimiento en sus servicios de alojamiento.

Además, LiteSpeed utiliza muchas cosas que funcionan de Apache, pero mejoradas. Incluso es compatible con la mayor parte de su configuración y con los módulos más esenciales de este hosting, motivo por el cual se considera el sustituto ideal.

Gracias a esta compatibilidad con Apache, y en específico con los archivos .htaccess, es posible realizar una migración hacia LiteSpeed sin tantos ajustes complicados, sin errores, de forma rápida y sencilla, permitiendo así que el proceso sea más eficiente que con otros servidores.

Debido a su compatibilidad con Apache, así como por ofrecer una mayor eficiencia y rendimiento, LiteSpeed es la opción ideal para cualquier empresa o negocio que esté buscando un hosting en el que poder almacenar su sitio web, ya que garantizará la calidad y velocidad que puede necesitar cualquier portal para ofrecer la mejor experiencia a los usuarios.

La mejor opción a elegir

Como ya hemos mencionado antes, el proveedor de servicios de alojamiento que indicamos más arriba, ofrece diferentes servicios de alojamiento. El más popular y eficiente que posee es el TITAN 2048un servicio de alojamiento orientado a los sitios web con un consumo de visualizaciones de tipo medio-bajo.

Son muchas las ventajas de este hosting, entre las cuales podemos destacar las siguientes.

Velocidad

Una de las mayores ventajas de LiteSpeed es su velocidad y eficiencia, ya que está diseñado con una arquitectura que aprovecha totalmente el uso de la CPU y de todos sus núcleos, así como de la memoria RAM y de forma simultánea, de esta manera se pueden disponer de webs de alto rendimiento que generen menos carga de trabajo a los servidores.

Además, se puede manejar una mayor cantidad de tráfico en comparación con Apache, utilizando el mismo hardware.

Seguridad

A nivel de seguridad, LiteSpeed ofrece una excelente protección contra hackeos o ataques DDoS.

Esto gracias a que es compatible con mod_security, un módulo de seguridad que funciona como un Firewall de programas o aplicaciones, ofreciendo una capa de seguridad capaz de filtrar las peticiones para así mantener una protección ante cualquier ataque. También incluye las funcionalidades de reCaptcha y de protección por países.

Servidores en CHILE - AUSTRALIA

Gracias a que los servidores se encuentran en SANTIAGO y MELBOURNE, es posible ofrecer un menor tiempo de acceso a las páginas web donde deseen acceder los usuarios.

Esto se debe a que, al viajar los paquetes por internet, saltan por varios puntos en la red, así que cuanto más lejos estén los usuarios del servidor, los paquetes darán más saltos y la latencia será mayor, tardando en llegar a los servidores.

Aparte de tener servidores en USA AUSTRALIA y CHILE, el proveedor de hosting dispone de IP’s Chilenas y de una conexión con empresas como Entel, Telstra, Telefónica o GTD MANQUEHUE.

Facilidad de uso

LiteSpeed trabaja con el panel de control cPanel, uno de los más utilizados dentro del sector de web hosting, por lo que podrás utilizarlo con mayor facilidad y así obtener un rendimiento más positivo, tanto en los servidores como en los sitios web.

Podrás crear correos electrónicos en pocos pasos y en las cantidades que quieras, ya que no existe un límite de cuentas de e-mail con este servicio.

Soporte

También puedes disponer de soporte 24/7, por lo que ante cualquier problema o duda que puedas tener con el servicio, tendrás un profesional disponible para ofrecerte las mejores soluciones.

Otra opción a considerar

Otro de sus paquetes de servicio de alojamiento que funciona con LiteSpeed es el Hosting, con el cual podrás aumentar la potencia de tu hosting sin que debas migrar a un servidor VPS.

Además de LiteSpeed, este servicio incluye otras licencias como cPanel, Softaculous, Antivirus, Antispam, Firewall, entre otros.

Gracias a estos servicios, en el momento que recibas más tráfico en tu sitio web, contarás con un mayor rendimiento que permitirá gestionar los diferentes tipos de visitas, y de esta manera no perderás ventas.

Gracias al servicio de hosting que ofrece Titan Hosting, tendrás un espacio optimizado, de gran rendimiento y rápido, en el que alojar tu sitio web, para así ofrecer la mejor experiencia de navegación a los usuarios que acceden a tu portal.