Preparar web.config para html5 y css3

Ref: http://madskristensen.net/post/prepare-webconfig-for-html5-and-css3

 

HTML5 and CSS3 introduces some new file types that enables us to create even better websites. We are now able to embed video, audio and custom fonts natively to any web page. Some of these file types are relatively new and not supported by the IIS web server by default. It’s file types like .m4v, .webm and .woff.

When a request is made to the IIS for these unsupported file types, we are met with the following error message:

HTTP Error 404.3 – Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

The problem is that the IIS doesn’t know how to serve these new files unless we tell it how. This can be easily done in the web.config’s <system.webServer> section by adding the following snippet:

<staticContent>
    <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
    <mimeMap fileExtension=".m4v" mimeType="video/m4v" />
    <mimeMap fileExtension=".ogg" mimeType="video/ogg" />
    <mimeMap fileExtension=".ogv" mimeType="video/ogg" />
    <mimeMap fileExtension=".webm" mimeType="video/webm" />

    <mimeMap fileExtension=".oga" mimeType="audio/ogg" />
    <mimeMap fileExtension=".spx" mimeType="audio/ogg" />

    <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
    <mimeMap fileExtension=".svgz" mimeType="image/svg+xml" />

    <remove fileExtension=".eot" />
    <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
    <mimeMap fileExtension=".otf" mimeType="font/otf" />
    <mimeMap fileExtension=".woff" mimeType="font/x-woff" />
</staticContent>

The above snippet includes support for most video, audio and font file types used by HTML5 and CSS3

Herramientas Bootstrap

29-09-2016:

Checkboxes y Radio Buttons para Bootstrap

Pretty Checkbox & Radio Inputs with Bootstrap and awesome-bootstrap-checkbox.css

Recursos Bootstrap Official:

http://startbootstrap.com/bootstrap-resources/

Dialogos modales:

https://nakupanda.github.io/bootstrap3-dialog/

Plugins varios:

http://webrevisions.com/bootstrap-plugin/50-super-useful-twitter-bootstrap-plugins/#.Vw6FbvnhCM8

Plugin de recorte de imagenes:

http://www.croppic.net/

Plantillas Bootstrap

https://almsaeedstudio.com/themes/AdminLTE/index.html

Plugin para Wizards

http://vadimg.com/twitter-bootstrap-wizard-example/#

Validacion de formularios:

http://formvalidation.io/

Leer archivos JSON en aplicaciones .NET

Add .json file in asp.net web.config file

Para poder leer archivos .json desde visual studio agregar lo siguiente al archivo de configuracion de la aplicacion

 <system.webServer>
 <staticContent>
 <mimeMap fileExtension=".json" mimeType="application/json"/>
 </staticContent>
 </system.webServer>

 

Usar autenticacion windows en aplicaciones .NET II

Windows Authentication With ASP.NET Web Pages

4.88 (26 votes)

The default authentication mechanism built into ASP.NET Web Pages site templates is Forms Authentication via the SimpleMembershipProvider, which is designed to enable authentication of users against a database. This requires the user to know their user name and password, and to enter those whenever they want to log in to access restricted areas within a site. If you are using the ASP.NET Web Pages framework to build an Intranet site that will be hosted within your own corporate network (i.e. client machines and web server are in the same domain), you can use Integrated Windows Authentication instead which simplifies authentication dramatically.

Integrated Windows Authentication is the preferred approach to authentication whenever users are part of the same Windows domain as the server. Users are authenticated against an existing identity store such as Active Directory, and their credentials are not transmistted across the Internet. In addition, users are provided with a seamless experience, as they only need to log in to Windows, and their browser and IIS take care of managing authentication from then on. There are a number of alternatives to Integrated Windows Authentication: Basic, Digest and Client Certificate, but only Integrated Windows Authentication provides strong authentication without the hassle of managing client certificates. It is therefore the recommended option.

Configuring Integrated Windows Authentication is quite straightforward, but there are a number of steps that need to be followed. The first step is to change the web.config file to specify that Windows Authentication is to be used for the site:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="EnableSimpleMembership" value="false" />
    </appSettings>

    <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <authentication mode="Windows" />

    </system.web>
</configuration>

