Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

C# Implicitly Typed Local Variables and Arrays

As a whole C# is a strongly-typed language. In other word the C# variables can hold explicitly defined data type.

From C# version 3.0 on the developer get the possibility to assign any values to a variable and the compiler to obtain accordingly the data type. It is not in the C# style as we know it but has some advantages of course.

var intVariable = 1235;
var stringVariable = "Hello";

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.

The biggest advantage of this new feature is the usage in LINQ query expression using anonymous data types. The anonymous type name is automatically generated by the compiler and is not available at the source code level, but his usage saves much developer's efforts.

For more information in MSDN click here

VB.NET: General Exception Handling in Windows Forms

VB.NET

My.Application.UnhandledException Event is the way for handling all unhandled exceptions in an windows forms application. The application raises this event when it encounters unhandled exception.
For using the event editing ApplicationEvents.vb file is needed. By default ApplicationEvents.vb is hidden. For openning (unhiding) it use Project Properties -> Application tab -> View Appication Events.
Then the handler can be added/edited as in the example below:

Private Sub MyApplication_UnhandledException( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs _
) Handles Me.UnhandledException

Try
//write log, which is nessted in Application Data folder
My.Application.Log.WriteException( _
e.Exception, _
TraceEventType.Critical, _
"Unhandled Exception!")

//check up if the Event folder exists.
//if not - create new one
If Not EventLog.SourceExists("My software") Then
EventLog.CreateEventSource("My software", "My Software")
End If

//write event log, can be seen by Event Viewer
EventLog.WriteEntry("My software", _
e.Exception.ToString(), _
EventLogEntryType.Error)
Catch ex As Exception

End Try

// code for notifying the user with user friendly message
...................

//set the default application action (closing) not to be performed.
e.ExitApplication = False
End Sub
And from now on all unhandled exception in the application will be stored as exception information and stack trace in the application log file or in the Windows Event log and the user will receive friendly message.


C#

Of course most of my posts give examples with VB and C# when they are different. Now I will give up this pleasure to R. Newman with his great post "Top-level Exception Handling in Windows Forms Applications"

How to check the type of an object or control using VB.NET or C#

The VB.NET check up is:

If (TypeOf sender Is TextBox)Then
Dim txt As TextBox= DirectCast(sender, TextBox)
End If



And the C# code:

if (sender Is TextBox){
TextBox txt=(TextBox)sender;
}

Adding a relationship between DataTables

A DataTable can be related to another DataTable in the same DataSet using DataRelation object. Using DataRelation the navigation between DataTable (foreign key connection) becomes very easy.

An example for using Child Relation is located here:
http://msdn.microsoft.com/en-us/library/system.data.datatable.childrelations.aspx

Here is an example for using Parent Relation:

We have two DataTables: DataTableOrder (OrderId is foreign key to DataTableOrderDetails) and DataTableOrderDetails (Id is primary key)

//create dataset
DataSet dataSet = new DataSet();

//add existing tables to the DataSet
dataSet.Tables.Add(DataTableOrder );
dataSet.Tables.Add(DataTableOrderDetails);

// create relation between both tables
dataSet.Relations.Add(
dataSet.Tables[1].Columns["Id"],
dataSet.Tables[0].Columns["OrderId"]);

