Tuesday, August 31, 2010

Format System.DateTime in .NET



System.DateTime in ASP.NET


Below are common uses of the DateTime Structure in C#


DateTime.Now; 8/31/2010 12:25:09 PM
DateTime.Now.ToString(); 8/31/2010 12:25:09 PM
DateTime.Now.ToShortTimeString()12:25 PM
DateTime.Now.ToShortDateString()8/31/2010
DateTime.Now.ToLongTimeString()12:25:09 PM
DateTime.Now.ToLongDateString()Tuesday, August 31, 2010





DateTime.Now.ToString("d")8/31/2010
DateTime.Now.ToString("D")Tuesday, August 31, 2010
DateTime.Now.ToString("f")Tuesday, August 31, 2010 12:25 PM
DateTime.Now.ToString("F")Tuesday, August 31, 2010 12:25:09 PM
DateTime.Now.ToString("g")8/31/2010 12:25 PM
DateTime.Now.ToString("G")8/31/2010 12:25:09 PM
DateTime.Now.ToString("m")August 31
DateTime.Now.ToString("r")Tue, 31 Aug 2010 12:25:09 GMT
DateTime.Now.ToString("s")2010-08-31T12:25:09
DateTime.Now.ToString("t")12:25 PM
DateTime.Now.ToString("T")12:25:09 PM
DateTime.Now.ToString("u")2010-08-31 12:25:09Z
DateTime.Now.ToString("U")Tuesday, August 31, 2010 5:25:09 PM
DateTime.Now.ToString("y")August, 2010
DateTime.Now.ToString("dddd, MMMM dd yyyy")Tuesday, August 31 2010
DateTime.Now.ToString("ddd, MMM d "'"yy")Tue, Aug 31 '10
DateTime.Now.ToString("dddd, MMMM dd")Tuesday, August 31
DateTime.Now.ToString("M/yy")8/10
DateTime.Now.ToString("dd-MM-yy")31-08-10


Source: http://www.csharpfriends.com/demos/system.datetime.aspx



Special folders in a VS web site

Special folders in a VS web site.

Special folders can be added to a Web site from the Visual Studio menu system. Typically
this involves right-clicking the Web application project and selecting Add ASP.NET Folder.

Folder NameDescription
App_BrowsersContains browser definition files (.browser) that ASP.NET uses
to identify browsers and determine their capabilities. These
files are often used to help support mobile applications.
App_CodeContains source code for classes and business objects (.cs,
.vb, and .jsl files) that you want to compile as part of your
application
App_DataContains application data files (.mdf and .xml files)
App_GlobalResourcesContains resources (.resx and .resources files) that are compiled
into assemblies and have a global scope. Resource files
are used to externalize text and images from your application
code. This helps you support multiple languages and
design-time changes without recompilation of source code
App_LocalResourcesContains resources (.resx and .resources files) that are
scoped to a specific page, user control, or master page in an
application.
App_ThemesContains subfolders that each define a specific theme (or
look) for your site. A theme consists of files (such as .skin,
.css, and image files) that define the appearance of Web
pages and controls.
App_WebReferencesContains Web reference files (.wsdl, .xsd, .disco, and .discomap
files) that define references to Web services
BinContains compiled assemblies (.dll files) for code that you
want to reference in your application. Assemblies in the Bin
folder are automatically referenced in your application


Wednesday, August 25, 2010

How to use mySQL with .Net

Add mySQL connector
In order to use mySQL with .Net you need to download the connector from the next web site:

http://dev.mysql.com/downloads/connector/net/


Add mySQL connector to your project
On your project right click on "References" ans select "Add Reference..."
Browse to the folder where you installed the connector and open the folder "Assemblies"
Add the MySql dlls

Use connector en your code
Now you can use the connector in your code to access mySQL database




using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace mySQLExample
{
///
/// Summary description for dbConnection.
///

public class dbConnection
{
private string connectionString;

public dbConnection()
{
connectionString = "Server=MySqlServer;Database=MySqlDB;Uid=MySqlUser;Pwd=MySQLPsw;Port=3306;old guids=true";
}


public DataSet ExecuteQuery(CommandType cmdType, string cmdText, params System.Data.Common.DbParameter[] cmdParms)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds, "dataset");
cmd.Parameters.Clear();
return ds;
}
}
}
}

public int ExecuteNonQuery(CommandType cmdType, string cmdText, params System.Data.Common.DbParameter[] cmdParms)
{
MySqlCommand cmd = new MySqlCommand();

using (MySqlConnection conn = new MySqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}

private static void PrepareCommand(System.Data.Common.DbCommand cmd, System.Data.Common.DbConnection conn, System.Data.Common.DbTransaction trans, CommandType cmdType, string cmdText, System.Data.Common.DbParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open) conn.Open();

cmd.Connection = conn;
cmd.CommandText = cmdText.Replace("@", "?").Replace(":", "?");

if (trans != null) cmd.Transaction = trans;

cmd.CommandType = cmdType;

if (cmdParms != null)
{
foreach (MySqlParameter parm in cmdParms)
{
parm.ParameterName = parm.ParameterName.Replace("@", "?").Replace(":", "?");
cmd.Parameters.Add(parm);
}
}
}

}
}