There are three items to note: first, an appSettings entry is added to turn off SimpleMembership, which relies on Forms Authentication. Then, within the system.web node, the authentication mode is set to Windows.

The next step is to ensure that your web server is set up to manage Windows Authentication for the site. To do this, you need to explicitly disable anonymous access (which allows anyone to access the site withoiut havng to authenticate) and enable Windows Authentication. WebMatrix doesn’t offer any GUI management tools for IIS Express, so you need to locate the applicationhost.config file (typically located in C:\Users\<your_username>\Documents\IISExpress\config). Having done that, navigate all the way to the bottom where you should find the closing </configuration> tag. Add the following, where «Windows Auth» is the name of your site:

	<location path="Windows Auth">
        <system.webServer>
            <security>
                <authentication>
                    <anonymousAuthentication enabled="false" />
                    <windowsAuthentication enabled="true" />
                </authentication>
            </security>
        </system.webServer>
    </location>
</configuration> <-- left in to help with positioning -->

Visual Studio Express for Web does provide a visual means to manage these settings: you can configure them with two clicks in the site properties:

Windows Authentication

There is an alternative way to disable anonymous access to the site, and that is to add the following to your web.config file within the system.web node:

<authorization>
    <deny users="?"/>
</authorization>

When you deploy the site to the full version of IIS, you can use the standard IIS administrative tools to manage configuration. First, you need to ensure that Windows Authentication is enabled for the web server. You can do this by going to Control Panel » Programs and Features, and then clicking Turn Windows features on or off (left hand side). Locate Internet Information Services and then drill down to Security and ensure that Windows Authentication is checked.

Windows Auth in IIS

Once you have created the site in IIS, go to Feature View and click Authentication:

Windows Authentication in IIS

Make sure that the options are the same as you set in IIS Express: Anonymous Authentication should be disabled, and Windows Authentication enabled.

Windwos Authentication IIS

Working with users and roles

Users are logged in automatically and their identity is stored in the Identity property of the User object. The User object is an instance of the IPrincipal interface. The underlying type is the WindowsPrinciple class. You can get the name of the user from User.Identity.Name. The value returned from this is in the form DomainName\UserName or MachineName\UserName. For example, if I have a Windows login for a domain called CONTOSO01, the value returned by User.Identity.Name might be CONTOSO01\mikebrind.

Some parts of the Intranet might only be accessible to members of certain Windows groups (roles) such as Administrator or Sales. In order to determine whether the current user belongs to a specific group, you use the User.IsInRole method:

@if(User.IsInRole(@"BUILTIN\Administrators") || User.IsInRole(@"DOMAIN\Sales")){
    <div>Is an administrator or sales person</div>
}

You can also use an override of the IsInRole method that takes a WindowsBuiltInRole enumeration, although you have to cast the User object to a WindowsPrincipal to use this option:

@using System.Security.Principal;
@{
    var user = (WindowsPrincipal)User;
    if(user.IsInRole(WindowsBuiltInRole.Administrator)){
        //user is an administrator
    }
}

Note that you also need to add a using directive to reference the System.Security.Principal namespace. Enumerations are good, in that Intellisense offers code completion and compile time checking, but you can’t use this approach to test for membership of custom groups that you have created such as the Sales one illustrated earlier.

You can’t do very much with groups or roles when using Windows Authentication. However, you can activate theWindowsTokenRoleProvider if you do need to make use of its limited features. To do this, add the following to your web.config within the system.web node:

<roleManager enabled="true" defaultProvider="WindowsProvider">
    <providers>
        <clear />
        <add name="WindowsProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
    </providers>
</roleManager>

The first thing to point out is that if you enable this feature, you can no longer use the WindowsBuiltInRole enumeration option with the User.IsInRole method because the underlying type for User has now become a RolePrincipal type, which cannot be converted to WindowsPrincipal. You can continue to use the User.IsInRole method that accepts a string, or you can use the Roles.IsUserInRole(string, string) method, that takes the user name and the role to check against. The only other meaningful method exposed by the WindowsTokenRoleProvider is the GetRolesForUser method which returns an array of roles:

@foreach(var role in Roles.GetRolesForUser()){
    <div>User belongs to @role</div>
}

