Sunteți pe pagina 1din 18

Practical: Using C# Programming Constructs

1. Write a program diamond shape in c#


2. Calculating Square Roots with Improved Accuracy .

3. Converting Integer Numeric Data to Binary

4. Multiplying Matrices
5. C# XML To SQL Stored Procedure
6. C# Get All Files In A Directory
7. c# - How to create images thumbnail control using picturebox
8. C# Copy From Text File To DataTable
9. C# RegEx Validator
10.

Solutions

how to calculate total days between two dates

1. diamond shape in c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace star_dimand
{
class Program
{
static void Main(string[] args)
{
int i, j,n;
Console.WriteLine("Enter no for printing star in diamond shape");
n = int.Parse(Console.ReadLine());
for (i = 1; i <= n; i++)
{
for (j = n; j >= i; j--)
{
Console.Write(" ");
}
for (j = 1; j <= i; j++)
{
Console.Write("*");
}
for (j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}

for (i = 1; i <= n; i++)


{
for (j = 0; j <=i; j++)
{
Console.Write(" ");
}
for (j = n; j >= i; j--)
{
Console.Write("*");
}
for (j = n; j >= i; j--)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
output

Enter no for printing star in diamond shape


6
**
****
******
********
**********

************
************
**********
********
******
****
**

// Finds the integer square root of a positive number


public static int Isqrt(int num) {
if (0 == num) { return 0; } // Avoid zero divide
int n = (num / 2) + 1;
// Initial estimate, never low
int n1 = (n + (num / n)) / 2;
while (n1 < n) {
n = n1;
n1 = (n + (num / n)) / 2;
} // end while
return n;
} // end Isqrt()
2.

3.Convert Decimal To Binary In C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace zSharp2008.zMath
{
class cMath
{
string error = string.Empty;
public string Error
{
get
{
return error;
}
}
public string DecimalToBinary(string data)
{
string result = string.Empty;
int rem = 0;
try
{
if (!IsNumeric(data))
error = "Invalid Value - This is not a numeric value";
else
{
int num = int.Parse(data);
while (num > 0)
{
rem = num % 2;
num = num / 2;
result = rem.ToString() + result;
}
}
}
catch (Exception ex)
{
error = ex.Message;
}

return result;
}
private bool IsNumeric(string number)
{
bool result = false;
try
{
int temp = int.Parse(number);
result = true;
}
catch (Exception ex)
{
//Do nothing.
}
return result;
}
}
}

4. matrix multiplication in c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace matrix_multiplication
{
class Program
{
static void Main(string[] args)
{

int i, j;
int[,] a = new int[2, 2];
Console.WriteLine("Enter no for 2*2 matrix");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
a[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("First matrix is:");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(a[i,j]+"\t");
}
Console.WriteLine();
}

int[,] b = new int[2, 2];


Console.WriteLine("Enter no for 2*2 matrix");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
b[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("second matrix is:");

for (i = 0; i < 2; i++)


{
for (j = 0; j < 2; j++)
{
Console.Write(b[i, j] + "\t");
}
Console.WriteLine();
}

Console.WriteLine("Matrix multiplication is:");


int[,] c = new int[2, 2];
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{

c[i,j]=0;
for (int k = 0; k < 2; k++)
{
c[i, j] += a[i, k] * b[k, j];
}
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(c[i, j]+"\t");
}
Console.WriteLine();

Console.ReadKey();
}
}
}

output

Enter no for 2*2 matrix


8
7
6
0
First matrix is:
8

Enter no for 2*2 matrix


4
3
2
1
second matrix is:
4

Matrix multiplication is:


46

31

24

18

5.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
//using System.Data;
using System.Data.SqlClient;
namespace zSharp2010.XMLToDB
{
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime DOB { get; set; }
}
public class cXMLToDB
{
public cXMLToDB(string serverName, string dbaseName)
{
List<Employee> emps = new List<Employee>();
Employee emp = new Employee();
emp.ID = 1;
emp.Name = "George";
emp.DOB = Convert.ToDateTime("1/1/1990");
emps.Add(emp);
emp = new Employee();

emp.ID = 2;
emp.Name = "John";
emp.DOB = Convert.ToDateTime("2/2/1990");
emps.Add(emp);
emp = new Employee();
emp.ID = 3;
emp.Name = "Thomas";
emp.DOB = Convert.ToDateTime("3/3/1990");
emps.Add(emp);
StringWriter sw = GetDataInXMLFormat(emps);
SqlConnection cnn = new SqlConnection("SERVER=" + serverName +
";Integrated Security=true;DATABASE=" + dbaseName);
SqlCommand cmd = new SqlCommand("zTest", cnn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@xmlData", sw.ToString());
cnn.Open ();
SqlDataReader dr = cmd.ExecuteReader();
cnn.Close();
//dr can then be used
}
private StringWriter GetDataInXMLFormat(List<Employee> emps)
{
XmlSerializer xSerializer = new XmlSerializer(emps.GetType());
StringWriter sw = new StringWriter();
XmlTextWriter tw = new XmlTextWriter(sw);

xSerializer.Serialize(tw, emps);
return sw;
}
}
}
___________________________________________
The Stored Procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE zTest
@xmlData nVarchar (max)
AS
BEGIN
DECLARE @hdoc INT
CREATE TABLE #Emp (ID Int, Name VarChar(50), DOB DateTime)
IF NOT (@xmlData IS NULL)
BEGIN
EXEC @xmlData = sp_xml_preparedocument @hdoc OUTPUT, @xmlData
IF @xmlData <> 0
BEGIN RAISERROR('System was unable to parse the xml data', 16, 1) RETURN END
END
INSERT INTO #Emp (ID, Name, DOB)
SELECT ID, Name, DOB
FROM OPENXML(@hdoc, '/ArrayOfEmployee/Employee', 2)
WITH (ID INT, Name VARCHAR(50), DOB DateTime) --The fields from XML are case sensitive
SELECT *
FROM #Emp

DROP TABLE #Emp


END
GO
6.

public string[] GetAllFilesInDirectory(string path, string pattern = "*.*",

SearchOption options = SearchOption.TopDirectoryOnly)


{
if (path.Trim().Length == 0)
return null; //Error handler can go here
if ((pattern.Trim().Length == 0) || (pattern.Substring(pattern.Length - 1) == "."))
return null; //Error handler can go here
if (Directory.GetFiles(path, pattern).Length == 0)
return null; //Error handler can go here
return Directory.GetFiles (path, pattern, options);
}

7.
private void AddImageToThumbnail(string[] images)
{
int top = 0;
int ht = 150;
int counter = 0;
PictureBox[] pictures = new PictureBox[images.Length];
if (images.Length > 0)

{
//The panel pnlThumbnail will hold thumbnail pictures.
pnlThumbnail.AutoScroll = true;
foreach (string image in images)
{
try
{
pictures[counter] = new PictureBox();
pictures[counter].Parent = pnlThumbnail;
pictures[counter].Top = top;
pictures[counter].Height = ht;
pictures[counter].Width = pnlThumbnail.Width - 10;
pictures[counter].Image = new Bitmap(image);
pictures[counter].BorderStyle = BorderStyle.FixedSingle;
top += pictures[counter].Size.Height + 5;
pictures[counter].SizeMode = PictureBoxSizeMode.StretchImage;
pictures[counter].Show();
//If user clicks on a picture then this event gets triggered, it can be used to display
the current image.
pictures[counter].Click += new EventHandler(fImage_Click);
pictures[counter].ImageLocation = image;
counter++;
textThumbnailCount.Text = counter.ToString();
}
catch
{
//Error handler

}
}
//Show the first image in the thumbnail
//fImage_Click(pictures[0], null);
}
}

Calling function:
string[] images = Directory.GetFiles(@"C:\Temp\Images\", "*.tif");
AddImageToThumbnail(images);

8.
private DataTable ReadAsDataTable(string file, bool hasHeader, char seperator)
{
DataTable dt = new DataTable();
StreamReader reader = new StreamReader(file);
string line = string.Empty;
string[] data = null;
int counter = 0;
while (reader.Peek() != -1)
{
line = reader.ReadLine();
data = line.Split(seperator);
if (hasHeader)
{

if (counter == 0)
{
foreach (string item in data)
{
dt.Columns.Add(item);
}
}
else
dt.Rows.Add(data);
}
else
dt.Rows.Add(data);
counter++;
}
reader.Close();
return dt;
}

Calling function
DataTable result = ReadAsDataTable(@"C:\temp\data.csv", true, ',');
9. //A simple RegEx validotor.

private bool RegExValidator(string expression, string toMatch, RegexOptions


options = RegexOptions.None)
{
bool isValid = true;
try

{
Regex validator = new Regex(expression, options);
isValid = validator.IsMatch(toMatch);
}
catch (Exception ex)
{
//error handler can go here;
isValid = false;
}
return isValid;
}
Calling method:
bool isValid = RegExValidator(@"^[-+]?[0-9]\d{0,11}(\.\d{1,2})?%?$", "1234",
RegexOptions.None);

10.

using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Total_days_from_two_dates_csharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btn_total_Click(object sender,


EventArgs e)
{
int Totaldays = duration(textBox1.Text,
textBox2.Text);
label1.Text = Convert.ToString(Totaldays);
}
public int duration(string startdate, string
enddate)
{
DateTime dt1 =
DateTime.Parse(Convert.ToDateTime(textBox1.Text).ToStrin
g("dd/MM/yyyy"));
DateTime dt2 =
DateTime.Parse(Convert.ToDateTime(textBox2.Text).ToStrin
g("dd/MM/yyyy"));
TimeSpan ts = dt2.Subtract(dt1);
int days = ts.Days;
return days;
}
}
}

S-ar putea să vă placă și