foreach (DataRow row in DataTableOrder .Rows)
{
//get parent rows using relation - all order details for current order
//use GetParentRows for relations 1 to many
DataRow dr=row.GetParentRow(dtm.ParentRelations[0]);
//check if there is a parent row
if(dr!=null){
Response.Write(row["OrderName"].ToString() +"->"+ dr["OrderDetails"].ToString() +"
")
}
}

How to build unsafe C# code with Visual Studio

Unsafe code may only appear if compiling with /unsafe

This appears as an error when you try to compile assembly which contains unsafe code in release mode.
You must change the compiler options using project's Properties page -> Build -> and check Allow Unsafe Code. Consider if you want to use unsafe code :)))

Understanding AutoEventWireup attribute in Asp.net page. Event handlers.

The AutoEventWireup attribute indicates if the page events are auto-wired up. If the attribute is set to true .Net framework searches automatically for methods which names are created in the way Page_xxxxx (Page_Load, Page_Init etc.) and connects them to the events. Otherwise the developer or the environment must do that using delegates:

this.Load += new System.EventHandler(this.Page_Load);

for all handled page events. Setting AutoEventWireup to false is the better way because of the performance -> the framework uses only the methods with code!

The attribute can be set on several places: in machine.config, web.config and for every page.

Note:
The note is not connected directly to the page events, but to events of postback controls like button, linkbutton etc.
In VB.NET the event handlers can be attached to the events using the keyword "Handles".

Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click

This method will handle the event Click and will work like adding the attribute
OnClick="LinkButton1_Click" to the LinkButton tag. But NEVER USE both of the ways at the same because this will invoke the method twice!!
Consider using keyword "Handles" OR OnEvent="", but never use them together.

How to covert System.Drawing.Color to a HTML/CSS color value

The System.Drawing.Color represenation of the color including the alpha color element:
alpha, red, green, blue.
The process is simple - convert the decimal color representation to a hexadecimal, then remove the alpha hexadecimal value from the string and concatenate to '#'.

Dim HTMLColor As String = Hex(color.ToArgb())
HTMLColor = "#" + HTMLColor.Substring(2)

where "color" is an instance of System.Drawing.Color

There is a difference between VB.NET and C# in getting the hexadecimal value as string. The C# fans can use the folloing code:

string HTMLColor = color.ToArgb().ToString("X8");
HTMLColor = "#" + HTMLColor.Substring(2);


The opposite process can be accomplished by ColorTranslator' services:
Dim color As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#e5e5e5")

ASP.NET How to access the EmptyDataTemplate controls from OnRowCommand in GridView

The way of getting access to the controls in EmptyDataTemplate is similar to the way of accessing controls in the same data row in the gridview.

For example - inserting value in the empty gridview:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") {
TextBox txt =
(((Control)e.CommandSource).NamingContainer).FindControl("txtTest") as TextBox;

//do insert action
}
}
Another way to do this is by getting EmptyDataTemplate table and its controls:
if (e.CommandName == "Insert")
{
Table table = (Table)GridView1.Controls[0];
TextBox txtTest= (TextBox)table.Rows[0].FindControl("txtTest");

//do insert actions
}

ASP.NET How to set and get key values for every gridrow in a gridview.

Setting primary key values during data binding:

gvUsersInRoles.DataSource=taUsersInRoles.GetData();
gvUsersInRoles.DataKeyNames = new string[] { "UserId", "RoleId" };
gvUsersInRoles.DataBind();
This example uses composite primary key for showing more complicated usage.

Getting primary key values during performing row command (command, insert, delete, update):

Guid uid = new Guid(gvUsersInRoles.DataKeys[e.RowIndex]["UserId"].ToString());
int pid = int.Parse(gvUsersInRoles.DataKeys[e.RowIndex]["RoleId"].ToString());

Passing data between two pages with Cross-page Postback and Server.Transfer

The ASP.NET control, that cause postback, post back to the page for processing. That page can be current page or another page. Every control that cause postback can be configured to post to a different page - this postback is called cross postback and is often used for getting information from the pages in the multi page form, especially convenient for creating wizards.

<asp:Button
ID="Button1"
PostBackUrl="~/TargetPage.aspx"
runat="server"
Text="Submit" />

Cross-page post back is similar to Server.Transfer method, but there are some imporrtant differences. Server.Transfer conserves the post data between pages and also it keeps the url. And also it has a documented bug with getting url parameters from the source page. The Server.Transfer method is a server-based operation whereas cross-page postback is a client-based transfer. The main aim of the Server.Transfre method is to reduce client request to the server which makes it faster than Response.Redirect().
Anyway the cross-page postaback can throw the user on another page but with possibility to get the post data.

if (Page.PreviousPage != null)
{
TextBox SourceTextBox =(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null) { Label1.Text = SourceTextBox.Text;
}
}


there is also possibility to get public properties from the source page with decalring the source:

<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>

getting the whole source page:

SourcePage_aspx sourcePage;
sourcePage = (SourcePage_aspx) PreviousPage;
Label1.Text = sourcePage.CurrentCity;

With PreviousPage.IsCrossPagePostBack we can determine whether the page was invoked from a cross-page posting.

Resources:
http://msdn2.microsoft.com/en-us/library/ms178139.aspx
http://www.developer.com/net/asp/article.php/3299641
http://www.codeproject.com/useritems/CrossPagePosting.asp

Using DataTable (DataView) Filter expressions, Sorting

In some cases it is necessary to be made some calculations or data filtering and sorting of local data - already received from a database. These things can be made with the DataTable or DataView classes in a way similar to SQL Select queries.
When we have a filled DataTable we can easy retrieve only the rows we need with DataView.RowFilter. This property gets or sets the expression used to filter which rows are viewed in the DataView (often used for DataSourse in data components).

