Showing posts with label 小程序. Show all posts
Showing posts with label 小程序. Show all posts

Sunday, June 21, 2009

C# open folder dialog (FolderBrowserDialog)

In .Net GUI Applications, Interaction with User on selecting files is a very basic topic. In the following code samples, I have demonstrate how to select files ( in comment code), more importantly, give an example code on how to get a folder name form the windows open dialog box. Something Interesting here is that you actually can’t get the folder name easily. (I mean select a folder, you can still select the file then get the full path, which include the folder name) The best option is to use FolderBrowserDialog !

Ok, now here is the sample code. Enjoy.

        private void importToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
string startupPath = Application.StartupPath;
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
dialog.Description = "Open a folder which contains the xml output";
dialog.ShowNewFolderButton = false;
dialog.RootFolder = Environment.SpecialFolder.MyComputer;
if(dialog.ShowDialog() == DialogResult.OK)
{
string folder = dialog.SelectedPath;
foreach (string fileName in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly))
{
SQLGenerator.GenerateSQLTransactions(Path.GetFullPath(fileName));
}
}
}
//using (OpenFileDialog dialog = new OpenFileDialog())
//{
// dialog.Filter = "xml files (*.xml)|*.xml";
// dialog.Multiselect = false;
// dialog.InitialDirectory = ".";
// dialog.Title = "Select file (only in XML format)";
// if (dialog.ShowDialog() == DialogResult.OK)
// {
// SQLGenerator.GenerateSQLTransactions(Application.StartupPath + Settings.Default.xmlFile);
// }
//}
}
catch (Exception exc)
{
MessageBox.Show("Import failed because " + exc.Message + " , please try again later.");
}

}

Tuesday, April 14, 2009

c# IIR Filter

This is an c# implementation of the matlab function Filter, which is a digital infinite impulse response IIR filter.  The code is fairly similar to the C++ version, which I use as an reference. Using the class below is much easier than use signal processing library. The default coefficient was the taken from Matlab documentation.

 class Filter
{
private List<double> a;
private List<double> b;

//default Filter
public Filter()
{

b = new List<double>();
b.Add(0.002899695497431);
b.Add(-0.006626465760968);
b.Add(0.004033620976099);
b.Add(0.004033620976099);
b.Add(-0.006626465760968);
b.Add(0.002899695497431);

a = new List<double>();
a.Add(1.000000000000000);
a.Add(-4.229081817661462);
a.Add(7.205853343227314);
a.Add(-6.177477993982333);
a.Add(2.662714482809827);
a.Add(-0.461394312968222);

}

public Filter(List<double> a, List<double> b)
{
this.a = a;
this.b = b;
}

public void Applyfilter(List<double> x, out List<double> y)
{
int ord = a.Count -1;
int np = x.Count -1;

if (np < ord)
{
for(int k=0;k<ord-np;k++)
x.Add(0.0);
np = ord;
}

y = new List<double>();
for(int k=0;k<np+1;k++)
{
y.Add(0.0);
}
int i, j;
y[0] = b[0] * x[0];
for (i = 1; i < ord + 1; i++)
{
y[i] = 0.0;
for (j = 0; j < i + 1; j++)
y[i] = y[i] + b[j] * x[i - j];
for (j = 0; j < i; j++)
y[i] = y[i] - a[j + 1] * y[i - j - 1];
}
/* end of initial part */
for (i = ord + 1; i < np +1; i++)
{
y[i] = 0.0;
for (j = 0; j < ord + 1; j++)
y[i] = y[i] + b[j] * x[i - j];
for (j = 0; j < ord; j++)
y[i] = y[i] - a[j + 1] * y[i - j - 1];
}
}
}

Tuesday, March 17, 2009

c# how to read write excel spreedsheet

用.net读写excel文件有很多种方法,这里介绍一种比较简单的:

使用Microsoft.Office.Interop.Excel

下面是一个我项目中的一个读取函数的删减版本,要用上using Excel = Microsoft.Office.Interop.Excel;

除了读取一个Range里的东西,下面的函数演示了怎么枚举所有的行列,这样就可以不用事先知道Range了。