Unless you actually need to use this method, there seems little point in activating the RoleManager for your intranet site.

Usar autenticacion windows en aplicaciones .NET

Para usar autenticacion Windows se deben de realizar minimo dos pasos

1.- Configurar el modo de la aplicacion web como windows

<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Windows"></authentication>
<authorization>
<allow users="megarep\vorellana"/>
<deny users="*"/>
</authorization>
</system.web>

2.- Configurar servidor IIS

Windows Auth in IIS

Windows Authentication in IIS

Windwos Authentication IIS

Resolver conflictos entre jquery y ASP NET (Update Panels)

Conflicts between ASP.NET AJAX UpdatePanels & jQuery functions

In one of my previous posts dealing with the jQuery DatePicker , a user commented reporting an issue where he uses the jQuery DatePicker and ASP.NET AJAX UpdatePanels.

He says: On the same control that I have the date picker, I also have an ajax update panel, with sync as well as asych triggers. The date pick works before I trigger any ajax, and doesn’t work after. Any clue of a workaround here?

Only two hours after his comment, I’ve replied with solution that I’ve used previously in one of my testing projects since I already experienced the same issue with some JavaScript functions previously.

So, once you see the issue, you will think that ASP.NET AJAX UpdatePanels does not like the other jQuery functions within the page. Hmm… it seems true, because after partial post-back has been made by the ASP.NET AJAX UpdatePanel, the JavaScript event handlers are lost.

First of all, we should avoid mixing different JavaScript libraries or frameworks because we may always have some issues when they override some of the default functions they use or some other conflicts that even we cannot think of. Also, both jQuery and ASP.NET Ajax use the dollar ($) sign in different context, which might be an issue when mixing both of the technologies on a single page.

Well, in order to reproduce the problem, lets pass trough the following steps:

1. Add reference to the jQuery library. If you don’t have the library on your local machine, you can reference it from the Microsoft Content Delivery Network (CDN)

<script src=»http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js» type=»text/javascript»></script>
2. The ASPX code – ScriptManager, UpdatePanel, Label and Button

<div>
<asp:ScriptManager ID=»ScriptManager1″ runat=»server»>
</asp:ScriptManager>
<asp:UpdatePanel ID=»UpdatePanel1″ runat=»server»>
<ContentTemplate>
<asp:Label runat=»server» ID=»lblText» />
<br />
<asp:Button ID=»btnClick» runat=»server» Text=»Click Me» OnClick=»btnClick_Click» />
</ContentTemplate>
</asp:UpdatePanel>
<br /><br />
<%= DateTime.Now %>
<!– the Date time won’t change on button click since its outside of the update panel –>
</div>

3. The jQuery function that will show an Alert when clicking on the Button

<script language=»javascript» type=»text/javascript»>
$(function () {
$(«#btnClick»).click(function () {
//will run on btnClick, which is inside the UpdatePanel
alert(«Alert: Hello from jQuery!»);
});
});
</script>

4. The server-side C# code that will run when the partial post back occurs, on button click event

protected void btnClick_Click(object s, EventArgs e)
{
lblText.Text = «Hello from the Server! Current Date&Time: » + DateTime.Now;
}

 

As you can see, I have mixed both technologies, the ASP.NET AJAX UpdatePanels and the jQuery that has event bound to the button inside the UpdatePanel.

Once we run the website, here is what happens:

–  The website runs and the following screen will show up

– Click on the “Click Me” button and the following alert message will pop up (the jQuery function is called)

– Right after the client-side code is executed, the UpdatePanel will trigger partial postback event to the server and the result will be

– Now, we click the “Click Me” button again, but there is no Alert message anymore, even though we were expecting the alert. Partial postback has been done again and the server returns new message (see the date time difference)

The problem is reproduced, now lets explain what has happened.

After the page was loaded for first time, everything seems ok. The jQuery function waits till the DOM is fully loaded and then binds its event to the button click. However, the button is inside ASP.NET Ajax UpdatePanel which’s content will get reloaded once the partial post-back is triggered, which actually causes the event handlers to get lost.

 

I’ve seen few blogs where developers have posted some workarounds. I will post three different methods to resolve this so that you can use the one which seems more suitable for your application.

