Monday 23 May 2011

Pre And Post Build Events in C#

http://visualstudiohacks.com/general/customize-your-project-build-process/

http://bytes.com/topic/c-sharp/answers/424841-post-build-events

http://www.dotnetperls.com/post-pre-build-macros


Friday 20 May 2011

SQL Server Date Formats

http://www.sql-server-helper.com/tips/date-formats.aspx

How To Get IP Address Of A Machine

 Getting the Host name and IP Address of Local Machine:
namespace NKUtilities 
{
    using System;
    using System.Net;
    
    public class DNSUtility
    {
        public static int Main (string [] args)
        {
        
          String strHostName = new String ("");
          if (args.Length == 0)
          {
              // Getting Ip address of local machine...

              // First get the host name of local machine.

              strHostName = DNS.GetHostName ();
              Console.WriteLine ("Local Machine's Host Name: " +  strHostName);
          }
          else
          {
              strHostName = args[0];
          }
          
          // Then using host name, get the IP address list..

          IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
          IPAddress [] addr = ipEntry.AddressList;
          
          for (int i = 0; i < addr.Length; i++)
          {
              Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
          }
          return 0;
        }    
     }
}
 
Getting the Local Machine's IP Address: 
 using System;
using System.Net;

class Test {

public static void Main() {
   IPAddress[] a = Dns.GetHostByName(Dns.GetHostName()).AddressList;
   for (int i=0; i<a.Length; i++)
      Console.WriteLine ("IpAddr[{0}]={1}",i,a[i]); }

}
 
For Any Host by using the site address:
using System;
// using the System.Net namespace
using System.Net;
class Class1
{

[STAThread]
static void Main(string[] args)
{
// Request the name
Console.Write("Please type the name of the host: ");
// Store it in 'host'
string host = Console.ReadLine();
try
{
// Get the DNS information
IPHostEntry ipHost = Dns.GetHostByName(host);
// Display the host name
Console.WriteLine("Host name: {0}", ipHost.HostName);
// Store the list of IP adresses
IPAddress[] ipAddr = ipHost.AddressList;
// Loop to actually display the IP
for(int x = 0; x < ipAddr.Length; x++)
{
Console.WriteLine("IP address: {0}", ipAddr[x].ToString());
}
}
// Catch the exception (if host was not found)
catch(System.Net.Sockets.SocketException)
{
Console.WriteLine("Host not found.");
}
}
} 

How To Use the Settings Class in C#

http://msdn.microsoft.com/en-us/library/aa730869%28v=vs.80%29.aspx
http://www.codeproject.com/KB/cs/PropertiesSettings.aspx 
http://codehill.com/2009/01/saving-user-and-application-settings-in-winforms/

SQL SERVER – Restore Database Backup using SQL


Database YourDB has full backup YourBaackUpFile.bak. It can be restored using following two steps.
Step 1: Retrive the Logical file name of the database from backup.
RESTORE DATABASE dbname
FROM DISK = 'D:BackUpYourBaackUpFile.bak'
WITH REPLACE
GO

Step 2: Use the values in the LogicalName Column in following Step.
----Make Database to single user Mode
ALTER DATABASE YourDB
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
----Restore Database
RESTORE DATABASE YourDBName
FROM DISK = 'D:BackUpYourBaackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:DataYourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'D:DataYourLDFFile.ldf'
/*If there is no error in statement before database will be in multiuser
mode.
If error occurs please execute following command it will convert
database in multi user.*/
ALTER DATABASE YourDB SET MULTI_USER
GO


SQL Server 2000 Backup and Restore:

http://technet.microsoft.com/en-us/library/cc966495.aspx

Read XML from a file by using C#

http://www.kirupa.com/net/reading_xml_directly_pg1.htm
http://www.developer.com/net/csharp/article.php/3489611/Manipulate-XML-File-Data-Using-C.htm
http://support.microsoft.com/kb/307548

To Read a XML file:
 XmlDocument doc = new XmlDocument();
            doc.Load("D:\\Dotnet Projects\\final\\ClientAppl\\Header.xml");

            XmlNodeList bookList = doc.GetElementsByTagName("Header");

            foreach (XmlNode node in bookList)
            {

                XmlElement bookElement = (XmlElement)node;
                string title = bookElement.InnerText;
                lblHeader.Text = title;
            }  

Using Windows Form Controls

http://www.codeproject.com/KB/books/1861004982.aspx

2 year exp asp.net interview question

http://www.dotnetspider.com/forum/231146-year-exp-asp-net-interview-question.aspx

Installing Oracle 10g – step by step guide

http://faq.programmerworld.net/database/installing-oracle-10g.html

State Management Techniques in ASP.NET

http://www.codeproject.com/KB/aspnet/state_management_intro.aspx

MySql Database Backuup And Restore Code

 Backup:
DateTime Time = DateTime.Now;
                int year = Time.Year;
                int month = Time.Month;
                int day = Time.Day;
                int hour = Time.Hour;
                int min = Time.Minute;
                //int second = Time.Second;
                //int millisecond = Time.Millisecond;

                            
                //Save file to C:\ with the current date as a filename
                string path = Application.StartupPath + "\\"+ "dbbackup"+"\\";

                path = path + year + "-" + month + "-" + day + "-" + hour + "-" + min + ".sql";
                //path = "C:\\Documents and Settings\\user\\Desktop\\dbbackup\\" + year + "-" + month + "-" + day +".sql";
                StreamWriter file = new StreamWriter(path);


                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = "mysqldump";
                psi.RedirectStandardInput = false;
                psi.RedirectStandardOutput = true;
                psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", "root", "password", "localhost", "inventory");
                psi.UseShellExecute = false;

                Process process = Process.Start(psi);

                string output;
                output = process.StandardOutput.ReadToEnd();
                file.WriteLine(output);
                process.WaitForExit();
                file.Close();
                process.Close();
                MessageBox.Show("Database Backup Completed Successfully");
