pu

Buscar este blog

sábado, 22 de enero de 2022

Como Instalar Odoo 13 En Centos 8



Hoy realizaremos la instalacion de odoo 13 en una maquina virtual centos 8 minimal desde 0.


1. Verificamos si tenemos instalado DNF con el Siguiente comando.


 sudo dnf update

2. Lo siguiente realizamos la instalacion de EPEL Repository

$ sudo dnf install epel-release

3. Lo siguiente es descargar e instalar todas las dependencias relacionadas para utilizar ODOO por mi parte se instalaron al rededor de 90 paquetes necesarios.

$ sudo dnf install python36 python36-devel git gcc wget nodejs libxslt-devel bzip2-devel openldap-devel libjpeg-devel freetype-devel

4. Ahora necesitamos la base de datos donde realizaremos la carga de todo relacionado con odoo para esto instalaremos POSTGRESQL

$ sudo dnf install postgresql-server postgresql-contrib

5. Ahora inicializamos el servicio en la maquina para que cada vez que inicie este habilitado.

$ sudo postgresql-setup initdb

6. Ahora realizamos una comprobacion de reinicio del sistema y habilitamos.

$ sudo systemctl restart postgresql
$ sudo systemctl enable postgresql

7. A continuacion chequiamos que este funcionando todo ok

$ sudo systemctl status postgresql
8. A continuacion instalamos un paquete indispensable para ODOO que es Wkhtmltopdf
$ sudo dnf install https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.5/wkhtmltox-0.12.5-1.centos8.x86_64.rpm
9. y empezamos a instalar odoo en la maquina creando usuarios y grupos
$ sudo useradd -m -U -r -s /bin/bash odoo -d /opt/odoo 
10. cambiamos al usuario odoo para realizar la instalacion en esa cuenta.
$ sudo su - odoo
11. clonamos el repositorio en la carpeta correspondiente.
$ git clone https://www.github.com/odoo/odoo --depth 1 --branch 13.0 /opt/odoo/odoo13

12. ahora clonamos el enviroment para realizar la instalacion
$ cd /opt/odoo
$ python3 -m venv odoo13-venv
13. verificamos que estamos en el enviroment adecuado
$ source odoo13-venv/bin/activate
14. y realizamos la instalacion de la lista de requerimientos de odoo (esto tarda un momento dependiendo de tu internet y la potencia de la maquina)
pip install --upgrade pip
$ pip3 install -r odoo13/requirements.txt
15. despues de todo ok realizamos la desactivacion de los ambientes de instalacion
$ deactivate && exit
16. creeamos y damos permiso a las carpetas para los addons del sistema odoo

$ sudo mkdir /opt/odoo/odoo13-custom-addons
$ sudo chown -R odoo:odoo /opt/odoo/odoo13-custom-addons
17. en la misma linea creamos direcctorios correspondientes a las configuraciones por default
$ sudo mkdir /var/log/odoo13
$ sudo touch /var/log/odoo13/odoo.log
$ sudo chown -R odoo:odoo /var/log/odoo13/
18. a continuacion creamos el archivo de config odoo
$ sudo vim /etc/odoo.conf

19. escribimos en el siguiente archivo lo siguiente
[options]
; This is the password that allows database operations:
admin_passwd = strong_password
db_host = False
db_port = False
db_user = odoo
db_password = False
xmlrpc_port = 8069
; longpolling_port = 8072
logfile = /var/log/odoo13/odoo.log
logrotate = True
addons_path = /opt/odoo/odoo13/addons,/opt/odoo/odoo13-custom-addons
20. Continuamos con crear el archivo de servicio

$ sudo vim /etc/systemd/system/odoo13.service
21. y escribimos lo sigiunete en el archivo de servicio
[Unit]
Description=Odoo13
#Requires=postgresql-10.6.service
#After=network.target postgresql-10.6.service

[Service]
Type=simple
SyslogIdentifier=odoo13
PermissionsStartOnly=true
User=odoo
Group=odoo
ExecStart=/opt/odoo/odoo13-venv/bin/python3 /opt/odoo/odoo13/odoo-bin -c /etc/odoo.conf
StandardOutput=journal+console