Method 1

The first method is by using the PageRequestManager. With the request manager, we can add an End Request event handler once the page has loaded after the partial post back is finished.

Here is how:

We need to write additional two JavaScript functions

load() – which will add the End Request event using the Page Request Manager and will register the jsFunctions function

jsFunctions() function which will reload the jQuery functions

<script language=»javascript» type=»text/javascript»>
function load() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(jsFunctions);
}
function jsFunctions() {
$(«#btnClick»).click(function () {
alert(«Alert: Hello from jQuery!»);
});
}
</script>

and we need to add

<body onload=»load()»>

which will call the load() function once the onload event occurs.

 

 

Method 2

ASP.NET Ajax has one pageLoad() method which invokes the Sys.Application.load load event. Think of the pageLoad() event similar to the Page_Load server-side event that runs on code-behind in server. Only the pageLoad() event runs on client-side, everytime the page is reloaded (no matter if the reload is full or partial). If we put the script inside this event, it will avoid all the conflicts that happen between ASP.NET Ajax and the jQuery because it will rebind the scripts every time the page will do post-back.

<body>
<script language=»javascript» type=»text/javascript»>
function pageLoad()
{
$(function () {
$(«#btnClick»).click(function () {
alert(«Alert: Hello from jQuery!»);
});
});
}
</script>

This seems definitely better than the first method since its more clear, you don’t need to create additional functions that will run on end request and you don’t need to add onload event to the body element.

 

Method 3

I won’t show anything new in this third method, but, I will show a way how to register the script from method 2 on server-side.

protected void Page_Load(object sender, EventArgs e)
{
//I’ve formatted the JS function to be more readable 😉
string javaScriptFunction =
«function pageLoad() {» +
«$(function () {» +
«$(‘#btnClick’).click(function () {» +
«alert(‘Alert: Hello from jQuery!’);» +
«});» +
«});» +
«}»;
ClientScript.RegisterStartupScript(this.GetType(), «myScript», javaScriptFunction, true);
}

I have added the script in the javaScriptFunction string, but you can add your scripts in an external JavaScript (.js) file and reference it using ClientScript.RegisterClientScriptInclude() function, so in such case we will have:

protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptInclude(this.GetType(), «myScript», «Scripts/javaScriptFile.js»);
}

where the Scripts/javaScriptFile.js is the script file.

Note: There are some other methods too, such as using the jQuery live() function.

 

COMPLETE CODE

Here is the complete code implemented as in Method 2 with commented code lines for the last method with the server-side code.

<%@ Page Language=»C#» %>

<!DOCTYPE html PUBLIC «-//W3C//DTD XHTML 1.0 Transitional//EN» «http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd»>

<html xmlns=»http://www.w3.org/1999/xhtml»>
<head id=»Head1″ runat=»server»>
<title>Conflicts between ASP.NET AJAX Update Panels & JavaScript/jQuery functions</title>
<script src=»http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js» type=»text/javascript»></script>
</head>
<body>
<script language=»javascript» type=»text/javascript»>
function pageLoad() {
$(function () {
$(«#btnClick»).click(function () {
alert(«Alert: Hello from jQuery!»);
});
});
}
</script>
<form id=»form1″ runat=»server»>
<div>
<asp:ScriptManager ID=»ScriptManager1″ runat=»server»>
</asp:ScriptManager>
<asp:UpdatePanel ID=»UpdatePanel1″ runat=»server»>
<ContentTemplate>
<asp:Label runat=»server» ID=»lblText» />
<br />
<asp:Button ID=»btnClick» runat=»server» Text=»Click Me» OnClick=»btnClick_Click» />
</ContentTemplate>
</asp:UpdatePanel>
<br /><br />
<%= DateTime.Now %>
<!– the Date time won’t change on button click since its outside of the update panel –>
</div>
<script runat=»server»>
protected void Page_Load(object sender, EventArgs e)
{
#region if you want to use your script in server side, uncomment the code inside this region
/*
string javaScriptFunction =
«function pageLoad() {» +
«$(function () {» +
«$(‘#btnClick’).click(function () {» +
«alert(‘Alert: Hello from jQuery!’);» +
«});» +
«});» +
«}»;

ClientScript.RegisterStartupScript(this.GetType(), «myScript», javaScriptFunction, true);
*/
#endregion

#region if you have your JS script in an external file and want to reference it, uncomment the following line
//ClientScript.RegisterClientScriptInclude(this.GetType(), «myScript», «Scripts/javaScriptFile.js»);
#endregion
}

protected void btnClick_Click(object s, EventArgs e)
{
lblText.Text = «Hello from the Server! Current Date&Time: » + DateTime.Now;
}
</script>
</form>
</body>
</html>

So, that’s it.

Even though the implementation is pretty simple, I made this blog post quite long in order to explain the details with trying not to get out of the problem boundaries.

I would like to note that I’m a big fun and I work a lot with both, the Microsoft ASP.NET Ajax and the jQuery library.

I hope this was helpful.

Kind Regards,
Hajan

Utilizar jquery ui con ASP .NET

Colocando esta linea de codigo funcionó los componentes de jquery ui con .NET

html aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AsistenteVentas.aspx.cs" Inherits="Mantenimientos.AsistenteVentas" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title></title>
 <link href="css/custom.css" rel="stylesheet" />
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
 <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" />
 <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
 <script type="text/javascript">
 function InIEvent()
 {
 $(function () {
 var xdialog;
xdialog = $('#BuscaPersonal').dialog({
 modal: true,
 autoOpen: false,
 height: 300,
 width: 650
 });
$('#xbtn_buscar').on('click', function () {
 xdialog.dialog('open');
 $('#hddorigen').val('ASISTVTA');
 });
xdialog.parent().appendTo($('form:first'));
 });
 }
$(document).ready(InIEvent);
 
 </script>
<body>
 <form id="form1" runat="server">
 <asp:ScriptManager runat="server"></asp:ScriptManager>
 <script type="text/javascript">
 Sys.WebForms.PageRequestManager.getInstance().add_endRequest(InIEvent);
 </script>
 <div class="contenido">
 <h2>Asistentes de Ventas</h2>
 <div>
 <div>
 <table>
 <tr>
 <td> 
 <asp:ImageButton ID="btnNuevoAsisVta" runat="server" ImageUrl="~/img/nuevo.png" Width="16px" OnClick="btnNuevoAsisVta_Click" />
 </td>
 </tr>
 </table>
 </div>
 <%-- Panel de mantenimiento de asistentes de ventas --%>
 <asp:UpdatePanel ID="updpnlMtoAsistVta" runat="server" UpdateMode="Conditional">
 <ContentTemplate>
 <asp:Panel ID="pnlmtoAsistVta" runat="server">
 <table class="form-tabla">
 <tr>
 <td>Codigo</td>
 <td>:</td>
 <td><asp:TextBox ID="txtcodigoAsistvta" runat="server" ReadOnly="true" Width="50px"></asp:TextBox></td>
 <td><img src="img/search.png" width="32" alt="" id="xbtn_buscar" class="img-boton" /></td>
 </tr>
 <tr>
 <td>Nombres y Apellidos</td>
 <td>:</td>
 <td colspan="2"><asp:TextBox ID="txtnomyape" runat="server" ReadOnly="true" Width="200px"></asp:TextBox></td>
 </tr>
 <tr>
 <td>Correo Electrónico</td>
 <td>:</td>
 <td colspan="2"><asp:TextBox ID="txtcorreo" runat="server" ReadOnly="true" Width="200px"></asp:TextBox></td>
 </tr>
 <tr>
 <td>L&iacute;nea</td>
 <td>:</td>
 <td colspan="2"><asp:DropDownList ID="ddl_linea" runat="server" Width="150px"></asp:DropDownList></td>
 </tr>
 <tr class="form-fila-botones">
 <td colspan="2"><asp:ImageButton ID="btnguardarAsisVta" runat="server" ImageUrl="~/img/save.png" Width="32" /></td>
 <td colspan="2"><asp:ImageButton ID="btnregresarAsisVta" runat="server" ImageUrl="~/img/back.png" Width="32" OnClick="btnregresarAsisVta_Click" /></td>
 </tr>
 </table>
 <asp:Label ID="lblmensaje1" runat="server"></asp:Label>
 </asp:Panel>
 </ContentTemplate>
 <Triggers>
 <asp:AsyncPostBackTrigger ControlID="btnguardarAsisVta" EventName="Click" />
 <asp:AsyncPostBackTrigger ControlID="btnregresarAsisVta" EventName="Click" />
 <asp:AsyncPostBackTrigger ControlID="btnNuevoAsisVta" EventName="Click" />
 </Triggers>
 </asp:UpdatePanel>
