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.

Wednesday 9 November 2011

Friday 28 October 2011

C# .NET datatype help

What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

Can you store multiple data types in System.Array? No.
What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.
What’s class SortedList underneath? A sorted HashTable.
Will finally block get executed if the exception had not occurred? Yes.
What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

Tuesday 27 September 2011

Asp.net custom error page

ASP.NET provides a simple yet powerful way to deal with errors that occur in your web applications. We will look at several ways to trap errors and display friendly meaningful messages to users. We will then take the discussion a step further and learn how to be instantly notified about problems so you can cope with them right away. As a geek touch we will also track the path 404's travel.
In the days of "classic" ASP you used to get cryptic—an often times downright misleading—error messages. "White pages" leave your visitors in the dark who don't know what happened and what to do next besides closing the browser or navigating away.
It's obvious that "white pages" are ugly but there's another angle to this—ASP.NET displays an exception stack trace which may reveal what your code does and how it works. These days, when the word "security" is in vogue, this could be a dangerous side effect.
Custom error pages are not luxury any more, they are a must-have. You have several ways to implement them.

Every time you create a web form in Visual Studio .NET you see that your page class derives from System.Web.UI.Page. The Page object helps you trap page-level errors. For this to happen you need to override its OnError method as follows:

protected override void OnError(EventArgs e)
{
  // At this point we have information about the error
  HttpContext ctx = HttpContext.Current;

  Exception exception = ctx.Server.GetLastError ();

  string errorInfo = 
     "<br>Offending URL: " + ctx.Request.Url.ToString () +
     "<br>Source: " + exception.Source + 
     "<br>Message: " + exception.Message +
     "<br>Stack trace: " + exception.StackTrace;

  ctx.Response.Write (errorInfo);

  // --------------------------------------------------
  // To let the page finish running we clear the error
  // --------------------------------------------------
  ctx.Server.ClearError ();
 
  base.OnError (e);
}

Friday 23 September 2011

What is RDBMS?

Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage.

OnClientClick Event In Asp.net

OnClientClick ="javascript:if (confirm('Are You Sure you want to delete?')==false)return false;"

Wednesday 21 September 2011

Delete All Stored Procedures

Delete All Stored Procedures

declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'p'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
            if @procName <> 'DeleteAllProcedures'
                  exec('drop procedure ' + @procName)
                  fetch next from cur into @procName
      end

close cur
deallocate cur

Delete All Views


declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'v'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
                  exec('drop view ' + @procName)
                  fetch next from cur into @procName
      end
close cur
deallocate cur

Delete All Functions


declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'fn'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
                  exec('drop function ' + @procName)
                  fetch next from cur into @procName
      end

close cur
deallocate cur

Delete All Tables in Sql

--Delete All Keys

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO

Inheritance and Cascading Styles in CSS Explained

1. Styles can be inherited from a parent

Some styles, like font family, text-alignment etc., are automatically inherited by child elements from their parent element (i.e. by an element contained inside another one).
Others are not automatically inherited.

Example

<div style=”font-family:serif; border:1px solid red; padding:10px;”>
This text will be in a serif font.
<p>
This text is also in a serif font, because font is inherited by default.
But the border and padding properties are not inherited from the parent div.
</p>
</div>
However, you can make an element inherit styles from its parent.

Example

<div style=”font-family:serif; border:1px solid red; padding:10px;”>
This text will be in a serif font.
<p style=”border:inherit;”> 
Now the paragraph also has a red border.
Border properties are not inherited by children, by default, but because I set border to “inherit”, it is.
</p>
</div>

Sunday 18 September 2011

css : Avoid Superfluous Selectors

Sometimes your CSS declaration can be simpler, meaning if you find yourself coding the following:
  • ul li { ... }
  • ol li { ... }
  • table tr td { ... }

They can be shorten down to just
  • li { ... }
  • td { ... }
Explanation:
li will only exist within ul or ol
and td will only be inside
tr and tableso there’s really not necessary to re-insert them.

Use Shorthand CSS

Shorthand CSS gives you a shorter way of writing your CSS codes, and most important of all – it makes the code clearner and easier to understand.

Instead of creating CSS like this

.header{
background-color: #fff;
background-image: url(image.gif);
background-repeat: no-repeat;
background-position: top left;
}
It can be short-handed into the following:

.header {
background: #fff url(image.gif) no-repeat top left
}

CSS3 Borders

CSS3 Borders

With CSS3, you can create rounded borders, add shadow to boxes,
and use an image as a border - without using a design program, like Photoshop.

In this Post you will learn about the following border properties:
border-radius
box-shadow
border-image
Browser Support
Internet Explorer 9 supports some of the new border properties.

Firefox requires the prefix -moz- for border-image.

Chrome and Safari requires the prefix -webkit- for border-image.

Opera requires the prefix -o- for border-image.

Safari also needs the prefix -webkit- for box-shadow.

Opera supports the new border properties.

CSS3 Rounded Corners
div
{
border:2px solid;
border-radius:25px;
-moz-border-radius:25px; /* Firefox 3.6 and earlier */
}
CSS3 Box Shadow
div
{
box-shadow: 10px 10px 5px #888888;
-webkit-box-shadow: 10px 10px 5px #888888; /* Safari */
}
CSS3 Border Image
div
{
border-image:url(border.png) 30 30 round;
-moz-border-image:url(border.png) 30 30 round; /* Firefox */
-webkit-border-image:url(border.png) 30 30 round; /* Safari and Chrome */
-o-border-image:url(border.png) 30 30 round; /* Opera */
}

Threading

(1)What is Multi-tasking ?
It’s a feature of modern operating systems with which we can run multiple programs a
same time example Word, Excel etc.

(2)What is Multi-threading ?
Multi-threading forms subset of Multi-tasking. Instead of having to switch between
programs this feature switches between different parts of the same program. Examp
you are writing in word and at the same time word is doing a spell check in backgroun

(3)What is a Thread ?
A thread is the basic unit to which the operating system allocates processor time.
(4)Did VB6 support multi-threading ?
While VB6 supports multiple single-threaded apartments, it does not support a fre
threading model, which allows multiple threads to run against the same set of data.