using System;
using System.Diagnostics;
class MyProcessManipulator {
static void Main(string[] args) {
Process ieProc = Process.Start("IExplore.exe", "www.intertechtraining.com");
Console.Write("--> Hit a key to kill {0}...", ieProc.ProcessName);
try {
ieProc.Kill();
} catch { } // In case user already killed it...
}
}
Month: February 2011
Get current Process Name
using System;
using System.Reflection;
using System.Diagnostics;
class AssemType
{
public static void Main(string[] args)
{
Process p = Process.GetCurrentProcess();
string assemblyName = p.ProcessName + ".exe";
Console.WriteLine("Examining : {0}", assemblyName);
Assembly a = Assembly.LoadFrom(assemblyName);
Type[] types = a.GetTypes();
foreach(Type t in types)
{
Console.WriteLine("
Type : {0}",t.FullName);
Console.WriteLine(" Base class : {0}",t.BaseType.FullName);
}
}
}
Polynomial all
/*
A Programmer's Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress L.P.
ISBN: 1-893115-62-3
*/
Polynomialall.zip( 11 k)
The simplest polynomial implementation
/*
A Programmer's Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress L.P.
ISBN: 1-893115-62-3
*/
//Compile:
//csc /debug- /o+ /out:polynomial.exe /r:system.dll Counter.cs Driver.cs PolySimple.cs polynomial.cs ipoly.cs
//File:PolySimple.cs
namespace Polynomial
{
using System;
///
///
///
/// This implementation loops through the coefficients and evaluates each
/// term of the polynomial.
///
class PolySimple: Polynomial
{
public PolySimple(params double[] coefficients): base(coefficients)
{
}
public override double Evaluate(double value)
{
double retval = coefficients[0];
double f = value;
for (int i = 1; i < coefficients.Length; i++)
{
retval += coefficients[i] * f;
f *= value;
}
return(retval);
}
}
}
//File:Polynomial.cs
namespace Polynomial
{
using System;
using PolyInterface;
///
///
public abstract class Polynomial
{
public Polynomial(params double[] coefficients)
{
this.coefficients = new double[coefficients.Length];
for (int i = 0; i < coefficients.Length; i++)
this.coefficients[i] = coefficients[i];
}
public abstract double Evaluate(double value);
protected double[] coefficients = null;
}
}
//File:IPoly.cs
namespace PolyInterface
{
///
///
public interface IPolynomial
{
double Eval(double value);
}
}
//File:Driver.cs
namespace Polynomial
{
using System;
using System.Diagnostics;
///
///
public class Driver
{
///
///
/// The polynomial to evaluate
public static double TimeEvaluate(Polynomial p)
{
double value = 2.0;
Console.WriteLine(“{0}”, p.GetType().Name);
// Time the first iteration. This one is done
// separately so that we can figure out the startup
// overhead separately…
long start = Counter.Value;
p.Evaluate(0.0); // do the first iteration.
long delta = Counter.Value – start;
Console.WriteLine(“Overhead = {0:f2} seconds”, (double) delta/Counter.Frequency);
Console.WriteLine(“Eval({0}) = {1}”, value, p.Evaluate(value));
int limit = 100000;
start = Counter.Value;
// Evaluate the polynomial the required number of
// times.
double result = 0;
for (int i = 0; i < limit; i++)
{
result += p.Evaluate(value);
}
delta = Counter.Value - start;
double ips = (double) limit * ((double)Counter.Frequency / (double) delta);
Console.WriteLine("Evalutions/Second = {0:f0}", ips);
Console.WriteLine();
return(ips);
}
///
///
///
public static void Eval(double[] coeff)
{
Polynomial[] imps = new Polynomial []
{
new PolySimple(coeff),
};
double[] results = new double[imps.Length];
for (int index = 0; index < imps.Length; index++)
{
results[index] = TimeEvaluate(imps[index]);
}
Console.WriteLine("Results for length = {0}", coeff.Length);
for (int index = 0; index < imps.Length; index++)
{
Console.WriteLine("{0} = {1:f0}", imps[index], results[index]);
}
Console.WriteLine();
}
///
///
public static void Main()
{
Eval(new Double[] {5.5});
// Evaluate the first polynomial, with 7 elements
double[] coeff =
new double[] {5.5, 7.0, 15, 30, 500, 100, 1};
Eval(coeff);
// Evaluate the second polynomial, with 50 elements
coeff = new double[50];
for (int index = 0; index < 50; index++)
{
coeff[index] = index;
}
Eval(coeff);
}
}
}
//File:Counter.cs
using System;
namespace Polynomial
{
class Counter
{
public static long Frequency
{
get
{
long freq = 0;
QueryPerformanceFrequency(ref freq);
return freq;
}
}
public static long Value
{
get
{
long count = 0;
QueryPerformanceCounter(ref count);
return count;
}
}
[System.Runtime.InteropServices.DllImport("KERNEL32")]
private static extern bool QueryPerformanceCounter( ref long lpPerformanceCount);
[System.Runtime.InteropServices.DllImport("KERNEL32")]
private static extern bool QueryPerformanceFrequency( ref long lpFrequency);
}
}
Polynomial.zip( 2 k)[/csharp]
This module contains the recursive descent parser that recognizes variables
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
/*
This module contains the recursive descent
parser that recognizes variables.
*/
using System;
// Exception class for parser errors.
class ParserException : ApplicationException {
public ParserException(string str) : base(str) { }
public override string ToString() {
return Message;
}
}
class Parser {
// Enumerate token types.
enum Types { NONE, DELIMITER, VARIABLE, NUMBER };
// Enumerate error types.
enum Errors { SYNTAX, UNBALPARENS, NOEXP, DIVBYZERO };
string exp; // refers to expression string
int expIdx; // current index into the expression
string token; // holds current token
Types tokType; // holds token's type
// Array for variables.
double[] vars = new double[26];
public Parser() {
// Initialize the variables to zero.
for(int i=0; i < vars.Length; i++)
vars[i] = 0.0;
}
// Parser entry point.
public double Evaluate(string expstr)
{
double result;
exp = expstr;
expIdx = 0;
try {
GetToken();
if(token == "") {
SyntaxErr(Errors.NOEXP); // no expression present
return 0.0;
}
EvalExp1(out result); // now, call EvalExp1() to start
if(token != "") // last token must be null
SyntaxErr(Errors.SYNTAX);
return result;
} catch (ParserException exc) {
// Add other error handling here, as desired.
Console.WriteLine(exc);
return 0.0;
}
}
// Process an assignment.
void EvalExp1(out double result)
{
int varIdx;
Types ttokType;
string temptoken;
if(tokType == Types.VARIABLE) {
// save old token
temptoken = String.Copy(token);
ttokType = tokType;
// Compute the index of the variable.
varIdx = Char.ToUpper(token[0]) - 'A';
GetToken();
if(token != "=") {
PutBack(); // return current token
// restore old token -- not an assignment
token = String.Copy(temptoken);
tokType = ttokType;
}
else {
GetToken(); // get next part of exp
EvalExp2(out result);
vars[varIdx] = result;
return;
}
}
EvalExp2(out result);
}
// Add or subtract two terms.
void EvalExp2(out double result)
{
string op;
double partialResult;
EvalExp3(out result);
while((op = token) == "+" || op == "-") {
GetToken();
EvalExp3(out partialResult);
switch(op) {
case "-":
result = result - partialResult;
break;
case "+":
result = result + partialResult;
break;
}
}
}
// Multiply or divide two factors.
void EvalExp3(out double result)
{
string op;
double partialResult = 0.0;
EvalExp4(out result);
while((op = token) == "*" ||
op == "/" || op == "%") {
GetToken();
EvalExp4(out partialResult);
switch(op) {
case "*":
result = result * partialResult;
break;
case "/":
if(partialResult == 0.0)
SyntaxErr(Errors.DIVBYZERO);
result = result / partialResult;
break;
case "%":
if(partialResult == 0.0)
SyntaxErr(Errors.DIVBYZERO);
result = (int) result % (int) partialResult;
break;
}
}
}
// Process an exponent.
void EvalExp4(out double result)
{
double partialResult, ex;
int t;
EvalExp5(out result);
if(token == "^") {
GetToken();
EvalExp4(out partialResult);
ex = result;
if(partialResult == 0.0) {
result = 1.0;
return;
}
for(t=(int)partialResult-1; t > 0; t--)
result = result * (double)ex;
}
}
// Evaluate a unary + or -.
void EvalExp5(out double result)
{
string op;
op = "";
if((tokType == Types.DELIMITER) &&
token == "+" || token == "-") {
op = token;
GetToken();
}
EvalExp6(out result);
if(op == "-") result = -result;
}
// Process a parenthesized expression.
void EvalExp6(out double result)
{
if((token == "(")) {
GetToken();
EvalExp2(out result);
if(token != ")")
SyntaxErr(Errors.UNBALPARENS);
GetToken();
}
else Atom(out result);
}
// Get the value of a number or variable.
void Atom(out double result)
{
switch(tokType) {
case Types.NUMBER:
try {
result = Double.Parse(token);
} catch (FormatException) {
result = 0.0;
SyntaxErr(Errors.SYNTAX);
}
GetToken();
return;
case Types.VARIABLE:
result = FindVar(token);
GetToken();
return;
default:
result = 0.0;
SyntaxErr(Errors.SYNTAX);
break;
}
}
// Return the value of a variable.
double FindVar(string vname)
{
if(!Char.IsLetter(vname[0])){
SyntaxErr(Errors.SYNTAX);
return 0.0;
}
return vars[Char.ToUpper(vname[0])-'A'];
}
// Return a token to the input stream.
void PutBack()
{
for(int i=0; i < token.Length; i++) expIdx--;
}
// Handle a syntax error.
void SyntaxErr(Errors error)
{
string[] err = {
"Syntax Error",
"Unbalanced Parentheses",
"No Expression Present",
"Division by Zero"
};
throw new ParserException(err[(int)error]);
}
// Obtain the next token.
void GetToken()
{
tokType = Types.NONE;
token = "";
if(expIdx == exp.Length) return; // at end of expression
// skip over white space
while(expIdx < exp.Length &&
Char.IsWhiteSpace(exp[expIdx])) ++expIdx;
// trailing whitespace ends expression
if(expIdx == exp.Length) return;
if(IsDelim(exp[expIdx])) { // is operator
token += exp[expIdx];
expIdx++;
tokType = Types.DELIMITER;
}
else if(Char.IsLetter(exp[expIdx])) { // is variable
while(!IsDelim(exp[expIdx])) {
token += exp[expIdx];
expIdx++;
if(expIdx >= exp.Length) break;
}
tokType = Types.VARIABLE;
}
else if(Char.IsDigit(exp[expIdx])) { // is number
while(!IsDelim(exp[expIdx])) {
token += exp[expIdx];
expIdx++;
if(expIdx >= exp.Length) break;
}
tokType = Types.NUMBER;
}
}
// Return true if c is a delimiter.
bool IsDelim(char c)
{
if((" +-/*%^=()".IndexOf(c) != -1))
return true;
return false;
}
}
// Demonstrate the parser.
public class ParserDemo1 {
public static void Main()
{
string expr;
Parser p = new Parser();
Console.WriteLine("Enter an empty expression to stop.");
for(;;) {
Console.Write("Enter expression: ");
expr = Console.ReadLine();
if(expr == "") break;
Console.WriteLine("Result: " + p.Evaluate(expr));
}
}
}
Regular Expressions: More Complex Parsing
/*
A Programmer's Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress L.P.
ISBN: 1-893115-62-3
*/
// 17 - StringsRegular ExpressionsMore Complex Parsing
// copyright 2000 Eric Gunnerson
// file=logparse.cs
// compile with: csc logparse.cs
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
public class MoreComplexParsing
{
public static void Main(string[] args)
{
if (args.Length == 0) //we need a file to parse
{
Console.WriteLine("No log file specified.");
}
else
ParseLogFile(args[0]);
}
public static void ParseLogFile(string filename)
{
if (!System.IO.File.Exists(filename))
{
Console.WriteLine ("The file specified does not exist.");
}
else
{
FileStream f = new FileStream(filename, FileMode.Open);
StreamReader stream = new StreamReader(f);
string line;
line = stream.ReadLine(); // header line
line = stream.ReadLine(); // version line
line = stream.ReadLine(); // Date line
Regex regexDate= new Regex(@":s(?<date>[^s]+)s");
Match match = regexDate.Match(line);
string date = "";
if (match.Length != 0)
date = match.Groups["date"].ToString();
line = stream.ReadLine(); // Fields line
Regex regexLine =
new Regex( // match digit or :
@"(?<time>(d|:)+)s" +
// match digit or .
@"(?<ip>(d|.)+)s" +
// match any non-white
@"(?<method>S+)s" +
// match any non-white
@"(?<uri>S+)s" +
// match any non-white
@"(?<status>d+)");
// read through the lines, add an
// IISLogRow for each line
while ((line = stream.ReadLine()) != null)
{
//Console.WriteLine(line);
match = regexLine.Match(line);
if (match.Length != 0)
{
Console.WriteLine("date: {0} {1}", date,
match.Groups["time"]);
Console.WriteLine("IP Address: {0}",
match.Groups["ip"]);
Console.WriteLine("Method: {0}",
match.Groups["method"]);
Console.WriteLine("Status: {0}",
match.Groups["status"]);
Console.WriteLine("URI: {0}
",
match.Groups["uri"]);
}
}
f.Close();
}
}
}
Set NumberGroupSeparator
using System.Globalization;
using System;
public class MainClass {
public static void Main() {
NumberFormatInfo f = new NumberFormatInfo();
f.NumberGroupSeparator = " ";
Console.WriteLine(12345.6789.ToString("N3", f)); // 12 345.679
}
}

