Showing posts with label ASP.NET MVC. Show all posts
Showing posts with label ASP.NET MVC. Show all posts

Tuesday, November 27, 2018

ASP.NET MVC Mono

Settings at 11/2018

.Net Framework 4.5.2 using project properties
Mysql.Data.Entity using NuGet(6.10.8)

Setup Web.config

<!--Added--> 
<configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.2.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections> 
<connectionStrings> 
  <add name="ferredb" connectionString="server=127.0.0.1;Port=3306;Database=ferre;Uid=root;Pwd=Microsoft;" providerName="MySql.Data.MySqlClient"/> </connectionStrings> 
<!--Added--> 
<entityFramework> 
<providers> 
  <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
  </provider> 
</providers> 
</entityFramework> 
<!--Added--> 
<system.data> 
<DbProviderFactories> <remove invariant="MySql.Data.MySqlClient" /> <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.10.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/> 
 </DbProviderFactories> 
</system.data>

Fix version of entry System.Web.Mvc.MvcWebRazorHostFactory at views/Web.config


Classes

//Ado
using System;
using System.Data.Entity;
using MySQLEntity.Models;

namespace MySQLEntity.Entity
{

public class MyDb : DbContext
{
public MyDb() : base("ferredb")
//public MyDb() : base(nameOrConnectionString: "ferredb")
{
}
public DbSet<Usuario> Usuarios { get; set; }
}


}


//Entity
using System;
//Added
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;


namespace MySQLEntity.Models
{
        [Table("Users")]
        public class Usuario
        {
            [Key]
            public string usuario { get; set; }
            public string apenom  { get; set; }
        }

}



Controller Snippet code

public ActionResult Index()
{
  MyDb db = new MyDb();
  var Model=db.Usuarios.ToList();
  return View(Model);
}

View Snippet code


@foreach (var item in Model)
{


<div> @item.usuario @item.apenom </div>
}

Action results
Types

References:
[1] MySQL EntityFramework web.config https://iyalovoi.wordpress.com/2015/04/06/entity-framework-with-mysql-on-mac-os/
[2] Action results
https://www.c-sharpcorner.com/article/different-types-of-action-results-in-asp-net-mvc/
[3] ViewBag better than DataView http://www.tutorialsteacher.com/mvc/viewbag-in-asp.net-mvc


Wednesday, February 12, 2014

Se detectó un posible valor Request.Form peligroso en el cliente …

en inglés se llama “A potentially dangerous Request.Form value was detected from the client”.

varias páginas indican dos cosas:
1. agregar en la cebecera del pagina aspx
<%@ Page validateRequest="false" %>

2. modificar web.config

< validaterequest="false">

...

pero no siempre funciona, o almenos no para lo que yo queria, entonces lo solucione con el siguiente tag:

[ValidateInput(false)]
public ActionResult SaveEdition(FormCollection form)
{
string editorValue = HttpUtility.HtmlDecode(Request["txtEditor"].ToString());
return null;
}

sobre el método que recibe el codigo html en su respectivo text o textarea


Adicionalmente para versiones recientes:

Agregar lo sgte en <system.web> :

<httpRuntime requestValidationMode="2.0" />




ASP.NET MVC: Implementing HTTP File Upload

Referencias:
[1]  http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

Friday, September 27, 2013

Asp.Net Insecure Session Cookie Handling Vulnerability

Add next code in c:\inetpub\wwwroot\web.config


    <system.web>
      <httpCookies
             httpOnlyCookies="true"
             requireSSL="true" />
    </system.web>


References:
[1] http://www.codeproject.com/Articles/291562/Asp-net-web-application-Security-Review-Dos-Dont
[2] http://forums.asp.net/t/1756774.aspx
[3] http://www.enterprisenetworkingplanet.com/netsecur/ten-tips-to-make-your-ssl-secure.html
[4] https://www.owasp.org/index.php/HttpOnly
[5] http://xss.cx/examples/dork/programming/ssl-cookie-without-secure-flag-set-example.html#1.7


IIS Custom Errors



1. Make html with custom message, and save that on any directory
    c:\inetpub\wwwroot\custom_errors\404.html
    c:\inetpub\wwwroot\custom_errors\500.html

2. Alter web.config of c:\inetpub\wwwroot, add next content.

<system.webServer> 
<httpErrors errorMode="Custom" existingResponse="Auto" defaultResponseMode="ExecuteURL">
  <clear />
  <error statusCode="404" path="/custom_errors/404.html" responseMode="ExecuteURL" />
  <error statusCode="500" path="/custom_errors/500.html" responseMode="ExecuteURL" /> 
