неделя, 25 септември 2011 г.

"Access Denied" error when writing into Event Log

When EventLog.WriteEntry(...) is used to write a log record in specific event log a pretty common error is the "Access Denied" message. That means you need to grant access to the user account that's been used by your Application pool. The account your web application uses to run is in "Internet Information Services (IIS) Manager -> Application Pools -> Your web Application Pool -> Advanced Settings -> Identity".
You need to give this user Read/Write permissions in the Log that you are trying to write into.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\YourLogName
It's accessible by the Register Editor.
The usual accounts that ASP.NET uses are NETWORK SERVICE (in WinSrv2003/2008 and Win7,Vista) and ASPNET in WinXP.

петък, 21 януари 2011 г.

Bind DataTable To GridView using TemplateFields ASP.NET

You have a DataTable object with data filled from your database. There is a "how to" here

In the *.aspx page:
<asp:GridView id="gViewSample"  runat="server">
<Columns>
<asp:TemplateField  ItemStyle-CssClass="GridItemClass">
<ItemTemplate>
<asp:Button ID="btnItem" runat="server" Text='<%# Eval("Item_id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField  ItemStyle-CssClass="GridItemClassDescription">
<ItemTemplate>
<asp:Label ID="lblItemDescription" runat="server" Text='<%# GetItemDescription(Container.DataItem) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

In the Code behind (C#)
protected string GetItemDescription(object dataItem)
{
    strint itemDescription = DataBinder.Eval(dataItem, "Description").ToString();
    // here is where you do some manipulation with the field data.
    return itemDescription;
}

In your *.css file you put styles for the header/item/footer templates
.Griditemclass
{
width: 70px;
color: Black;
/* etc. etc. */
}

The binding itself:
protected void Page_Load(object sender, EventArgs e)
{
    gViewSample.DataSource = dt;
    gViewSample.DataBind();
}
--------------------------------------------
The Template fields: you can get data there either directly from the DataTable using Eval("FieldName") either by function in the code behind (like GetItemDescription) if you need to manipulate your data. You put your css classes in an external file.

четвъртък, 20 януари 2011 г.

How to Store ASP.NET Sessions in MSSql Database


Change the settings inside the session tag in your application web.config file:

<sessionState allowCustomSqlDatabase="true" cookieless="UseCookies" cookieName="HTTP_COOKIE" mode="SQLServer"
    regenerateExpiredSessionId="true" sqlConnectionString="data source=ServerName\SqlInstance;
    DataBase=dbName;Integrated Security=True" stateConnectionString="tcpip=127.0.0.1:42424"
    stateNetworkTimeout="20" timeout="500" />

Open the Command Prompt, go to "C:\Windows\Microsoft.NET\Framework\v2.0.50727" 
and run this command:  
aspnet_regsql.exe -S <Server\Instance> -U <Username> -P <Password> -ed -d <DataName>  
 
After this command, two tables (ASpStateTempApplications and ASPStateTempSessions
are created in the selected database as well as several stored procedures and sql job for 
deleting/updating/inserting sessions in the tables. The SQL account you used in this 
command must also have rights to make changes on the database, otherwise you get an 
"no execute permission" error. You can check the settings you just set in the web.config 
file in the IIS "Session State" section - they should be the same. In this scenario you 
have 500 minutes timeout of your session cookies. You have regenerateExpiredSessionId 
set to "True" which means that any postback made by the user updates the record in the 
database and changes the expiration time of your session record.

Get Data From MS SQL Database with ADO.NET C#

In the code-behind you have: 
-------------------------------
using System.Data.SqlClient;
using System.Data;
string yourSqlQuery = "SELECT ID, Decsription FROM Articles Where ManufacturerName = @ParamName";
string connString = "Data Source=ServerName\\SqlInstance;Database=dbName;User=UserAcc;password=Pwd;Integrated Security=False";

SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(yourSqlQuery, conn);
cmd.Parameters.AddWithValue("@ParamName", "paramValue");
if (conn.State != ConnectionState.Open)
    conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
------------------------------
Note: Account "UserAcc" used to run the query needs permissions in the SqlServer -> Security -> Logins. In case you use Integrated Security=True you actually use Network Services account (or ASPNET in Win XP) and should consider granting necessary permissions. Have in mind that firewalls, routers can also block your connection to the SqlServer.

Capture Enter Key in Textbox with JavaScript


In the code behind (*.cs file) you have to attach the event handler:
protected void Page_Load(object sender, EventArgs e)
{
textField.Attributes.Add("onkeypress", "return textBoxOnKeyDown(this);");
textField.Attributes.Add("onkeydown", "return textBoxOnKeyDown(this);");
}
The JavaScript (in the *.js file) for the event handler:
<script type="text/javascript">
<!--
function textBoxOnKeyDown(elementRef)
{
 var keyCodeEntered = (event.which) ? event.which : (window.event.keyCode) ? window.event.keyCode : -1;
 if ( keyCodeEntered == 13 )
 {
  <%= ClientScript.GetPostBackEventReference(testAnchor, string.Empty) %>;
  return false;
 }
 return true;
}
// -->
</script>


Note: "onkeypress" event works with IE 6+, Chrome, Opera while onkeydown works with Mozilla. You can add any key value (Enter key is '13') and try to make a more complex javascript function depending on your needs.