Restore:
int x = 10; int y = 10;
                files = Directory.GetFiles(Application.StartupPath + "\\" + "dbbackup", "*.sql");
                for (int i = 0; i < files.Length; i++)
                {
                    split = files[i].Split('\\');

                    foreach (string file in split)
                    {
                        if (file.EndsWith(".sql"))
                        {

                            LinkLabel lb = new LinkLabel();
                            lb.Location = new Point(x, y);
                            lb.Name = file;
                            lb.Text = file;
                            lb.Width = 300;
                            dbfilepanel.Controls.Add(lb);
                            y = y + 20;
                            lb.Click += new EventHandler(lb_Click);

in lb_Click Event:
string dbfile = ((Control)sender).Name;
                string respath = Application.StartupPath + "\\" + "dbbackup" + "\\" + dbfile;

                /* for restoring the database */
                StreamReader file = new StreamReader(respath);
                ProcessStartInfo proc = new ProcessStartInfo();
                string cmdArgs = string.Format(@"-u{0} -p{1} -h{2} {3}", "root", "password", "localhost", "inventory");
                proc.FileName = "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysql.exe";
                proc.RedirectStandardInput = true;
                proc.RedirectStandardOutput = false;
                proc.Arguments = cmdArgs;
                proc.UseShellExecute = false;
                Process p = Process.Start(proc);
                string res = file.ReadToEnd();
                file.Close();
                p.StandardInput.WriteLine(res);
                p.Close();
                MessageBox.Show("Database Restore Completed Successfully");


Wednesday 11 May 2011

Adding checkbox to Dynamically created grid...

SQL Server 2005 Database Backup & Restore by using C#

Introduction

The following article describes accessing a SQL Server 2005 database backup and restoring it programmatically using C#.NET 2.0 and SMO. This article provides coding samples to perform the task.
SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server.
The following namespaces can be used to access SQL Server 2005 programmatically:
  • Microsoft.SqlServer.management
  • Microsoft.SqlServer.Management.NotificationServices
  • Microsoft.SqlServer.Management.Smo
  • Microsoft.SqlServer.Management.Smo.Agent
  • Microsoft.SqlServer.Management.Smo.Broker
  • Microsoft.SqlServer.Management.Smo.Mail
  • Microsoft.SqlServer.Management.Smo.RegisteredServers
  • Microsoft.SqlServer.Management.Smo.Wmi
  • Microsoft.SqlServer.Management.Trace

Pre-Requisite

You need to reference the following namespaces before using this code:
  • Microsoft.SqlServer.Management.Smo;
  • Microsoft.SqlServer.Management.Common;
I used these two class to perform the backup and restore operations:
  • Microsoft.SqlServer.Management.Smo.Backup
  • Microsoft.SqlServer.Management.Smo.Restore
For more information, regarding these two class, check MSDN:

Backup database

Collapse
public void BackupDatabase(String databaseName, String userName, 
            String password, String serverName, String destinationPath)
{
    Backup sqlBackup = new Backup();
    
    sqlBackup.Action = BackupActionType.Database;
    sqlBackup.BackupSetDescription = "ArchiveDataBase:" + 
                                     DateTime.Now.ToShortDateString();
    sqlBackup.BackupSetName = "Archive";

    sqlBackup.Database = databaseName;

    BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
    ServerConnection connection = new ServerConnection(serverName, userName, password);
    Server sqlServer = new Server(connection);
    
    Database db = sqlServer.Databases[databaseName];
    
    sqlBackup.Initialize = true;
    sqlBackup.Checksum = true;
    sqlBackup.ContinueAfterError = true;
    
    sqlBackup.Devices.Add(deviceItem);
    sqlBackup.Incremental = false;

    sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
    sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

    sqlBackup.FormatMedia = false;

    sqlBackup.SqlBackup(sqlServer);
}

Restore Database

Collapse
public void RestoreDatabase(String databaseName, String filePath, 
       String serverName, String userName, String password, 
       String dataFilePath, String logFilePath)
{
    Restore sqlRestore = new Restore();
    
    BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
    sqlRestore.Devices.Add(deviceItem);
    sqlRestore.Database = databaseName;

    ServerConnection connection = new ServerConnection(serverName, userName, password);
    Server sqlServer = new Server(connection);

    Database db = sqlServer.Databases[databaseName];
    sqlRestore.Action = RestoreActionType.Database;
    String dataFileLocation = dataFilePath + databaseName + ".mdf";
    String logFileLocation = logFilePath + databaseName + "_Log.ldf";
    db = sqlServer.Databases[databaseName];
    RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);
    
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName+"_log", logFileLocation));
    sqlRestore.ReplaceDatabase = true;
    sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
    sqlRestore.PercentCompleteNotification = 10;
    sqlRestore.PercentComplete += 
       new PercentCompleteEventHandler(sqlRestore_PercentComplete);
            
    sqlRestore.SqlRestore(sqlServer);
    db = sqlServer.Databases[databaseName];
    db.SetOnline();
    sqlServer.Refresh();
}
The portion of code uses full backup features. If you want, you can perform incremental and differential backup as well.

Updates: June 8, 2008

In order to use this code, your SQL Server authentication mode needs to be configured as Mixed Mode authentication. If you use Windows Authentication, then you need to modify the ServerConnection:
Collapse
SqlConnection sqlCon = new SqlConnection ("Data Source=Bappi; Integrated Security=True;");
ServerConnection connection = new ServerConnection(sqlCon);
Modify the ServerConnection portion of both code samples using this code in order to use Windows Security.