</httpErrors> 
</system.webServer> 



References:
[1] http://stackoverflow.com/questions/434272/iis7-overrides-customerrors-when-setting-response-statuscode
[2] http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404-in-asp-net-mvc
[3] http://stackoverflow.com/questions/717628/asp-net-mvc-404-error-handling

Thursday, April 28, 2011

ASP.NET::The timeout period

The timeout period elapsed prior to completion of the operation or the server is not responding.

try below options, set command timeout parameter to 0. It will execute till the end. By default it will timeout in 30 secs.

Using Code:

sqlCommand.CommandTimeout = 0;

Using Connection String: Check the timeout in connection string, try setting it to max...
data source="ServerName;initial catalog=DataBaseName;uid=ID;pwd=Password;Connect Timeout=120"

Using Sql Server:On the SQL Server also you can set timeout of a query. Check with SQL Server DBA's to know the Query time out set on servers.

Using IIS: On IIS also you have timeout setting. In IIS --> Website tab --> Connection time out box . Set the max timeout value (in secs) IIS should maintain idle connection .

check all these possibilities

Tuesday, March 22, 2011

ASP.NET MVC and HTTPS

Enable SSL or HTTPS in IIS 7

1. Open IIS from Administrative Tools.
2. Navigate to Sites>Default Web Site. Or select the web site you want to enable SSL or HTTPS.
3. In the right pane, Click Binding.
4. Default is setup Port 80. You can click Add and to HTTPS or port 443.
5. Continue the instruction to complete the settigns.


Referencias:
[1]Adding HTTPS/SSL support to ASP.NET MVC routing
http://blog.stevensanderson.com/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/
[2]Requiring SSL For ASP.NET MVC Controllers
http://weblogs.asp.net/dwahlin/archive/2009/08/25/requiring-ssl-for-asp-net-mvc-controllers.aspx
[3]SSL pages under ASP.NET MVC
http://stackoverflow.com/questions/156748/ssl-pages-under-asp-net-mvc
[4]http://es.wikipedia.org/wiki/Hypertext_Transfer_Protocol_Secure
[5]Enabling SSL on IIS 7.0 Using Self-Signed Certificates http://weblogs.asp.net/scottgu/archive/2007/04/06/tip-trick-enabling-ssl-on-iis7-using-self-signed-certificates.aspx
[6] Configure IIS http://learn.iis.net/page.aspx/144/how-to-set-up-ssl-on-iis-7/
[7] IIS 7 SSL Certificate Installation http://www.digicert.com/ssl-certificate-installation-microsoft-iis-7.htm
[8] Enable SSL on IIS 7 (Spanish) http://thinkingindotnet.wordpress.com/2007/04/06/trucos-habilitar-ssl-en-iis-70-usando-certificados-firmados-por-nosotros/
[9] IIS7 - How to Install GoDaddy SSL Certificate http://www.netometer.com/video/tutorials/iis7-godaddy-ssl-certificate/
[10] Self-Signed Certificates on IIS 7 – the Easy Way and the Most Effective Way http://www.robbagby.com/iis/self-signed-certificates-on-iis-7-the-easy-way-and-the-most-effective-way/

Wednesday, December 15, 2010

ASP.NET C# Upload from URL

using System.Net;
WebClient wc = new WebClient();

wc.DownloadFile("http://sourcefile.ext", "drive:\\path\\targetfile.ext");



References:
[1] http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=115

Wednesday, September 22, 2010

Spring.NET NHibernate Dynamic ConnectionString

Configuration cfg = new
Configuration().Configure("hibernate.cfg.xml");
cfg.SetProperty("connection.connection_string", "Data
Source=MI_BASE;User ID=ID_USUARIO; Password=PASS_USUARIO");



References
[1] The Spring.NET Framework
http://www.springframework.net/doc-latest/reference/html/index.html
[2] http://gist.github.com/432083 (src-best)
[3] Changing your connection string at runtime with Spring.Net (src)
http://blog.bennymichielsen.be/2009/03/24/changing-your-connection-string-at-runtime-with-spring-net/

[4]How to change a connection string at runtime? (src)
http://forum.springframework.net/showthread.php?t=3390&page=3

[5] Authentication, Impersonation, and Dynamic NHibernate Connection Strings
http://jasondentler.com/blog/2009/11/authentication-impersonation-and-dynamic-nhibernate-connection-strings/
[6] Setting and retrieving the database connectionstring in nHibernate
http://codebetter.com/blogs/peter.van.ooijen/archive/2008/03/07/setting-and-retrieving-the-database-connectionstring-in-nhibernate.aspx

Thursday, September 09, 2010

ReportViewer with ASP.NET/ASP.NET MVC in Local Mode

Source code of original tutorial How to create local reports RDLC featuring barcode images in ASP.NET[0] on [1].
And adapted for ASP.NET MVC on [2]





Reference
[0] http://neodynamic.com/ND/FaqsTipsTricks.aspx?tabid=66&prodid=1&sid=66#2
[1] ReportViewer ASP.NET Sample Local mode http://www.megaupload.com/?d=RMP2MMI1
[2] ReportViewer ASP.NET MVC Sample Local mode http://www.megaupload.com/?d=U4SCTYDG
[3]Understanding ASP.NET View State http://msdn.microsoft.com/en-us/library/ms972976.aspx
[4] Creating Charts Using Aspnet ReportViewer Control http://www.highoncoding.com/Articles/339_Creating_Charts_Using_Aspnet_ReportViewer_Control.aspx
[5] Microsoft Report Viewer Redistributable 2008 http://www.microsoft.com/downloads/en/details.aspx?familyid=cc96c246-61e5-4d9e-bb5f-416d75a1b9ef&displaylang=en

[6] Leveraging the ASP.NET ReportViewer Control http://www.devproconnections.com/article/aspnet2/leveraging-the-asp-net-reportviewer-control.aspx

Friday, August 20, 2010

Cross-Domain & jsonp (java struts, php, asp.net mvc, otros )

Cross-Domain Proxy
En el caso de Ajax, por seguridad sólo se permite acceder al mismo dominio origen de la página web que realiza la petición. Si se necesita acceder a otros servicios localizados en otros dominios, se instala un Cross-Domain proxy en el dominio origen que recibe las peticiones ajax y las reenvia a los dominios externos.

Con jsonp es posible la llamada cross-domain, debido a que no es una llamada ajax sino una carga de un script js completo que lanza una función que definimos en la url y que actúa como callback.

Mientras que por motivos de seguridad es lógico que Ajax no funcione en dominios distintos al que lanza la web; con esta técnica JSON con Padding se genera un archivo JSON dinámicamente dejandolo abierto en el script que lo crea. Una variable que podemos definir nosotros mismos en la url será colocada antes del objeto Json, así al crear el script Json decidimos que variable "callback" usar.


Referencias

[1] jQuery y Strust
http://blog.pontt.com/json-con-java/generar-respuesta-en-java-struts-para-getjson-de-jquery/
[2] jQuery y php http://www.9lessons.info/2009/12/display-cross-domain-data-json-callback.html
[3] jQuery y Asp.Net Mvc (cross-domain JSON to ASP.NET MVC with jQuery)
http://www.integratedwebsystems.com/2010/07/cross-domain-jsonp-using-asp-net-mvc-and-jquery/
[4] cross-domain JSON to ASP.NET MVC with jQuery II
http://stackoverflow.com/questions/2022878/posting-cross-domain-json-to-asp-net-with-jquery
[5] Genericos(muy buenos)
http://www.ibm.com/developerworks/library/wa-aj-jsonp1/
http://ox.no/posts/ajast-cross-domain-rest-calls-using-json-injection
[6] Json to JsonP (easy)
http://www.codeproject.com/KB/aspnet/JSONToJSONP.aspx
http://www.codedigest.com/Articles/jQuery/310_Calling_a_WebService_using_jQuery_in_ASPNet.aspx
[7] Cross-site data retrieval using JSONP http://www.stpe.se/2008/10/cross-site-data-retrieval-using-jsonp/

Tuesday, June 08, 2010

ASP.NET HttpException: Maximum request length exceeded

Limite por defecto para uploads en Web.Config es 4096 (4 megabytes)

Las siguientes lineas cambian a 20MB

<configuration>
...
<system.web>
...
<httpRuntime maxRequestLength="20480" />
</system.web>
</configuration>


Otras Configuraciones

<httpRuntime executionTimeout="300" maxRequestLength="51200"/>
<httpRuntime
executionTimeout="1200"
maxRequestLength="102400"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="100" />

Nota:
maxRequestLength<=1048576 (1 GB) para .NET Framework 1.0/1.1 y
maxRequestLength<=2097151 (2 GB) for .NET Framework 2.0.

Referencias
FileUpEE - Large Uploads in ASP.NET:
http://support.softartisans.com/docs/fileupeev4/doc/dotnet/aspdotnet_largeuploads.asp

FileUpSE - large uploads in ASP.NET:
http://support.softartisans.com/docs/fileupv4/prog_g_dotnet_largeuploads.htm

Firefox open multiple private window

    /opt/firefox/firefox-bin --profile $(mktemp -d) --private-window www.google.com www.bing.com