private void LoadExcelFile(string annotationFile)
{
Excel.Workbooks objBooks;
Excel.Sheets objSheets;
Excel._Worksheet objSheet;
Excel.Range range;

try
{
// Instantiate Excel and start a new workbook.
objApp = new Excel.Application();
objBooks = objApp.Workbooks;
objBook = objBooks.Open(annotationFile, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
objSheets = objBook.Worksheets;
objSheet = (Excel._Worksheet)objSheets.get_Item(1);


//Get a range of data.
range = objSheet.get_Range("A1", Missing.Value);
range = range.get_Resize(1, 1);
double videoTimeOffset = (double)range.get_Value(Missing.Value);

//Another way of getting data
string output = "";
int rowIndex = 3;
//object colIndex2 = 11;
while (((Excel.Range)objSheet.Cells[rowIndex, 1]).Value2 != null)
{
string tmp = "";
int lapID;
SwimLap.StrokeTypeEnum strokeType;
string lapType; //Warm Up/Down Main

tmp = (((Excel.Range)objSheet.Cells[rowIndex, 1]).Value2 == null) ? "-" : ((Excel.Range)objSheet.Cells[rowIndex, 1]).Value2.ToString();
if (tmp.Equals(" ") || tmp.Equals("-"))
lapID = 0;
else
lapID = Convert.ToInt32(tmp);

tmp = (((Excel.Range)objSheet.Cells[rowIndex, 2]).Value2 == null) ? "-" : ((Excel.Range)objSheet.Cells[rowIndex, 2]).Value2.ToString();
strokeType = SwimLap.GetStrokeTypeEnum(tmp);

lapType = (((Excel.Range)objSheet.Cells[rowIndex, 3]).Value2 == null) ? "-" : ((Excel.Range)objSheet.Cells[rowIndex, 3]).Value2.ToString();


SwimLap sl = new SwimLap(videoTimeOffset,lapID,strokeType,lapType,lapTime,lapVideoStartTime,lapVideoEndTime,strokeCount,confidence,isTurn,isVideoFullLap,startType,strokeRate);

ss.AddLap(sl);

rowIndex++;

}

objBooks.Close();
objApp.Quit();

}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}

Friday, March 13, 2009

写了个小程序,parse网页的traceroute信息

动态域名服务商基本都被屏蔽了,DNS解析不了,只能通过IP访问。写了个程序解决这个问题。

 

以google为例子,程序会抓取信息,然后放到你的hosts文件里面,这样www.google.com就可以直接用了。 目标地址是 http://www.telstra.net.au/cgi-bin/trace?www.google.com 如果你的机器能够访问的话,应该程序就能使。代码如下,想修改的自己可以拿c#改。


static void Main(string[] args)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                byte[] buf = new byte[8192];
                // prepare the web page we will be asking for
                HttpWebRequest request = (HttpWebRequest)
                    WebRequest.Create(@"http://www.telstra.net.au/cgi-bin/trace?www.google.com");
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream resStream = response.GetResponseStream();
                string tempString = null;
                int count = 0;
                do
                {
                    count = resStream.Read(buf, 0, buf.Length);
                    if (count != 0)
                    {
                        // translate from bytes to ASCII text
                        tempString = Encoding.ASCII.GetString(buf, 0, count);
                        sb.Append(tempString);
                    }
                } while (count > 0);
                string resovle_to_ip = "\twww.google.com";
                string regexPattern = @"traceroute to www.l.google.com \((?<ip>[^a-zA-Z]+)\),";
                Regex re = new Regex(regexPattern, RegexOptions.ExplicitCapture);
                Match m = re.Match(sb.ToString());
                resovle_to_ip = m.Groups["ip"].Value + resovle_to_ip;
                try
                {
                    using (StreamReader rfile = new StreamReader(@"C:\WINDOWS\system32\drivers\etc\hosts"))
                    {
                        using (StreamWriter wfile = new StreamWriter(@"C:\WINDOWS\system32\drivers\etc\hosts_temp"))
                        {
                            string line;
                            while ((line = rfile.ReadLine()) != null)
                            {
                                if (!line.Contains("www.google.com"))
                                    wfile.WriteLine(line);
                            }
                            wfile.WriteLine(resovle_to_ip);
                            wfile.Close();
                        }
                        rfile.Close();
                    }
                    File.Copy(@"C:\WINDOWS\system32\drivers\etc\hosts_temp", @"C:\WINDOWS\system32\drivers\etc\hosts", true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                Console.WriteLine("({0}) successfully written to hosts file.", resovle_to_ip);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }