Saturday, 31 December 2011

VB.NET - LINQ query to get list of files and bind to DataGridView


Cheat sheet to Convert an ArrayList to a DataTable

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
                'get files from current directory
        Dim Files = From file In My.Computer.FileSystem.GetFiles(CurDir)
                    Order By file
                    Select file
'returns IEnumerable of FileInfo object that contains file information
        Dim Filesinfo = From File In Files Select My.Computer.FileSystem.GetFileInfo(File)
        'Bind to grid
        'ToList() is to get FileInfo
        DataGridView1.DataSource = Filesinfo.ToList()      
    End Sub

ASP.NET - Send Email in C#.NET


Sending Email in ASP.NET
using System.Net.Mail;
protected void imgbtnSendEmail_Click(object sender, EventArgs e)
        {
            MailMessage Msg = new MailMessage();
            Msg.To = txtTo.Text;
            Msg.From = txtFrom.Text;
            Msg.Cc = txtCc.Text;
            Msg.Subject = "SyntaxHelp Welcomes You";
            Msg.objEmail.Body = txtBody.Text;
            Msg.Priority = MailPriority.High;
            Msg.BodyFormat = MailFormat.Html;
            Msg.Attachments.Add(Server.MapPath("SyntaxHelp.doc"));
            //Notifies if delivery of e-mail is success
            DeliveryNotificationOptions= DeliveryNotificationOptions.OnSuccess
            SmtpClient client = new SmtpClient("localhost");

            client.Timeout = 500;
            try
            {
                client.Send(Msg);
                Response.Write("Your Email has been sent sucessfully");
            }
            catch (Exception exc)
            {
                Response.Write(" Send Email fails: " + exc.ToString());
            }
        }

Change web.config settings to Configure SMTP
     <system.net>
   <mailsettings>
     <smtp from="syntaxhelp@syntaxhelpdomain.com">
       <network host="somesmtpserver" port="25" username="name" password="pass" defaultcredentials="true">
     </network></smtp>
   </mailsettings>
</system.net>

If the price of the product is less than 90 then change the cell color in GridView


  
//Fires after every row data bound
  protected void gvCities_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // Checking if row type
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // find the label control
            Label lblPrice = e.Row.FindControl(“lblPrice”) as Label;

            // read the value from the datasoure
            Double Price = Convert.ToDouble(Convert.ToString(DataBinder.Eval(e.Row.DataItem, “Rate”)));

            if (Price < 90.00)
            {
                // get the cell where that label contains
                DataControlFieldCell d = lblPrice.Parent as DataControlFieldCell;

                // to change the backcolor
                d.BackColor = System.Drawing.Color.Blue;

                // to change the row color by setting
                e.Row.BackColor = System.Drawing.Color.Red;

                // to change the text color like this
                lblPrice.ForeColor = System.Drawing.Color.Green;
             }
        }
   }


Monday, 26 December 2011

How to get the primary key value of the GridView rows in JavaScript or popup page?


.Aspx page
<asp:GridView ID="GridView1" runat="server" EnableViewState="false" DataKeyNames="AutoId">
<Columns>
<asp:TemplateField HeaderText="Details">
<ItemTemplate>
<a href="javascript:void(0)" title="Click for more details"
onclick="OpenPopup('<%# Eval("AutoId") %>')">Details</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<script language="javascript" type="text/javascript">
function OpenPopup(autoid) {
alert("AutoId: " + autoid);
window.open("dummyPage.aspx?autoid=" + autoid, "", "width=300,height=200");
}
</script>

Dispalying selected value of RBL Control

Design: 

<asp:radiobuttonlist id="rblGender" runat="server">
<asp:listitem text="Male"/>
<asp:listitem text="FeMale"/>
<asp:Radiobuttonlist>
Javascript: 


function ShowSelectedGender()
{
var Gen=document.getelementbyid("rblGender");
for(var i=0;i<Gen.cells.length;i++)
{
if(Gen.cells.firstChild.checked)
{
alert("You've selected Gender is:"+Gen.cells.firstChild.value);
}
}
}
.cs
page Load call Javascript
{
btnsubmit.attribure.add("onClick","ShowSelectedGender()");
}

Thursday, 15 December 2011

Understanding Session



A session is defined as a period of time that is shared between the web application and the user. Each user that is using the web application has their own session. Items/Objects can be placed into the Session which would only define these object for that user. Session contains key variables which help to identify the related values. This can be thought of as a hash table. Each user would represent a different key node in the hash identifying unique values. The Session variables will be clear by the application which can clear it, as well as through the timeout property in the web config file.

A practical example would be a web application where a user logs into. Each user that logs into your system will have a unique session. We can hold additional data into the session which can be used as the user browses your site. We can hold the first name, last name, and other data simply by adding it to the session:

Session[“FirstName”] = “User First Name”;
Session[“LastName”] = “User Last Name”;

We can clear the session variable by doing the following:

Session[“FirstName”] = null;

We can clear all Session variables by dong the following:

Session.Abandon();

A Session variable should be used with respect to the individual user. It stores the information on the server side and should not be taken advantage of. The difference between the cache and session is that the cache is available to be accessed from the global/application level where one reference to memory is updated. Each request will use the same cache for different users. Session variables will use different session variables for each different user. Usually a large amount of data can be stored on the session, however web sites that have a large amount of traffic usually would not use this method, as it would put a severe load on the server memory.

A step by step guide to use radio buttons as a template column in VS2005 within a gridview

A step by step guide to use radio buttons as a template column in
VS2005 within a gridview. Selecting a radio button will result in
the row being selected.


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;


public partial class _Default : System.Web.UI.Page
{

private string connectionstring =
"server=YOURSERVER;database=DB;uid=user;password=password;";

protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
//Bind Master Details
BindData();
}
}

private void BindData()
{
//====Query For Master Rows======================
string QueryString = "SELECT distinct top 10 OrderID, ShipName as Name, " +
"ShipCity as City, ShipRegion as Region, ShipPostalCode as Postal " +
"FROM Orders order by ShipName";
//================================================

System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
try
{
conn.ConnectionString = connectionstring;
if (conn.State == System.Data.ConnectionState.Closed)
{
//OPEN CONNECTION
conn.Open();
}

//FILL DATASET
System.Data.SqlClient.SqlDataAdapter adapter =
new System.Data.SqlClient.SqlDataAdapter(QueryString, conn);

DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();

}
catch (Exception ex1)
{
Response.Write("An error has occurred: ");
Response.Write(ex1.Message.ToString());
Response.End();

}
finally
{
if (conn.State == System.Data.ConnectionState.Open)
{
//CLOSE CONNECTION
conn.Close();
}
}
}

protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
LabelSelected.Text = "";

//Clear Selection
GridView1.SelectedIndex = -1;

//Get the RadioButton Which Was Selected
RadioButton SelectedRadioButton = (RadioButton)sender;

//Since this is a template column,
//we can get the specific row, by using
//the Naming Container.
GridViewRow SelectedGridRow = (GridViewRow)SelectedRadioButton.NamingContainer;

//Clear All Radio Button Choices From Prior
foreach (GridViewRow GridRow in GridView1.Rows)
{
if (GridRow != SelectedGridRow)
{
RadioButton RowRadioButton =
(RadioButton)GridRow.FindControl("RadioButton1");

RowRadioButton.Checked = false;
}
}

if (SelectedRadioButton.Checked == true)
{
//Set the row as selected
GridView1.SelectedIndex = SelectedGridRow.RowIndex;

//Print out details of selected row data
string MessageOutput = "Items Selected are: ";
for (int i = 1; i < SelectedGridRow.Cells.Count; i++) { MessageOutput += GridView1.HeaderRow.Cells[i].Text + ": " + SelectedGridRow.Cells[i].Text + "
";
}

LabelSelected.Text = MessageOutput;
}
}
}

Wednesday, 14 December 2011

NumberToWords in c#

public static string NumberToWords(int number)
{
if (number == 0)
return "zero";

if (number < 0) return "minus " + NumberToWords(Math.Abs(number)); string words = ""; if ((number / 1000000) > 0)
{
words += NumberToWords(number / 1000000) + " million ";
number %= 1000000;
}

if ((number / 1000) > 0)
{
words += NumberToWords(number / 1000) + " thousand ";
number %= 1000;
}

if ((number / 100) > 0)
{
words += NumberToWords(number / 100) + " hundred ";
number %= 100;
}

if (number > 0)
{
if (words != "")
words += "and ";

var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

if (number < 20) words += unitsMap[number]; else { words += tensMap[number / 10]; if ((number % 10) > 0)
words += "-" + unitsMap[number % 10];
}
}

return words;
}

Monday, 5 December 2011

Advantages and Disadvantages of Stored Procedure

Advantages of stored procedures:

the procedures/functions are stored in the database and are, therefore, executed on the database server which is likely to me more powerful than the clients which in turn means that stored procedures should run faster;
the code is stored in a pre-compiled form which means that it is syntactically valid and does not need to be compiled at run-time, thereby saving resources;
each user of the stored procedure/function will use exactly the same form of queries which means the queries are reused thereby reducing the parsing overhead and improving the scalability of applications;
as the procedures/functions are stored in the database there is no need to transfer the code from the clients to the database server or to transfer intermediate results from the server to the clients. This results in much less network traffic and again improves scalability;
when using PL/SQL packages, as soon as one object in the package is accessed, the whole package is loaded into memory which makes subsequent access to objects in the package much faster
stored procedures/functions can be compiled into “native” machine code making them even faster (available with Oracle 9i and above)

Disadvantages:

there is an overhead involved in switching from SQL to PL/SQL, this may be significant in terms of performance but usually this overhead is outweighed by performance advantages of using PL/SQL
more memory may be required when using packages as the whole package is loaded into memory as soon as any object in the package is accessed
native compilation can take twice as long as normal compilation

Despite the advantages listed above, there are some situations where the use of stored procedures is not recommended or may be infeasible.

Disadvantages

Applications that involve extensive business logic and processing could place an excessive load on the server if the logic was implemented entirely in stored procedures. Examples of this type of processing include data transfers, data traversals, data transformations and intensive computational operations. You should move this type of processing to business process or data access logic components, which are a more scalable resource than your database server.

Do not put all of your business logic into stored procedures. Maintenance and the agility of your application becomes an issue when you must modify business logic in T-SQL. For example, ISV applications that support multiple RDBMS should not need to maintain separate stored procedures for each system.

Writing and maintaining stored procedures is most often a specialized skill set that not all developers possess. This situation may introduce bottlenecks in the project development schedule.