C# and mySQL error: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)


Problem:
When working with C# and mySQL, I use the code below I get the error message "Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)"


       public DataSet ExecuteQuery(System.Data.Common.DbTransaction trans, CommandType cmdType, string cmdText,
           params System.Data.Common.DbParameter[] cmdParms)
       {
           MySqlCommand cmd = new MySqlCommand();

           PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);

           MySqlDataAdapter da = new MySqlDataAdapter(cmd);

           DataSet ds = new DataSet();

           da.Fill(ds, "ds");

           cmd.Parameters.Clear();

           return ds;
       }


Cause:
The problem is that the the guids are being returned as varbinary(16) instead of binary(16) and as a result nhibernate throws an error.

Solution:
After version 6.1.1 you should add "old guids=true" to your connection string whenever you use BINARY(16) as your storage type. Else you should use CHAR(36)




Tuesday, August 24, 2010

How to insert a new line in a TextBox


To insert a new line in a TextBox, first make sure you have the MultiLine property of the TextBox set to True.
Do not try to use \r\n (carriage return and new line) because is not going to work, instead you must use:

Environment.Newline

Example:
TextBox1.Text = "First line" + + Environment.NewLine + "Second line";


This is working since C# 1.1

Thursday, August 19, 2010

How to detect screen rotation on windows mobile

You need to add the next references:

Microsoft.WindowsMobile
Microsoft.WindowsMobile.Status


Add the next code to your form load:

Microsoft.WindowsMobile.Status.SystemState MyScreenOrientationMonitor = new Microsoft.WindowsMobile.Status.SystemState(Microsoft.WindowsMobile.Status.SystemProperty.DisplayRotation);

MyScreenOrientationMonitor.Changed += new Microsoft.WindowsMobile.Status.ChangeEventHandler(ScreenRotatingDetector_Changed);


Finally add the specified event handler that fires when the screen has changed:

void ScreenRotatingDetector_Changed(object sender, Microsoft.WindowsMobile.Status.ChangeEventArgs args)
{
//Send a message to the screen
MessageBox.Show("Rootating......");
}

Friday, August 6, 2010

Change default language in Visual Studio





  1. Tools
  2. Import export settings wizard


  3. Reset all settings


  4. No, just reset settings, overwriting my current settings
  5. Select the default collection of settings (C#, VB, etc.)
  6. Finish



Thursday, August 5, 2010

Get the name of the day from a number





int dayName = 5;
string NameOfDay =
System.Globalization.DateTimeFormatInfo.CurrentInf o.GetDayName((DayOfWeek)
dayName);





String Format for DateTime in C#

Following examples demonstrate how are the format specifiers rewritten to the output.
// create date time 2008-03-09 16:05:07.123
DateTime dt = DateTime.Now;

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

// ***********************************************************************
// custom date and time formatting:

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime


Source:
http://www.csharp-examples.net/string-format-datetime/

Tuesday, August 3, 2010

Find the Most Time Consuming Code in SQL




To find the the Top 10 queries that take the most time run the query:
select top 10 source_code,stats.total_elapsed_time/1000000 as seconds,last_execution_time
from sys.dm_exec_query_stats as statscross
apply(SELECT text as source_code FROM sys.dm_exec_sql_text(sql_handle)) AS query_textorder by total_elapsed_time desc

To find the top 10 queries that take the maximum physical_reads run the query:
select top 10 source_code,stats.total_elapsed_time/1000000 as seconds,last_execution_time
from sys.dm_exec_query_stats as statscross
apply(SELECT text as source_code FROM sys.dm_exec_sql_text(sql_handle)) AS query_textorder by total_physical_reads desc


The method would work from version 2005 onwards. If you use it make sure the compatibility mode is set to 90.


How to change the compatibility mode in SQL



Maybe sometimes you get errors on a query you just found on the internet like:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'apply'.

The problem is that you are using functions from a different SQL version, you need to change the compatibility mode in SQL.
Changing the compatibility mode will not bring the server, or the database, down. The issues primarily have to do with what object names are valid, and what new commands are allowed. If dev is working fine with compatibility level 90, and you wont' be running any different code or accessing any different objects on Live, there should be no problems.

In addition, changing the compatibility mode doesn't change the database in anyway, so you can always revert back to compatibility level 80 if you want.

To change to compatibility mode use the next code:

ALTER DATABASE database_name SET COMPATIBILITY_LEVEL = { 80 | 90 | 100 }

or

EXEC sp_dbcmptlevel database_name, {80|90|100};

Version of SQL Server that can be reverted to can be one of the following:
60 = SQL Server 6.0
65 = SQL Server 6.5
70 = SQL Server 7.0
80 = SQL Server 2000
90 = SQL Server 2005
100 = SQL Server 2008




Monday, August 2, 2010

Auto align assignments on VS10

  1. Download "Productivity Power Tools" for VS10, from here, then install it.
  2. Select your code then press Ctrl+Alt+]
These are the results:
Before


After



Disable unique IDs on paste for Expression Web


If you want to disable the unique IDs on paste or when you modify your dwt in order to keep the correct reference to the style sheet, all you have to do is:
  1. Launch the "Page Editor Options" from the Tools menu option
  2. Uncheck the option "Make ID unique on paste"