[Install]
WantedBy=multi-user.target
22. realizamos un reload al sistema para que tome los cambios realizados

$ sudo systemctl daemon-reload
23. continuamos con recargar el sistema de odoo e inicializar 
$ sudo systemctl start odoo13
$ sudo systemctl enable odoo13
24. continuamos confirmamos que odoo esta correctamente corriendo.

$ sudo systemctl status odoo13
25. instalamos netstat para habilitar el acceso a la maquina

$ yum -y install net-tools
26. habilitamos el puerto para establecer comunicacion

$ sudo netstat -pnltu | grep 8069
27. para acceder del browser habilitamos desde firewall
$ sudo firewall-cmd --add-port=8069/tcp --zone=public --permanent
$ sudo firewall-cmd --reload
28. ahora instalamos nginx
$ sudo dnf install nginx
29. y pega este codigo en el archivo de odoo13.conf

$ sudo vim /etc/nginx/conf.d/odoo13.conf

siguiendo lo de mas abajo.

upstream odoo {
 server 127.0.0.1:8069;
}
server {
    listen 80;
    server_name server-IP;

    access_log /var/log/nginx/odoo13.access.log;
    error_log /var/log/nginx/odoo13.error.log;

        location / {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;

        proxy_redirect off;
        proxy_pass http://odoo;
    }
location ~* /web/static/ {
        proxy_cache_valid 200 90m;
        proxy_buffering on;
        expires 864000;
        proxy_pass http://odoo;
    }
    gzip_types text/css text/less text/plain text/xml application/xml application/json application/javascript;
    gzip on;
}
29. ahora inicializamos nginx
$ sudo systemctl start nginx
$ sudo systemctl enable nginx
30. confrmamos que nginx este funcionando

$ sudo systemctl status nginx
31. entramos a la url del sitio

http://tu-server/
32. actualizacion de error hacer lo siguiente para agregar el rol al usuario odoo

500 internal server error (Linux)

OperationalError: FATAL: role "root" does not exist

You find this error in file : /var/log/postgrsql/postgrsql-10-main.log (on linux system)

The solution may be :

    1- Open Terminal and enter => sudo su postgres
    2- Enter password for postgres System user (if it is necessary)
    3- createuser odoo -s
    4- psql template1
    5- alter role odoo with password 'yourpassword';
    6- \q
    7- exit
    8- service odoo restart

Now try again to localhost:8069

jueves, 13 de enero de 2022

What is header file #include ?




*The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header <stdio.h>.

  • The first thing you will notice is the first line of the file, the #include "stdio.h" line. This is very much like the #define the preprocessor , except that instead of a simple substitution, an entire file is read in at this point.
  • The system will find the file named "stdio.h" and read its entire contents in, replacing this statement.
  • Obviously then, the file named "stdio.h" must contain valid C source statements that can be compiled as part of a program.
  • This particular file is composed of several standard #defines to define some of the standard I/O operations.
  • The file is called a header file and you will find several different header files on the source disks that came with your C compiler.
  • Each of the header files has a specific purpose and any or all of them can be included in any program.

  • Your C compiler uses the double quote marks to indicate that the search for the "include" file will begin in the current directory, and if it not found there, the search will continue in the "include" directory as set up in the environment.

  • It also uses the "less than" and "greater than" signs to indicate that the file search should begin in the directory specified in the environment.
  • Most of the programs in this tutorial have the double quotes in the "include" statements. The next program uses the "<" and ">" to illustrate the usage.
  • Note that this will result is a slightly faster (but probably unnoticeable) compilation because the system will not bother to search the current directory.

C – stdio.h library functions

  ********All C inbuilt functions which are declared in stdio.h header file are given below.********