<div> 
 <%-- Grilla de asistentes de ventas --%>
<asp:GridView ID="gvAsistentes" runat="server" AutoGenerateColumns="False">
 <Columns>
 <asp:TemplateField HeaderText="ID"> 
 <ItemTemplate>
 <asp:LinkButton ID="lnkID" runat="server" Text='<%# Eval("codigo").ToString() %>'></asp:LinkButton>
 </ItemTemplate>
 </asp:TemplateField>
 <asp:BoundField DataField="linea" HeaderText="Linea" />
 <asp:BoundField DataField="nombres" HeaderText="Nombres y Apellidos" />
 <asp:BoundField DataField="correo" HeaderText="Correo electronico" />
 <asp:TemplateField>
 <ItemTemplate>
 <asp:ImageButton ID="btneliminar" runat="server" ImageUrl="~/img/eliminar.png" Width="16" /> 
 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
 </asp:GridView>
 </div>
 <div id="BuscaPersonal" class="widget" title="Busqueda de personal">
 <div>
 <%-- LA BUSQUEDA DE PERSONAL --%>
 <asp:Panel ID="pnl_buscar" runat="server" DefaultButton="btn_buscar">
 <table class="form-tabla">
 <tr>
 <td>Ingrese nombres o correo electrónico</td>
 <td>:</td>
 <td><asp:TextBox ID="txtbuscar" runat="server" Width="300px"></asp:TextBox></td>
 <td><asp:ImageButton ID="btn_buscar" runat="server" ImageUrl="~/img/search.png" Width="32" OnClick="btn_buscar_Click" /></td>
 </tr>
 </table> 
 </asp:Panel>
 </div>
 <asp:UpdatePanel ID="upd1" runat="server" UpdateMode="Conditional">
 <ContentTemplate>
 <asp:GridView ID="gvpersonal" runat="server" AutoGenerateColumns="False" CssClass="grid-net" >
 <Columns>
 <asp:TemplateField HeaderText="Codigo"> 
 <ItemTemplate>
 <asp:LinkButton ID="lnkpersonal" runat="server" Text='<%# Eval("CodigoPersona").ToString() %>'></asp:LinkButton>
 </ItemTemplate>
 </asp:TemplateField>
 <asp:BoundField DataField="NombresApellidos" HeaderText="Nombres y Apellidos" />
 <asp:BoundField DataField="CorreoElectronico" HeaderText="Correo electronico" />
 </Columns>
 </asp:GridView> 
 <asp:HiddenField ID="hddorigen" runat="server" /> 
 </ContentTemplate>
 <Triggers>
 <asp:AsyncPostBackTrigger ControlID="btn_buscar" EventName="Click" />
 </Triggers>
 </asp:UpdatePanel> 
 <div>
</div>
 </div>
<div>
 <%-- LA BUSQUEDA DE PERSONAL --%>
 <h3>Personal de Ventas</h3>
 <div>
 <table>
 <tr>
 <td><asp:ImageButton ID="img_nuevo_vta" runat="server" ImageUrl="~/img/nuevo.png" Width="16px" /></td>
 </tr>
 </table>
 </div>
 <div>
 <asp:GridView ID="gv_ventas" runat="server" AutoGenerateColumns="False">
 <Columns>
 <asp:BoundField DataField="codigo" HeaderText="Codigo" />
 <asp:BoundField DataField="nombres" HeaderText="Nombres y Apellidos" />
 <asp:BoundField DataField="correo" HeaderText="Correo electrónico" />
 <asp:TemplateField>
 <ItemTemplate>
 <asp:ImageButton ID="img_eliminar_vta" runat="server" ImageUrl="~/img/eliminar.png" Width="16px" />
 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
 </asp:GridView>
 </div>
 </div>
 <div>
 <table>
 <tr>
 <td>
