Last active
September 3, 2018 00:59
-
-
Save sin2akshay/71116aadcc30398a35da416053bc12fb to your computer and use it in GitHub Desktop.
C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ReadDataFromDatabaseUsingDA() | |
{ | |
// 1 | |
// Open connection | |
using (SqlConnection c = new SqlConnection(@"Data Source=PCName\\SQLEXPRESS;Initial Catalog= DBEmployeeDetailsMock;Integrated Security=True")) | |
{ | |
c.Open(); | |
// 2 | |
// Create new DataAdapter | |
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs", c)) | |
{ | |
// 3 | |
// Use DataAdapter to fill DataTable | |
DataTable t = new DataTable(); | |
a.Fill(t); | |
} | |
} | |
foreach (DataRow dr in t.Rows) | |
{ | |
Console.WriteLine(dr["Employee_Id"].ToString()); | |
Console.WriteLine(dr["Employee_Name"].ToString()); | |
Console.WriteLine(Convert.ToDateTime(dr["DateOfJoining"]).ToShortDateString()); | |
Console.WriteLine(dr["Email_Id"].ToString()); | |
} | |
} | |
public void ReadDataFromDatabaseUsingDR() | |
{ | |
using (SqlConnection connection = new SqlConnection(connectionString)) | |
using (SqlCommand command = new SqlCommand("select * from Requests where Complete = 0", connection)) | |
{ | |
connection.Open(); | |
using (SqlDataReader reader = command.ExecuteReader()) | |
{ | |
while (reader.Read()) | |
{ | |
Console.WriteLine(reader["Username"].ToString()); | |
Console.WriteLine(reader["Item"].ToString()); | |
Console.WriteLine(reader["Amount"].ToString()); | |
Console.WriteLine(reader["Complete"].ToString()); | |
} | |
} | |
} | |
} | |
public void InsertToDatabase() | |
{ | |
SqlConnection sqlConnectionString = new SqlConnection | |
(@"Data Source=PCName\\SQLEXPRESS;Initial Catalog= DBEmployeeDetailsMock;Integrated Security=True"); | |
//In case of update | |
//command.Text = "UPDATE Student SET Address = @add, City = @city Where FirstName = @fn and LastName = @add"; | |
SqlCommand command = new SqlCommand("Insert into Employees values (@Employee_Id,@Employee_Name,@DateOfJoining,@Email_Id)", sqlConnectionString); | |
command.Parameters.Add(new SqlParameter("@Employee_Id", "001")); | |
command.Parameters.Add(new SqlParameter("@Employee_Name", "John")); | |
command.Parameters.Add(new SqlParameter("@DateOfJoining", Convert.ToDateTime("03/20/2012"))); | |
command.Parameters.Add(new SqlParameter("@Email_Id", "[email protected]")); | |
sqlConnectionString.Open(); | |
command.ExecuteNonQuery(); | |
sqlConnectionString.Close(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data.SqlClient; | |
using System.Data; | |
using System.Collections; | |
using System.Xml; | |
using System.Xml.Linq; | |
using System.Text.RegularExpressions; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Data.Sql; | |
using System.Xml.Serialization; | |
namespace EmployeeValidation | |
{ | |
public class EmployeeValidator | |
{ | |
/* | |
* Do not remove the attached TestProject. It is meant for auto evaluation of your source code. | |
* Do not attach any test classess to the attached test project. | |
* Do not attach any new test projects. | |
* You are not required to write any automated test cases. You are supposed to write only the code. | |
*/ | |
public void ProcessData(string xmlFilePath, string xmlFileName, SqlConnection connection) | |
{ | |
//Do your logic here | |
EmployeeValidator empVal = new EmployeeValidator(); | |
List<Employee> lstEmp = new List<Employee>(); | |
//Step 1 | |
//ReadAllEmployeesFromXmlFile | |
lstEmp = empVal.ReadAllEmployeesFromXmlFile(xmlFilePath, xmlFileName); | |
//Step 2 | |
//PickValidEmployees | |
lstEmp = empVal.PickValidEmployees(lstEmp); | |
//Step 3 | |
//SaveValidEmployeesToDataBase | |
empVal.SaveValidEmployeesToDB(lstEmp, connection); | |
} | |
public List<Employee> ReadAllEmployeesFromXmlFile(string xmlFilePath, string xmlFileName) | |
{ | |
//Read the employee details from the xml file and return it in List collection | |
//Do not hardcode the filename and the file path here | |
List<Employee> Emplst = new List<Employee>(); | |
XElement xelement = XElement.Load(xmlFilePath + xmlFileName); | |
IEnumerable<XElement> allEmployees = xelement.Elements(); | |
foreach (var employee in allEmployees) | |
{ | |
Emplst.Add(new Employee() | |
{ | |
EmployeeId = employee.Element("EmployeeId").Value, | |
EmployeeName = employee.Element("EmployeeName").Value, | |
EmailId = employee.Element("EmailId").Value, | |
DateOfJoining = employee.Element("DateOfJoining").Value | |
}); | |
} | |
return Emplst; | |
//Do not return the date with time appended to it. | |
} | |
public List<Employee> PickValidEmployees(List<Employee> employees) | |
{ | |
//Pick the valid employees from the List collection | |
//Return the valid employees in a List | |
List<Employee> empList = new List<Employee>(); | |
Regex IsNumeric = new Regex(@"\d+"); | |
Regex IsAlphaNumeric = new Regex(@"^\d*[a-zA-Z]+"); | |
Regex IsValidEmail = new Regex(@"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$"); | |
empList = employees.Select(x => employees.Find( | |
m => m.EmployeeName != null && | |
m.EmployeeName != string.Empty && | |
IsNumeric.IsMatch(m.EmployeeId.ToString()) && | |
IsAlphaNumeric.IsMatch(m.EmployeeName) | |
)).Distinct().ToList(); | |
return empList;//Return only valid employees in List | |
} | |
public void SaveValidEmployeesToDB(List<Employee> employees, SqlConnection connection) | |
{ | |
//Do not Prefix Database name in the SQL Query. Query should be "Insert into SBA.TableName" | |
//Should not be "Insert into DatabaseName.SBA.TableName" | |
//Do not hardcode the connection string here | |
string query = @"Insert into SBA.Employees(EmployeeId,EmployeeName,EmailId,DateOfJoining) | |
values(@EmployeeId,@EmployeeName,@EmailId,@DateOfJoining)"; | |
connection.Open(); | |
using (SqlCommand cmd = new SqlCommand(query, connection)) | |
{ | |
foreach (var employee in employees) | |
{ | |
cmd.Parameters.AddWithValue("@EmployeeId", employee.EmployeeId); | |
cmd.Parameters.AddWithValue("@EmployeeName", employee.EmployeeName); | |
cmd.Parameters.AddWithValue("@EmailId", employee.EmailId); | |
cmd.Parameters.AddWithValue("@DateOfJoining", employee.DateOfJoining); | |
int i = cmd.ExecuteNonQuery(); | |
} | |
} | |
connection.Close(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.IO; | |
namespace FileSystemDemo | |
{ | |
public class Watcher | |
{ | |
static void Main(string[] args) | |
{ | |
FileSystemWatcher watcher = new FileSystemWatcher(); | |
//Replace the path to your local path | |
string _path = @"C:\Users\153239\Desktop\FileSystemTest\"; | |
watcher.Path = _path; | |
watcher.EnableRaisingEvents = true; | |
watcher.Created += new FileSystemEventHandler(OnChanged); | |
watcher.Deleted += new FileSystemEventHandler(OnChanged); | |
watcher.Changed += new FileSystemEventHandler(OnChanged); | |
Console.WriteLine("FileSystemWatcher is listening to changes in the path :\n\n" + _path); | |
Console.Read(); | |
} | |
// Define the event handlers. | |
private static void OnChanged(object source, FileSystemEventArgs e) | |
{ | |
// Specify what is done when a file is changed, created, or deleted. | |
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string s = "Please ask for on arrival"; | |
//Reverse string character wise | |
var s_char = s.ToCharArray(); | |
Array.Reverse(s_char); | |
Console.WriteLine(new String(s_char)); | |
//Write to a file | |
FileStream fs = new FileStream("test.txt", FileMode.Append, FileAccess.Write); | |
StreamWriter sw = new StreamWriter(fs); | |
sw.WriteLine("Entering this string into the text file."); | |
sw.Flush(); | |
sw.Close(); | |
fs.Close(); | |
//Read character by character from a file | |
char ch; | |
StreamReader sr = new StreamReader("test.txt"); | |
do{ | |
ch = (char)reader.Read(); | |
Console.WriteLine(ch) | |
}while(!reader.EndofStream); | |
reader.Close(); | |
reader.Dispose(); | |
//Reverse words in a string | |
var s_split = s.Split(' '); | |
Array.Reverse(s_split); | |
Console.WriteLine(string.Join(" ", s_split)); | |
//Search a substring and print | |
string search = "ask"; | |
var askIndex = s.IndexOf("ask"); | |
Console.WriteLine(s.Substring(askIndex, search.Length)); | |
//Insert a substring before a given word | |
string name = "Akshay "; | |
Console.WriteLine(s.Insert(s.IndexOf("on"), name)); | |
//Replace a substring | |
Console.WriteLine(s.Replace("Please a", "A")); | |
//REGULAR EXPRESSIONS YOU SHOULD KNOW: | |
Matching a Username: /^[a-z0-9_-]{3,16}$/ | |
Matching a Password: /^[a-z0-9_-]{6,18}$/ | |
Matching a Hex Value: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/ | |
Matching a Slug: /^[a-z0-9-]+$/ | |
Matching an Email: /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/ | |
Matching a URL: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ | |
Matching an IP Address: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/ | |
Matching an HTML Tag: /^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/ | |
//Using Regex.Match | |
Match m = Regex.Match("123 Axxxxy", @"A.*y"); | |
if (m.Success) | |
{ | |
Console.WriteLine("Value = " + m.Value); | |
Console.WriteLine("Length = " + m.Length); | |
Console.WriteLine("Index = " + m.Index); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
////LINQ Queries//// | |
//--LINQ to Objects--// | |
//Finding repeated values in a list | |
this.numberList.GroupBy(num => num).Where(grp => grp.Count() > 1).Select(grp => grp.Key); | |
//Output Elements in Ascending order | |
var dispFruits = from fruits in this.fruitNameList orderby fruits ascending select fruits; | |
var dispFruits = this.fruitNameList.OrderBy(f => f.Length).Select(f => f); | |
//GroupBy | |
var numberGroups = | |
from n in numbers | |
group n by n % 5 into g | |
select new { Remainder = g.Key, Numbers = g }; | |
//Using where clause | |
var expensiveInStockProducts = | |
from p in products | |
where p.UnitsInStock > 0 && p.UnitPrice > 3.00M | |
select p | |
//Getting elements having length shorter their index in an array | |
var shortDigits = digits.Where((digit, index) => digit.Length < index); | |
//First or Default with condition | |
Product product789 = products.FirstOrDefault(p => p.ProductID == 789); | |
//Get Second number in the list greater than 5 | |
int fourthLowNum = ( | |
from n in numbers | |
where n > 5 | |
select n) | |
.ElementAt(1); | |
//--LINQ to SQL--// | |
//Reading from Database | |
static void Main(string[] args) | |
{ | |
MyDatabase db = new MyDatabase(); | |
var salesDept = from e in db.Employees | |
where e.Department == "Sales" | |
select e; | |
foreach (var employee in salesDept) | |
Console.WriteLine(employee.ID + " " + employee.Name); | |
Console.ReadLine(); | |
} | |
//Writing to Database | |
static void Main(string[] args) | |
{ | |
MyDatabase db = new MyDatabase(); | |
db.ExecuteCommand("CREATE TABLE Employees (ID int, Name varchar(50), Department varchar(50))"); | |
Employee employee1 = new Employee(); | |
employee1.ID = 101; | |
employee1.Name = "John Smith"; | |
employee1.Department = "Sales"; | |
db.Employees.InsertOnSubmit(employee1); | |
db.SubmitChanges(); | |
} | |
//--LINQ to XML--// | |
//To Fetch Values under Root Element | |
static void Main(string[] args) | |
{ | |
XElement xelement = XElement.Load(@"C:\Employees.xml"); | |
IEnumerable<XElement> employees = xelement.Elements(); | |
Console.WriteLine("List of all Employee Names :"); | |
foreach (var employee in employees) | |
{ | |
Console.WriteLine(employee.Element("Name").Value); | |
} | |
Console.ReadKey(); | |
} | |
//To Fetch using attributes of the elements | |
static void Main(string[] args) | |
{ | |
XElement xelement = XElement.Load("C:\\Employees.xml"); | |
var homePhone = from phoneno in xelement.Elements("Employee") | |
where (string)phoneno.Element("Phone").Attribute("Type") == "Home" | |
select phoneno; | |
Console.WriteLine("List HomePhone Nos."); | |
foreach (XElement xEle in homePhone) | |
{ | |
Console.WriteLine(xEle.Element("Phone").Value); | |
} | |
Console.ReadKey(); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
////READ FROM A FILE//// | |
// Example #1 | |
// Read the file as one string. | |
string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt"); | |
// Display the file contents to the console. Variable text is a string. | |
System.Console.WriteLine("Contents of WriteText.txt = {0}", text); | |
// Example #2 | |
// Read each line of the file into a string array. Each element | |
// of the array is one line of the file. | |
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt"); | |
// Display the file contents by using a foreach loop. | |
System.Console.WriteLine("Contents of WriteLines2.txt = "); | |
foreach (string line in lines) | |
{ | |
// Use a tab to indent each line of the file. | |
Console.WriteLine("\t" + line); | |
} | |
////WRITE TO A FILE//// | |
// Example #1: Write an array of strings to a file. | |
// Create a string array that consists of three lines. | |
string[] lines = { "First line", "Second line", "Third line" }; | |
// WriteAllLines creates a file, writes a collection of strings to the file, | |
// and then closes the file. You do NOT need to call Flush() or Close(). | |
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines); | |
// Example #2: Write one string to a text file. | |
string text = "A class is the most powerful data type in C#. Like a structure, " + | |
"a class defines the data and behavior of the data type. "; | |
// WriteAllText creates a file, writes the specified string to the file, | |
// and then closes the file. You do NOT need to call Flush() or Close(). | |
System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text); | |
// Example #3: Write only some strings in an array to a file. | |
// The using statement automatically flushes AND CLOSES the stream and calls | |
// IDisposable.Dispose on the stream object. | |
// NOTE: do not use FileStream for text files because it writes bytes, but StreamWriter | |
// encodes the output as text. | |
using (System.IO.StreamWriter file = | |
new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt")) | |
{ | |
foreach (string line in lines) | |
{ | |
// If the line doesn't contain the word 'Second', write the line to the file. | |
if (!line.Contains("Second")) | |
{ | |
file.WriteLine(line); | |
} | |
} | |
} | |
// Example #4: Append new text to an existing file. | |
// The using statement automatically flushes AND CLOSES the stream and calls | |
// IDisposable.Dispose on the stream object. | |
using (System.IO.StreamWriter file = | |
new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true)) | |
{ | |
file.WriteLine("Fourth line"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
////To serialize Vehicle class object to xml file.//// | |
public static void SerializeToXml(Vehicle vehicle) | |
{ | |
XmlSerializer xmlSerilizer = new XmlSerializer(typeof(Vehicle)); | |
TextWriter textWriter = new StreamWriter(@"C:\vehicle.xml"); | |
xmlSerilizer.Serialize(textWriter, vehicle);// Only public member are serialzed. | |
textWriter.Close(); | |
Console.WriteLine("\n Vehicle class object has been serialized !"); | |
} | |
////Binary Serialization and Deserialization//// | |
//This method serialize the object of account class. | |
public void SerializeAccObj(BinaryFormatter bFormatter, FileStream fStream, Account accObj) | |
{ | |
fStream = new FileStream(@"C:\BinarySerializeDemo.bin", FileMode.Create); | |
bFormatter.Serialize(fStream, accObj); | |
fStream.Close(); | |
Console.WriteLine("\nData is Serialized Successfully with Binary Formatter."); | |
} | |
//This method deserialize the object of account class. | |
public void DeserializeAccObj(BinaryFormatter bFormatter, FileStream fStream, Account accObj) | |
{ | |
fStream = new FileStream(@"C:\BinarySerializeDemo.bin", FileMode.Open); | |
accObj = bFormatter.Deserialize(fStream) as Account; | |
fStream.Close(); | |
Console.WriteLine("\n------Restoring the object back to its former state------"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Globalization:
http://msdn.microsoft.com/en-us/library/System.Globalization.aspx
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.80).aspx