List of inbuilt C functions in stdio.h file:

  1. printf() This function is used to print the character, string, float, integer, octal and hexadecimal values onto the output screen

  2. scanf() This function is used to read a character, string, numeric data from keyboard.

  3. getc() It reads character from file

  4. gets() It reads line from keyboard

  5. getchar() It reads character from keyboard

  6. puts() It writes line to o/p screen

  7. putchar() It writes a character to screen

  8. clearerr() This function clears the error indicators

  9. f open() All file handling functions are defined in stdio.h header file

  10. f close() closes an opened file

  11. getw() reads an integer from file

  12. putw() writes an integer to file

  13. f getc() reads a character from file

  14. putc() writes a character to file

  15. f putc() writes a character to file

  16. f gets() reads string from a file, one line at a time

  17. f puts() writes string to a file

  18. f eof() finds end of file

  19. f getchar reads a character from keyboard

  20. f getc() reads a character from file

  21. f printf() writes formatted data to a file

  22. f scanf() reads formatted data from a file

  23. f getchar reads a character from keyboard

  24. f putchar writes a character from keyboard

  25. f seek() moves file pointer position to given location

  26. SEEK_SET moves file pointer position to the beginning of the file

  27. SEEK_CUR moves file pointer position to given location

  28. SEEK_END moves file pointer position to the end of file.

  29. f tell() gives current position of file pointer

  30. rewind() moves file pointer position to the beginning of the file

  31. putc() writes a character to file

  32. sprint() writes formatted output to string

  33. sscanf() Reads formatted input from a string

  34. remove() deletes a file

  35. fflush() flushes a file

lunes, 3 de enero de 2022

U.S. FDA authorizes Pfizer-BioNTech COVID-19 vaccine boosters for children ages 12-15




 The FDA also shortened the time for booster shots from at least six months after completion of the initial series to at least five months, for everyone aged 12 and older.

WASHINGTON, Jan. 3 (Xinhua) -- The U.S. Food and Drug Administration (FDA) on Monday expanded the emergency use authorization for the Pfizer-BioNTech COVID-19 vaccine boosters to children ages 12 to 15.

The FDA also shortened the time for booster shots from at least six months after completion of the initial series to at least five months, for everyone aged 12 and older.

The agency has determined that the protective health benefits of a single booster dose of the Pfizer-BioNTech COVID-19 vaccine to provide continued protection against COVID-19 and the associated serious consequences outweigh the potential risks in individuals ages 12 to 15.

The agency said that it found "no new safety concerns" following a booster shot in young teenagers, and that there were no new reports of two types of heart inflammation called myocarditis or pericarditis linked to the boosters.

The decision came as the Omicron variant is spreading rapidly across the United States and has led to record high hospitalizations among younger people.

martes, 28 de diciembre de 2021

Trabajadores de Informática de Junaeb son separados del área por expresar desacuerdo con decisiones de la dirección

 

Trabajadores de Informática de Junaeb son separados del área por expresar desacuerdo con decisiones de la dirección







Andrés Reyes, Rodrigo Matus y Bárbara Gálvez fueron separados de la Unidad de Desarrollo, Sistemas y Soporte. Esta determinación la tomó la dirección de Junaeb luego que nuestros compañeros hicieran ver actos de negligencia, así como la nula participación en la cotización y adquisición de sistemas informáticos, softwares y tecnologías de información en general.

“Solicitamos una reunión hace más de un año con el director, para informar que los procesos informáticos iban mal, que no se puede externalizar los procesos que son propios de Junaeb que era un riesgo latente. Hoy todas las compras de desarrollo se encuentran sin avances y algunos proveedores han abandonado los proyectos, si nos movilizamos es porque necesitábamos ayuda para tomar medidas que permitieran minimizar el impacto en los beneficiarios. Realizamos un petitorio por un trato digno bajo el marco de respeto y fuimos castigados, sin importar el gesto noble de alertar”,

Afaeb está asesorando y apoyando a los trabajadores involucrados y luego de conocer los detalles de la situación condenó enérgicamente el actuar de la Dirección de Junaeb: “Creemos que es una nueva manifestación del estilo autoritario y anti trabajadores de la administración de Jaime Tohá, quien claramente está malusando las herramientas administrativas para amedrentar y coartar la acción funcionaria. No aceptaremos estas malas prácticas, por eso iniciaremos acciones judiciales para que se restablezcan en sus funciones a los compañeros removidos, pues no obedece a motivos técnicos, sino meramente revanchistas”, advirtió Carolina Pizarro, presidenta de AFAEB. 