DataTable dt= ......... //filling the data table
DataView dv= dt.DefaultView;
dv.RowFilter="AreaId="+searchId+" AND SubAreaName LIKE 's*'; //getting all records for searched area whic name starts with 's'
dv.Sort="Name desc, number asc"; //sorting data

dv.RowFilter = "Name LIKE 's*'" // values that start with "s"'
dv.RowFilter = "Name LIKE '%s%'" // values that contain 's'
dv.RowFilter = "Name NOT LIKE 's*'" // values that don't start with 's'
dv.RowFilter = "Name <> 'MyName'" // values different than 'MyName'
dv.RowFilter = "Name IN ('MyName','MySecondName')" // value equal to 'MyName' or 'MySecondName'


If the pattern string in a LIKE statement contains special characters like * % [ ], they must be escaped in brackets [ ] in this way [*], [%], [[] or []].

RowFilter is an expression string that can be evaluated to true or false, and uses the syntax described in the DataColumn.Expression documentation.

It is very useful to use also aggregate functions for calculation. For example
dt.Columns("ItemCount").Expression = "Count(ItemID)"
dt.Columns("ItemCount").Expression = "FirstName = 'John'"   
dt.Columns("ItemCount").Expression = "Date < #1/31/82#" 
dt.Columns("ItemCount").Expression = (LastName = 'Smith' OR LastName = 'Jones') AND FirstName = 'John' 

Here is the MSDN reference for the filter expressions:
http://msdn2.microsoft.com/en-us/library/system.data.datacolumn.expression(VS.71).aspx

How to delete row in a DataTable with C# or VB.NET

When you use a DataRow.Delete() method the row is not actually deleted. It is only marked to be deleted after calling DataTable.AcceptChanges(). It is not good idea to remove row with DataTable.Rows.Remove or RemoveAt methods. They forces row removing and causes by iterating the following exception:
'Collection was modified; enumeration operation may not execute'
One more thing to be sure that the iterating will be performed succesfully is to iterate through returned by DataTable.Select() rows (not DataTable.Rows).

For Each row As DataRow In dt.Select()
   If (bool_statement) Then
     row.Delete()
   End If
Next

dt.AcceptChanges

If adapter is used changes can be commited by Update method. All rows with DataRow.RowState of 'Deleted' will be deleted.

How to get random number or generate random password with VB.NET or C#

The simplest way to get random number is to get instance of the Random class and use the "Next" method.
Dim rand As Random=new Random()
rand.Next() gives you a random nonnegative number
rand.Next(23) gives you a random nonnegative number less than integer value (23 for the example)
rand.Next(23, 89) gives you a random nonnegative number in the specified range

With this class you can generate also double values and bytes.

Here is an way for generating random password using guid.
So simple, so effective.

Public Function GetRandomPassword(ByVal length As Integer) As String
Dim rand As String = System.Guid.NewGuid().ToString()
rand = rand.Replace("-", String.Empty)

If length <= 0 OrElse length > rand.Length Then
Throw New ArgumentException("Length must be between 1 and " & rand.Length)
End If

Return rand.Substring(0, length)
End Function

Read and Write to configuration's files

Reading:
string value = ConfigurationManager.AppSettings["Setting1"];

Writing:
System.Configuration.Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Setting1"].Value = "3";
config.AppSettings.Settings["Setting2"].Value = "blabla";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

When use configuration settings in your web.config you have tou use
WebConfigurationManager class.

ASP.NET C# How to send mail with SMTP Authetication.

To send email from ASP.NET hosting account it is necessary to use credentials for smtp authentication.
Here is a way to do this with help function for sending mail.

private void sendEmail(string strTo, string strFrom,
string strSubject, string strBody, Attachment item, bool isHTML)
{

MailAddress maFrom = new MailAddress(strFrom, "sender");
MailAddress maTo = new MailAddress(strTo);
MailMessage mail = new MailMessage(maFrom, maTo);
mail.Attachments.Add(item);
mail.IsBodyHtml = isHTML;
mail.Subject = strSubject;
mail.Body = strBody;
SmtpClient sc = new SmtpClient();
System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("email account", "password");

sc.Credentials = basicAuthenticationInfo;
sc.Host = "mail.xxxx.xxx";
sc.Port = 25;
sc.Send(mail);
}

Email account you can register with the hosting control panel (if you don't have already). The host is usually mail.+ domain name.

C#, VB.NET - How to convert string to Guid

string str="565G6B7D-8H7D-8J7D-A0C6-908H7D868H7D";
Guid g= new Guid(str);


Dim str As String="565G6B7D-8H7D-8J7D-A0C6-908H7D868H7D";
Dim g As System.Guid = New Guid(str);