Monday, 9 January 2012

How to convert number into words in c# code.


 public string retWord(int number)
  {

      if (number == 0) return "Zero";
      if (number == -2147483648) return "Minus Two Hundred and Fourteen Crore Seventy Four Lakh Eighty Three Thousand Six Hundred and Forty Eight";
      int[] num = new int[4];
      int first = 0;
      int u, h, t;
      System.Text.StringBuilder sb = new System.Text.StringBuilder();

      if (number < 0)
      {
          sb.Append("Minus");
          number = -number;
      }
      string[] words0 = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight", "Nine " };
      string[] words = { "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };

      string[] words2 = { "Twenty", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty", "Ninety " };

      string[] words3 = { "Thousand ", "Lakh ", "Crore " };

      num[0] = number % 1000; // units

      num[1] = number / 1000;

      num[2] = number / 100000;

      num[1] = num[1] - 100 * num[2]; // thousands

      num[3] = number / 10000000; // crores

      num[2] = num[2] - 100 * num[3]; // lakhs
      for (int i = 3; i > 0; i--)
      {
          if (num[i] != 0)
          {
              first = i;
              break;
          }
      }
      for (int i = first; i >= 0; i--)
      {
          if (num[i] == 0) continue;

          u = num[i] % 10; // ones

          t = num[i] / 10;

          h = num[i] / 100; // hundreds

          t = t - 10 * h; // tens

          if (h > 0) sb.Append(words0[h] + "Hundred ");

          if (u > 0 || t > 0)
          {
              if (h > 0 || i == 0) sb.Append("and ");
              if (t == 0)
                  sb.Append(words0[u]);

              else if (t == 1)
                  sb.Append(words[u]);
              else
                  sb.Append(words2[t - 2] + words0[u]);
          }

          if (i != 0) sb.Append(words3[i - 1]);
      }
      return sb.ToString().TrimEnd();

  }  

Thursday, 5 January 2012

display currency as Rs. 1,594.00

We can display the currency like this

by writing few lines of code


foreach (GridViewRow item in grdBill.Rows)
        {
            Label lblPrc = item.FindControl("lblPrice") as Label;
            double f = Convert.ToDouble(lblPrc.Text);
            System.Globalization.NumberFormatInfo nfi;
            nfi = new System.Globalization.NumberFormatInfo();
            nfi.CurrencyGroupSeparator = ",";
            nfi.CurrencySymbol = "Rs. ";
            lblPrc.Text = string.Format(nfi, "{0:C}", f);
            //lblPrc.Text=f.ToString("C");
        }

Thursday, 29 December 2011

sql server basic interview questions


Can you give me an overview of some of the database objects available foruse in SQL Server 2000?

You are looking for objects such as: tables, views,user-defined functions, and stored procedures; it's even better if they mentionadditional objects such as triggers. It's not a good sign if an applicantcannot answer this basic question.

What does NULL mean?

The value NULL is a very tricky subject in the databaseworld, so don't be surprised if several applicants trip up on this question.
The value NULL means UNKNOWN; it does not mean '' (emptystring). Assuming ANSI_NULLS are on in your SQL Server database, which they areby default, any comparison to the value NULL will yield the value NULL. Youcannot compare any value with an UNKNOWN value and logically expect to get ananswer. You must use the IS NULL operator instead.

What is a primary key? What is a foreign key?

A primary key is the field(s) in a table that uniquelydefines the row in the table; the values in the primary key are always unique.A foreign key is a constraint that establishes a relationship between twotables. This relationship typically involves the primary key field(s) from onetable with an adjoining set of field(s) in another table (although it could be thesame table). The adjoining field(s) is the foreign key.

What can be used to ensure that a field in a table only accepts a certain range of values?

This question can be answered a couple of different ways,but only one answer is a "good" one. The answer you want to hear is aCheck constraint, which is defined on a database table that limits the valuesentered into that column. These constraints are relatively easy to create, andthey are the recommended type for enforcing domain integrity in SQL Server.
Triggers can also be used to restrict the values accepted ina field in a database table, but this solution requires the trigger to bedefined on the table, which can hinder performance in certain situations. Forthis reason, Microsoft recommends Check constraints over all other methods forrestricting domain integrity.

What is a left outer join? Give an example.

Assume you have two tables, TableA and TableB. You need all the rows from TableA and all matching rows from TableB. You would use a left outer join to accomplish this with TableA being the left table as in the following.
SELECT *
FROM TableA
LEFT OUTER JOIN TableB
ON TableA.Col1 = TableB.Col1
 What is the default value of an integer data type in SQL Server 2005?
NULL
• What is the difference between a CHAR and a VARCHAR data type?
CHAR and VARCHAR data types are both non-Unicode character data types with a maximum length of 8,000 characters. The main difference between these 2 data types is that a CHAR data type is fixed-length while a VARCHAR is variable-length. If the number of characters entered in a CHAR data type column is less than the declared column length, spaces are appended to it to fill up the whole length.
Another difference is in the storage size wherein the storage size for CHAR is n bytes while for VARCHAR is the actual length in bytes of the data entered (and not n bytes).
You should use CHAR data type when the data values in a column are expected to be consistently close to the same size. On the other hand, you should use VARCHAR when the data values in a column are expected to vary considerably in size.

How
are the UNIQUE and PRIMARY KEY constraints different?

A UNIQUE constraint is similar to PRIMARY key, but you can have more than one UNIQUE constraint per table.

When you declare a UNIQUE constraint, SQL Server creates a UNIQUE index to speed up the process of searching for duplicates. In this case the index defaults to NONCLUSTERED index, because you can have only one CLUSTERED index per table.
* The number of UNIQUE constraints per table is limited by the number of indexes on the table i.e 249 NONCLUSTERED index and one possible CLUSTERED index.
Contrary to PRIMARY key UNIQUE constraints can accept NULL but just once. If the constraint is defined in a combination of fields, then every field can accept NULL and can have some values on them, as long as the combination values is unique.




Monday, 26 December 2011

Getting Last inserted Identity value in SQL server



Dear Friends


 Here i'm writing sql query by which you can get currently inserted rows identity column value


declare @id as int
set @id=SELECT IDENT_CURRENT(‘TableName’)




to use this your table must have an identity column

Thursday, 22 December 2011

How to convert Date format from dd/MM/yyyy to mm/dd/yyyy in asp.net





DEAR FRIENDS::

  SOME TIMES IN C# CODING DEVELOPER WANTS TO CONVERT DATETIME FORMAT AS MM/DD/YYY,  BUT SYSTEMS GIVES AN ERROR WHEN YOU INSERT 11/13/2011
IT GIVES AN ERROR
 because  datetime object default format is dd/mm/yyyy
and to convert datetime dd/mm/yyyy to mm/dd/yyyy format we have to write one  more line before converting datetime.

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

DateTime dtstart = Convert.ToDateTime(txtStart.Text);


I hope this helps you.

If You find right answer then please send me comment.



go through this link for wcf introduction
http://msdn.microsoft.com/en-us/library/aa480190.aspx

Wednesday, 21 December 2011

How to import MS Excel data to SQL Server table using c#.net



If you already have data in MS Excel file, and want to migrate your MS Excel data to SQL Server table, follow below steps
1. Lets take an example to import the data to SQL Server table, I am going to import student information data from ms excel sheet to tStudent SQL table,
My Excel sheet structure is looks like 

2. Now design a tStudent table in SQL server
Create Table
(
StudentName varchar(64),
RollNo varchar(16),
Course varchar(32),
your ms excel sheet and SQL table is ready, now its time to write c# code to import the excel sheet intotStudent table 
3.
Add these two name space in your class file
using System.Data.OleDb;
using System.Data.SqlClient;
Use following code
public void importDataFromExcel(string excelFilePath)
//Declare Variables - Edit these based on your particular situation
 string sSQLTable = "tDataMigrationTable";
 // make sure your sheet name is correct, here sheet name is Sheet1, so you can change your sheet name if have different
string myExcelDataQuery = "Select StudentName,RollNo,Course from [Sheet1$]"
try
{
//Create our connection strings
string sExcelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFilePath + ";Extended Properties=" + "\"Excel 8.0;HDR=YES;\"";

string sSqlConnectionString = "SERVER=MyDatabaseServerName;USER ID=DBUserId;PASSWORD=DBUserPassword;DATABASE=DatabaseName;CONNECTION RESET=FALSE"
//Execute a query to erase any previous data from our destination table
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
SqlConn.Close(); 
//Series of commands to bulk copy data from the excel file into our SQL table
OleDbConnection OleDbConn = new OleDbConnection(sExcelConnectionString);
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn); 
OleDbConn.Open(); 
OleDbDataReader dr = OleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString); 
bulkCopy.DestinationTableName = sSQLTable; 
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
OleDbConn.Close();
}
catch (Exception ex)
{
//handle exception
} 
In above function you have to pass ms excel file path as a parameter, if you want to import your data by providing client an access to select the excel file and import, then you might have to use asp.net file control, and upload the excel file on the server in some temp folder, then use the file path of the upload excel file and pass the path in above function. Once data import is completed then you can delete temporary file. 
The above method , first delete the existing data from the destination table, then import the excel data into the same table.

Friday, 16 December 2011

how to create random number in c#

Dear Friends..  
  Here i'm writing code to generate random number of five digit.



       public int getRandomID ()
       {
        Random r = new Random();
       return r.Next(10000,99999);
       }
Contact Us:

Email:

Vinodkumar434@gmail.com,
vinodtechnosoft@gmail.com

Skype Name:

vinodtechnosoft