</td>
 </tr>
 </table>
 </div>
 </div>
 </div>
 </form>
</body>
</html>

Codigo C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DTO;
using ENT;

namespace Mantenimientos
{
 public partial class AsistenteVentas : System.Web.UI.Page
 {
 protected void Page_Load(object sender, EventArgs e)
 {
 if (!(Page.IsPostBack))
 {
 DTOAsistVta obj = new DTOAsistVta();
 List<ENTLinea> lstLinea = obj.ListarLineas();

 if (lstLinea.Count == 1 && lstLinea[0].Mensaje != null)
 {
 ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", string.Format("alert('Ha ocurrido un error: {0}", lstLinea[0].Mensaje), true);
 return;
 }

 this.ddl_linea.DataSource = lstLinea;
 this.ddl_linea.DataTextField = "NombreLinea";
 this.ddl_linea.DataValueField="CodigoLinea";
 this.DataBind();

 this.ddl_linea.Items.Insert(0, new ListItem("...Seleccione", "0"));
 //this.pnlmtoAsistVta.Style.Add(HtmlTextWriterStyle.Display, "none");
 this.pnlmtoAsistVta.Visible = false;
 }
 }

 protected void btn_buscar_Click(object sender, ImageClickEventArgs e)
 {
 DTOAsistVta obj = new DTOAsistVta();

 List<ENTPersona> lstpersona = obj.ListarColaboradores(this.txtbuscar.Text.Trim());
 
 //Verificando que no haya error

 if (lstpersona.Count == 1 && lstpersona[0].Mensaje != null)
 {
 ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", string.Format("alert('Ha ocurrido un error: {0}", lstpersona[0].Mensaje), true);
 return;
 }

 this.gvpersonal.DataSource = lstpersona;
 this.gvpersonal.DataBind();
 }

 protected void btnNuevoAsisVta_Click(object sender, ImageClickEventArgs e)
 {
 //this.pnlmtoAsistVta.Style.Add(HtmlTextWriterStyle.Display, "inline");
 this.pnlmtoAsistVta.Visible = true;
 }

 protected void btnregresarAsisVta_Click(object sender, ImageClickEventArgs e)
 {
 this.pnlmtoAsistVta.Visible = false;
 }


 }
}

No ejecutan controles de servidor ASP.NET con Jquery UI

Hay que agregar la ultima linea luego de configurar el dialog jqueryui

jQuery(function() {
    var dlg = jQuery("#dialog").dialog({
                         draggable: true,
                         resizable: true,
                         show: 'Transfer',
                         hide: 'Transfer',
                         width: 320,
                         autoOpen: false,
                         minHeight: 10,
                         minwidth: 10
                     });
    dlg.parent().appendTo(jQuery("form:first"));
})

Solucion error WCF IIS: Memoria disponible menor al 5%

El detalle del error mostrado por IIS es:

Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InsufficientMemoryException: Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element

Se ha solucionado añadiendo las siguientes lineas en el web config de la aplicación

<system.serviceModel> 
    <serviceHostingEnvironment minFreeMemoryPercentageToActivateService="0" />
</system.serviceModel> 

Encryptar / Desencryptar QueryString ASP NET

HTML Markup
Page 1
The following HTML Markup consists of a TextBox, a DropDownList and a Button. The value from the TextBox and the DropDownLists will be encrypted and send using QueryString Parameters to the next page on Button click.
<table border=»0″ cellpadding=»0″ cellspacing=»0″>
    <tr>
        <td>
            Name:
        </td>
        <td>
            <asp:TextBox ID=»txtName» runat=»server» Text=»Mudassar Khan» />
        </td>
    </tr>
    <tr>
        <td>
            Technology:
        </td>
        <td>
            <asp:DropDownList ID = «ddlTechnology» runat=»server»>
                <asp:ListItem Text=»ASP.Net» Value = «ASP.Net» />
                <asp:ListItem Text=»PHP» Value = «PHP» />
                <asp:ListItem Text=»JSP» Value = «JSP» />
            </asp:DropDownList>
        </td>
    </tr>
</table>
<hr />
<asp:Button ID=»Button1″ Text=»Submit» runat=»server» OnClick = «Submit» />
 
Page 2
The following HTML Markup consists of two Label controls which will be used to display the QueryString Parameter values received on the page.
<table border=»0″ cellpadding=»0″ cellspacing=»0″>
    <tr>
        <td>
            Name:
        </td>
        <td>
            <asp:Label ID=»lblName» runat=»server» Text=»» />
        </td>
    </tr>
    <tr>
        <td>
            Technology:
        </td>
        <td>
            <asp:Label ID=»lblTechnology» runat=»server» Text=»» />
        </td>
    </tr>
</table>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Text;
using System.Security.Cryptography;
VB.Net
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
 
 
AES Algorithm Encryption and Decryption functions
Below are the functions for Encryption and Decryption which will be used for the Encrypting or Decrypting QueryString Parameter Values.
Note: The following functions have been explained in the article AES Encryption Decryption (Cryptography) Tutorial with example in ASP.Net using C# and VB.Net
 
 
Encrypting the QueryString Parameter Values
When the Button is clicked the following event handler is executed. Here the values of the TextBox and the DropDownList are first encrypted using the AES Symmetric Key Algorithm and then encoded using the UrlEncode method of the HttpUtility class. Finally these values are sent as QueryString Parameters to the next page.
Note: Here Encoding is required as the Encrypted string contains special characters and it is necessary to encode special characters before sending them as QueryString parameter.
C#
protected void Submit(object sender, EventArgs e)
{
    string name = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim()));
    string technology = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value));
    Response.Redirect(string.Format(«~/CS2.aspx?name={0}&technology={1}», name, technology));
}
private string Encrypt(string clearText)
{
    string EncryptionKey = «MAKV2SPBNI99212»;
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(ms.ToArray());
        }
    }
    return clearText;
}
 
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
    Dim name As String = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim()))
    Dim technology As String = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value))
    Response.Redirect(String.Format(«~/VB2.aspx?name={0}&technology={1}», name, technology))
End Sub
Private Function Encrypt(clearText As String) As String
    Dim EncryptionKey As String = «MAKV2SPBNI99212»
    Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText)
    Using encryptor As Aes = Aes.Create()
        Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
         &H65, &H64, &H76, &H65, &H64, &H65, _
         &H76})
        encryptor.Key = pdb.GetBytes(32)
        encryptor.IV = pdb.GetBytes(16)
        Using ms As New MemoryStream()
            Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
                cs.Write(clearBytes, 0, clearBytes.Length)
                cs.Close()
            End Using
            clearText = Convert.ToBase64String(ms.ToArray())
        End Using
    End Using
    Return clearText
End Function
 
 
Decrypting the QueryString Parameter Values
In the Page Load event of the page, the values of the TextBox and DropDownList sent from the previous page are first fetched from the QueryString Parameters and then are decoded using the UrlDecode method of the HttpUtility class.
After decoding the string is decrypted using the AES Symmetric Key Algorithm and then the decrypted values are displayed using Label controls.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString[«name»]));
        lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString[«technology»]));
    }
}
private string Decrypt(string cipherText)
{
    string EncryptionKey = «MAKV2SPBNI99212»;
    cipherText = cipherText.Replace(» «, «+»);
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString(«name»)))
        lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString(«technology»)))
    End If
End Sub
Private Function Decrypt(cipherText As String) As String
    Dim EncryptionKey As String = «MAKV2SPBNI99212»
    cipherText = cipherText.Replace(» «, «+»)
    Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText)
    Using encryptor As Aes = Aes.Create()
        Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
         &H65, &H64, &H76, &H65, &H64, &H65, _
         &H76})
        encryptor.Key = pdb.GetBytes(32)
        encryptor.IV = pdb.GetBytes(16)
        Using ms As New MemoryStream()
            Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)
                cs.Write(cipherBytes, 0, cipherBytes.Length)
                cs.Close()
            End Using
            cipherText = Encoding.Unicode.GetString(ms.ToArray())
        End Using
    End Using
    Return cipherText
End Function
 

Encrypt and Decrypt QueryString Parameter Values in ASP.Net using C# and VB.Net

Encrypt and Decrypt QueryString Parameter Values in ASP.Net using C# and VB.Net