Esta no es una situación aislada, se trata de una política institucional de maltrato y abandono para posteriormente justificar nuevas externalizaciones. Actualmente, la Dirección Nacional de Junaeb enfrenta más de 10 presentaciones realizadas en la Contraloría General de la República entre los años 2020 y 2021 por maltrato y acoso laboral, conflictos de interés, faltas graves a la probidad administrativa, irregularidad en licitaciones públicas, entre otros. Además, hay más de 7 acciones judiciales presentadas ante Tribunales del Trabajo y Cortes de Apelaciones por eventual vulneración por discriminación arbitraria, integridad física y psíquica, así como despidos arbitrarios.

¿Cómo darle una nueva vida a tu viejo computador? claves y buenos consejos




Cada vez son más las personas que optan por comprar un portátil frente a un ordenador de sobremesa. Pero como sucede con la tecnología, los portátiles con el paso de los años comienzan a ir lentos o se quedan desfasados. Y en ese punto siempre nos hacemos la misma pregunta ¿Qué hago con mi viejo portátil? Para ayudarte, nos hemos puesto en contacto con Informaticos con experiencia. Ellos nos han dado una serie de claves con las cuales podremos dar una segunda vida al portátil y así sacarle más partido. Tanto si quieres cuidar el medio ambiente o quieres ahorrar, las siguiente claves te vendrán muy bien.

  Cambia el sistema operativo 


En muchas ocasiones el portátil va lento porque el sistema operativo exige más de lo que el ordenador puede dar. Eso hace que la experiencia sea desagradable y los bloqueos están al orden del día. Para evitar ese problema, puede ser una buena opción cambiar el sistema operativo por uno como Linux o sobre todo Chrome OS, el cual exige muy poco del ordenador. Eso hará que puedas dar un uso normal al ordenador sin los continuos bloqueos. Es verdad que el sistema es un poco diferente, pero rápidamente te acostumbras y podrás seguir disfrutando el ordenador. 

  Compra recambios para el portátil 


En ocasiones el portátil deja de funcionar correctamente porque una de las piezas deja de funcionar bien. Como nos informan desde area de Informática, expertos en piezas de recambios para ordenadores, las baterías suelen ser una de las piezas que antes se suelen estropear. En ese caso, solo tienes que acudir a una tienda de recambios como la de Informatica Arcos y adquirir una nueva batería. Pero debes saber que también hay recambios para muchas otras piezas de los portátiles. Suele ser bastante común ver como muchas personas solicitan pantallas, cargadores, teclados o incluso memoria interna. Si tienes claro qué es lo que necesita tu ordenador, con una pieza podrás darle una buena vida al portátil. Así reducirás la contaminación medioambiental y podrás seguir usando tu portátil a cambio de una inversión baja. Además, los cambios son bastante sencillos, sobre todo si usamos uno de los tutoriales que podemos encontrar por internet con facilidad. 

  Desmonta y reutiliza las piezas 


Si tienes claro que no le puedes dar una segunda vida al portátil, puede ser una buena opción desmontar las diferentes piezas y reutilizarlas. Si ves que por cualquier motivo no vas a dar uso a las diferentes piezas como disco duro, RAM, pantalla… debes saber que hay empresas que te comprarán esas piezas. Es verdad que no vas a sacar demasiado dinero, pero algo sí que sacaras. No solo sacarás dinero para adquirir un nuevo portátil, también conseguirás ayudar al medio ambiente porque buena parte de las piezas tendrán un segundo uso.
 

Deja el portátil como un ordenador secundario


Si el problema viene dado en que el ordenador no tiene fuerza para mover determinadas aplicaciones, puedes dejarlo como ordenador secundario. Son muchas las personas que lo dejan para poder ver por internet películas y series. Solo hay que borrar todo lo que hace que el ordenador no funcione bien y dejar aplicaciones tan sencillas como HBO o Netflix. Gracias a esas plataformas solo tendrás que poner la peli que te gusta y podrás sacarle rendimiento a tu viejo portátil. Además, las videoconsolas en la nube como Stadia se están poniendo de moda. Eso significa que también podrás usar tu viejo portátil para jugar a juegos actuales. Parece mentira, pero plataformas como Stadia te permitirán jugar en tu viejo ordenador a juegos como RDR2 entre otros muchos. Lo importante es tener una buena conexión y que el ordenador solo haga de transmisor. La exigencia es tan baja que incluso los ordenadores más viejos pueden mover la plataforma si son capaces de reproducir YouTube. Tienes juegos gratis para probar y ver si puedes usar el ordenador como una consola en la nube. 

  

Juegos retro 


Si no quieres jugar a una consola en la nube y quieres algo más tradicional, puedes usar el portátil para crear una pequeña consola de juegos retro. En la actualidad hay muchos emuladores, pero lo que está claro es que los más sencillos apenas consumen recursos. Eso significa que podrás darle una segunda oportunidad al ordenador como pequeña consola de juegos antiguos. Como hemos comentado, hay muchos emuladores entre los que elegir. Uno de los más conocidos es Puppy Arcade, pero hay más. Siempre que instales el emulador deberás fijarte si cuenta con los juegos que te interesan. Luego solo tendrás que instalar un mando para jugar a los juegos. Hay mandos que se conectan al USB rápidamente y otros que funcionan de manera inalámbrica. Dependiendo del ordenador que tengas, podrás optar o no por la opción inalámbrica. 





  Crear un centro multimedia

 

Si el ordenador no está demasiado mal, otra opción para sacarle partido es crear un centro multimedia. En su interior podrás guardar fotos, pelis y series. No solo las podrás reproducir en el propio ordenador, también podrás mandar la información a otros dispositivos. Para conseguirlo, puede ser una buena opción que uses centros multimedia como Plex o Kodi. Son los más populares, pero hay otras opciones entre las que elegir. 

  Donación 



Si no tienes paciencia o no tienes claro que segunda vida dar al portátil, no lo tires a la basura. Si todavía funciona, siempre te queda la opción de donarlo para que terceras personas sin recursos lo puedan usar y aprovechar. Parece mentira, pero para nosotros es un ordenador que debe ir a la basura, para otros es una auténtica joya. En tu mano está donarlo o tirarlo. Pero debes tener claro que a través de una donación podrás hacer a una persona muy feliz. En la actualidad hay algunas ONG que se encargan de recoger en tu propia casa el portátil y ellos ya se lo donan a la persona que lo necesite. Así no te deberás preocupar de nada.

miércoles, 22 de diciembre de 2021

FUAS 2021 | ¿Cómo y dónde revisar los resultados?

 La tarde de este miércoles se darán a conocer los resultados del nivel socioeconómico del FUAS.





Hoy se darán a conocer los resultados socioeconómicos del Formulario Único de Acreditación Socioeconómica (FUAS), un cuestionario creado por el Ministerio de Educación (Mineduc) para facilitar la inscripción simultánea a todas las becas y ayudas del Estado para estudiantes de educación superior.

Son 18 los beneficios disponibles en total, entre gratuidad, becas, fondos y créditos. Tomando en cuenta que estudiar una carrera universitaria implica grandes gastos que no todos pueden costear, estos beneficios estatales significan una gran oportunidad para quienes buscan avanzar hacia la educación superior, pero que no tienen los medios para pagarla.

Si ya postulaste al FUAS 2022 y quieres conocer tus resultados, te explicamos a continuación cómo hacerlo.


¿Cómo y dónde revisar los resultados del FUAS?

Los resultados del FUAS se publican este miércoles 22 de diciembre a las 15.00 horas. Para conocer tus resultados deberás ingresar AQUÍ.

Ten presente que estos son solo los resultados socioeconómicos, es decir solo se informará a los postulantes si cumplen con los requisitos socioeconómicos para optar a los beneficios.

Recién el 20 de enero de 2022 se conocen los resultados de preselección, que indican si el postulante cumple los otros requisitos para obtener los beneficios.

Luego, el 25 de enero comienza el proceso de matrículas. Después de esto, cuando el estudiante esté matriculado en una carrera, se hacen válidos los beneficios obtenidos en la preselección y el Mineduc publica los resultados finales de asignación.

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"))