Xây dựng ứng dụng kiểm thử phần mềm tự động C#
- TestForm.cs
- AutomatedTest /
- project /
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.Reflection;
10 using System.Xml;
11 using System.Xml.XPath;
12 using System.IO;
13 using System.CodeDom;
14 using System.CodeDom.Compiler;
15 using System.Diagnostics;
16 using Excel = Microsoft.Office.Interop.Excel;
17
18 namespace AutomatedTest
19 {
20 public partial class TestForm : Form
21 {
22 public TestForm()
23 {
24 InitializeComponent();
25 }
26 private string AssemblyNameToTest;
27 private void GetAssemblyName()
28 {
29 openFileDialog1.Title = "DLL under test";
30 openFileDialog1.Filter = "DLL files (*.dll)|*.dll|Executable files (*.exe)|*.exe|All files (*.*)|*.*";
31
32
33 if (openFileDialog1.ShowDialog() == DialogResult.OK)
34 {
35 AssemblyNameToTest = openFileDialog1.FileName;
36 }
37 else
38 {
39 AssemblyNameToTest = "";
40 }
41 }
42 private void GetTypesOfAssemblyUnderTest()
43 {
44 if (AssemblyNameToTest.Length <= 0)
45 {
46 return;
47 }
48 TypeUnderTest typeDUT = new TypeUnderTest();
49 try
50 {
51 Assembly asm = Assembly.LoadFrom(AssemblyNameToTest);
52 Type[] tys = asm.GetTypes();
53 foreach (Type ty in tys)
54 {
55 typeDUT.chckListType.Items.Add(ty.Name);
56 }
57
58 }
59 catch (Exception ex)
60 {
61 MessageBox.Show(ex.Message);
62 return;
63 }
64 typeDUT.lblTypeAvailable.Text = "Thư mục chứa các lớp để kiểm thử:\n" + AssemblyNameToTest;
65 typeDUT.ShowDialog();
66
67 PassSelectedTypesUT(typeDUT);
68 }
69
70 private string m_typesDUT;
71 private void PassSelectedTypesUT(TypeUnderTest typeDUT)
72 {
73 if (typeDUT.TypeState == DialogResult.OK)
74 {
75 m_typesDUT = "";
76 for (int i = 0; i < typeDUT.chckListType.Items.Count; i++)
77 {
78 if (typeDUT.chckListType.GetItemChecked(i))
79 m_typesDUT = m_typesDUT + typeDUT.chckListType.GetItemText(typeDUT.chckListType.Items[i]) + " ";
80 }
81 }
82 else
83 {
84 m_typesDUT = "";
85 }
86 }
87
88 private Assembly DUTAsm;
89 private string xlsDataStoreFilename = @"C:/temp/SoftTestDataStore.xls"; //textbox2.text
90 private int Tongsodong;
91 private void Khoitaophuongthuckiemthu()
92 {
93
94 int i = 2;
95 if (m_typesDUT.Length > 1)
96 {
97 //mở sheet trong Excel
98 TaoSheet();
99
100 //load file dll
101 try
102 {
103 DUTAsm = Assembly.LoadFrom(AssemblyNameToTest);
104 }
105 catch (Exception err)
106 {
107 MessageBox.Show(err.Message);
108 }
109
110 Type[] types = null;
111 types = DUTAsm.GetTypes();
112
113 foreach (Type t in types)
114 {
115 if (m_typesDUT.IndexOf(t.Name) > -1)
116 {
117 ConstructorInfo[] cis = t.GetConstructors();
118 foreach (ConstructorInfo ci in cis)
119 {
120 LayCacCell(xSheet, i, 1, t.Name, null);
121 LayCacCell(xSheet, i, 2, t.Name, null);
122 ParameterInfo[] ps = ci.GetParameters();
123 foreach (ParameterInfo p in ps)
124 {
125 LayCacCell(xSheet, i, p.Position + 3, p.Name, p);
126 }
127 i++;
128 }
129
130 MethodInfo[] ms = t.GetMethods();
131
132 foreach (MethodInfo m in ms)
133 {
134 LayCacCell(xSheet, i, 1, t.Name, null);
135 LayCacCell(xSheet, i, 2, m.Name, null);
136 ParameterInfo[] ps = m.GetParameters();
137 foreach (ParameterInfo p in ps)
138 {
139 LayCacCell(xSheet, i, p.Position + 3, p.Name, p);
140 }
141 if (m.ReturnType.ToString() == "System.Void")
142 {
143 }
144 else
145 {
146 ThemGiaTriMongDoi(xSheet, i, m);
147 }
148 i++;
149 }
150 }
151 }
152
153 try
154 {
155 xBook.SaveAs(xlsDataStoreFilename, -4143, "", "", false, false, 0, "", 0, "", "", "");
156 }
157 catch (Exception err) { MessageBox.Show(err.Message); }
158 }
159 Tongsodong = i;
160 }
161
162 Excel.Application xApp;
163 Excel.Workbook xBook;
164 Excel.Worksheet xSheet;
165 private void TaoSheet()
166 {
167 xApp = new Excel.Application();
168 xBook = xApp.Workbooks.Add(1);
169 xSheet = (Excel.Worksheet)xBook.ActiveSheet;
170 xSheet.Cells.set_Item(1, 1, "TÊN LỚP");
171 xSheet.Cells.set_Item(1, 2, "TÊN PHƯƠNG THỨC");
172 xSheet.Cells.set_Item(1, 3, "CÁC THAM SỐ ĐẦU VÀO");
173 Excel.Range range;
174 range = xSheet.get_Range("A1", "Z1");
175 range.Interior.ColorIndex = 8;
176 range.Columns.AutoFit();
177 range.Font.Bold = true;
178 xApp.Visible = true;
179 }
180
181 private void ThemGiaTriMongDoi(Excel.Worksheet xs, int shtRow, MethodInfo mi)
182 {
183 Excel.Range range = null;
184 int parCount = 0;
185 try
186 {
187 foreach (ParameterInfo pi in mi.GetParameters())
188 {
189 parCount++;
190 }
191 string ColChar = TestUtility.ConvCHAR(parCount + 3);
192
193 range = xs.get_Range(ColChar + shtRow, ColChar + shtRow);
194 range.AddComment("giá trị mong đợi " + mi.ReturnType.ToString());
195 range.Interior.ColorIndex = 43;
196 range.Font.ColorIndex = 3;
197 range.Font.Bold = true;
198 }
199 catch { }
200 }
201
202 private void LayCacCell(Excel.Worksheet xs, int shtRow, int shtCol, string setText, ParameterInfo p)
203 {
204 string ColChar = TestUtility.ConvCHAR(shtCol);
205 Excel.Range range = null;
206 //Giá trị mong đợi trả giá trị trả về của tham số đưa vào
207 range = xs.get_Range(ColChar + shtRow, ColChar + shtRow);
208
209 if (null != p)
210 {
211 range.Value2 = TestUtility.SysToCSPro(p.ParameterType.ToString()) + " " + setText;
212 }
213 else
214 range.Value2 = setText;
215
216 if (p != null)
217 {
218 DuaVaoThamSoTuDong(p, range);
219 }
220
221 try
222 {
223 if (p == null)
224 range.Font.ColorIndex = 3;
225 else if (p != null)
226 range.AddComment(TestUtility.SysToCSPro(p.ParameterType.ToString()) + " " + setText);
227 if (p != null)
228 if (p.ParameterType.ToString().IndexOf("&") > 0)
229 {
230 if (p.IsOut)
231 range.Interior.ColorIndex = 8; //set color to a out parameter cell
232 else
233 range.Interior.ColorIndex = 6; //set color to a ref parameter cell
234 }
235 }
236 catch { }
237
238 string formulaStr = null;
239 string[] tempShort = null;
240 bool defaultEnumIsSet = false;
241
242 if (p != null)
243 {
244 if (p.ParameterType.IsEnum)
245 {
246 FieldInfo[] enumMembers = p.ParameterType.GetFields();
247 foreach (FieldInfo fs in enumMembers)
248 {
249 tempShort = fs.ToString().Trim().Split(' ');
250 if (tempShort[tempShort.Length - 1] != "value__")
251 {
252 formulaStr = formulaStr + tempShort[tempShort.Length - 1] + ",";
253 if (!defaultEnumIsSet)
254 {
255 defaultEnumIsSet = true;
256 range.Value2 = tempShort[tempShort.Length - 1];
257 }
258 }
259 }
260 defaultEnumIsSet = false;
261 formulaStr = formulaStr + "xxxx";
262 formulaStr = formulaStr.Replace(" ", ".");
263 formulaStr = formulaStr.Replace(",xxxx", "");
264
265 try
266 {
267 range.Validation.Delete();
268 range.Validation.Add(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, formulaStr, "");
269 }
270 catch { }
271 }
272 }
273 }
274
275 private void DuaVaoThamSoTuDong(ParameterInfo p, Excel.Range range)
276 {
277 Random thamso = new Random();
278
279 if (p.ParameterType.ToString().IndexOf("Boolean") > 0)
280 range.Value2 = "true";
281 if (p.ParameterType.ToString().IndexOf("Boolean") > 0 && p.ParameterType.ToString().IndexOf("&") > 0)
282 range.Value2 = "false";
283
284 if (CacKieuSo(TestUtility.SysToCSPro(p.ParameterType.ToString())))
285 {
286 if (p.ParameterType.ToString().IndexOf("Double") > 0 || p.ParameterType.ToString().IndexOf("Decimal") > 0)
287 range.Value2 = (double)thamso.Next() / 1000000;
288 else
289 range.Value2 = (int)thamso.Next() / 1000000;
290 }
291 }
292
293 private bool CacKieuSo(string typeStr)
294 {
295 if (typeStr.StartsWith("int") ||
296 typeStr.StartsWith("double") ||
297 typeStr.StartsWith("long") ||
298 typeStr.StartsWith("short") ||
299 typeStr.StartsWith("uint") ||
300 typeStr.StartsWith("float") ||
301 typeStr.StartsWith("decimal") ||
302 typeStr.StartsWith("ulong") ||
303 typeStr.StartsWith("ushort"))
304 return true;
305
306 return false;
307 }
308
309 //Start coding XML documentation
310 private void ThaoTacDulieuXML()
311 {
312 XmlDocument xmldoc = MoFileXML();
313
314 //add code to read XML data into Excel data store
315
316 for (int RowC = 2; RowC < Tongsodong; RowC++)
317 {
318 //Get the Column with data;
319 int ColC = 0;
320 Excel.Range colRange = xSheet.get_Range(TestUtility.ConvCHAR(1) + RowC, TestUtility.ConvCHAR(1) + RowC);
321 while (colRange.Value2 != null || colRange.Comment != null)
322 {
323 ColC++;
324 colRange = xSheet.get_Range(TestUtility.ConvCHAR(ColC) + RowC, TestUtility.ConvCHAR(ColC) + RowC);
325 }
326 if (ColC > 3)
327 {
328 //parameter starts from column 3
329 for (int ColCou = 3; ColCou < ColC; ColCou++)
330 {
331 DocDuLieuXMLTrongNguon(xmldoc, RowC, ColCou);
332 }
333 }
334 }
335
336 try
337 {
338 xBook.Save();
339 }
340 catch (Exception err)
341 {
342 MessageBox.Show(err.Message);
343 }
344 }
345
346 private XmlDocument MoFileXML()
347 {
348 string[] TenDuongDanThuMuc = AssemblyNameToTest.Split('\\');
349 string ThuMucGocxml = AssemblyNameToTest.Replace(TenDuongDanThuMuc[TenDuongDanThuMuc.Length - 1], "");
350 DirectoryInfo ThuMucxml = null;
351 try
352 {
353 ThuMucxml = new DirectoryInfo(ThuMucGocxml);
354 }
355 catch (Exception e)
356 {
357 MessageBox.Show(e.Message + "\n\n Nguyên nhân có thể: Tập tin XML không phải trong cùng thư mục với việc kiểm thử, hoặc thuộc tính không được thiết lập để xây dựng một đầu ra XML được đặt tên", "Không thể tìm thấy tập tin XML");
358 return null;
359 }
360 FileInfo[] TatCaFile = ThuMucxml.GetFiles();
361 FileInfo xmlFile = null;
362 foreach (FileInfo xmlF in TatCaFile)
363 {
364 if (xmlF.Extension == ".xml")
365 {
366 xmlFile = xmlF;
367 break;
368 }
369 }
370
371 if (xmlFile != null)
372 {
373 XmlReader Docfilexml = new XmlTextReader(File.OpenRead(xmlFile.FullName));
374 XmlDocument Tailieuxml = new XmlDocument();
375 Tailieuxml.Load(Docfilexml);
376 Docfilexml.Close();
377
378 return Tailieuxml;
379 }
380
381 return null;
382 }
383
384 private void DocDuLieuXMLTrongNguon(XmlDocument xmlDoc, int RowC, int ColC)
385 {
386 Excel.Range xmlRange = xSheet.get_Range(TestUtility.ConvCHAR(ColC) + RowC, TestUtility.ConvCHAR(ColC) + RowC);//LocateRangeForXML(RowC, ColC);
387
388 XmlNodeList memNames = xmlDoc.GetElementsByTagName("member");
389
390 for (int memCount = 0; memCount < memNames.Count; memCount++)
391 {
392 XmlAttributeCollection memAtt = memNames[memCount].Attributes;
393
394 string classMem = (string)xSheet.get_Range(TestUtility.ConvCHAR(1) + RowC, TestUtility.ConvCHAR(1) + RowC).Value2;//LocateRangeForXML(RowC, 1).Value2;
395 string methodMem = (string)xSheet.get_Range(TestUtility.ConvCHAR(2) + RowC, TestUtility.ConvCHAR(2) + RowC).Value2;//LocateRangeForXML(RowC, 2).Value2;
396
397 if (memAtt[0].Value.IndexOf(classMem + "." + methodMem) > 0 || memAtt[0].Value.IndexOf(classMem + ".#ctor(") > 0)//("LowLevelObj.SimpleMath") > 0)
398 {
399 XmlNodeList paramNodes = memNames[memCount].ChildNodes;
400
401 for (int paramCount = 0; paramCount < paramNodes.Count; paramCount++)
402 {
403 if (paramNodes[paramCount].Name == "param")// || paramNodes[2].Name == "returns")
404 {
405 XmlAttributeCollection paramAtt = paramNodes[paramCount].Attributes;
406
407 string[] commentStr = null;
408 try
409 {
410 commentStr = xmlRange.Comment.Shape.AlternativeText.Split(' ');
411 }
412 catch { }
413 if (commentStr != null)
414 {
415 if (paramAtt[0].Value == commentStr[commentStr.Length - 1])// "x")
416 {
417
418 DuaDuLieuXMLLenExcel(paramNodes[paramCount].InnerXml, xmlRange);
419 break;
420 }
421 }
422 }
423
424 if (paramNodes[paramCount].Name == "returns")
425 {
426 if (xmlRange.Comment.Shape.AlternativeText.IndexOf("Expect to return a") >= 0)
427 {
428
429 DuaDuLieuXMLLenExcel(paramNodes[paramCount].InnerXml, xmlRange);
430 break;
431 }
432 }
433 }
434 }
435 }
436 }
437
438 private void DuaDuLieuXMLLenExcel(string TuVanBanXML, Excel.Range PhamViXML)
439 {
440 string DenCell = TuVanBanXML;//[paramCount].InnerXml;
441 int DuLieuDauTien = DenCell.IndexOf("e.g.,");
442 //int dataLen = GotoCell.Length - startData;
443 try
444 {
445 DenCell = DenCell.Substring(DuLieuDauTien);
446 }
447 catch { }
448 DenCell = DenCell.Replace("e.g.,", "").Trim();
449 PhamViXML.Value2 = DenCell;
450 }
451
452 //Start coding chapter 7
453 private void btnExit_Click(object sender, System.EventArgs e)
454 {
455 Application.Exit();
456 }
457 private void DongExcelSheet()
458 {
459 xBook.Close(false, Missing.Value, false);
460 xApp.Quit();
461 xSheet = null;
462 xBook = null;
463 xApp = null;
464 }
465
466 Excel.Range range = null;
467 Type typ = null;
468 Type[] types = null;
469 CodeMemberMethod cm = null;
470 CodeDomProvider codeProvider = null;
471 ICodeGenerator cg = null;
472 string nameSpace = null;
473 CodeCompileUnit TestUnit;
474 CodeNamespace cnamespace;
475 string clsName;
476 CodeTypeDeclaration co;
477 CodePropertyReferenceExpression pState = null;
478 CodeExpression[] pCode = null;
479 CodeFieldReferenceExpression cLeft = null;
480 CodeFieldReferenceExpression cRight = null;
481
482 private void TaoMaKiemThu(Assembly DUT, TextWriter t)
483 {
484 BatDauCodeDom(DUT);
485 ThemNamespaces(DUT);
486 PhuongThucLopDauTien();
487 TaoMaSheet(cm);
488 ThemMaExcelDauTien(cm);
489 MaCuaCacPhuongThuc(cm);
490
491 //Thông tin bắt đầu từ dòng 2 của Excel sheet
492 int i = 2;
493
494 range = xSheet.get_Range(TestUtility.ConvCHAR(1) + i, TestUtility.ConvCHAR(1) + i);
495 string previousType = range.Value2.ToString();
496 KhoiTaoCacKieuKiemThu(i, ref previousType);
497
498 int totalRows = DemCacDongTrongSheet(xSheet);
499
500 MethodInfo mi = null;
501 ConstructorInfo ci = null; //khởi tạo
502 Type[] AmbiguousOverLoad = null;
503 string wholeCellText = null;
504 string[] typeText = null;
505 string strPar = null;
506 string[] arrayPar = null;
507 Excel.Range rng;
508 Excel.Range rngCstr;
509
510 for (i = 2; i < totalRows; i++)//while (range.Value2.ToString() != "")
511 {
512 int j = 3;
513
514 CacKieuMoi(ref i, ref j, ref previousType);
515
516 rng = xSheet.get_Range(TestUtility.ConvCHAR(j) + i, TestUtility.ConvCHAR(j) + i);
517 rngCstr = xSheet.get_Range(TestUtility.ConvCHAR(1) + i, TestUtility.ConvCHAR(1) + i);
518
519 if (range.Value2.ToString() == rngCstr.Value2.ToString())//kiểm tra xem nó được khởi tạo
520 {
521 ThemKhoiMaKiemThu(ref i, ref j, ref rng, ref wholeCellText, ref typeText, ref strPar, ref arrayPar, ref AmbiguousOverLoad, ref ci);
522 }
523 else
524 {
525 ThemMaPhuongThucKiemThu(ref i, ref j, ref mi, ref rng, ref wholeCellText, ref typeText, ref strPar, ref arrayPar, ref AmbiguousOverLoad);
526
527 ParameterInfo[] ps = mi.GetParameters();
528 string parStr = "";
529
530 ThuThapCacThamSochoKiemThu(ref i, ref j, ref rng, ref ps, ref parStr);
531
532 pState = new CodePropertyReferenceExpression(null, "obj" + typ.Name);
533 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, parStr) };
534 CodeStatement[] trySt = null;
535 CodeExpression[] passPar = new CodeExpression[] { new CodeFieldReferenceExpression(null, "xResult, shtRow, mName") };
536
537 AddInvokeTestMethodCallCode(ref i, ref parStr, ref mi, ref trySt, ref passPar);
538
539 //add log result code
540 int colPosition = 0;
541 LogParmResultAndReturnValue(ref i, colPosition, ps, ref mi);
542 }
543 range = xSheet.get_Range(TestUtility.ConvCHAR(1) + i, TestUtility.ConvCHAR(1) + i);
544 }
545 AddOtherCodesPartII(cm, clsName);
546
547 if (objReturnStub == null)//Thêm cho việc kiểm thử COM
548 objReturnStub = new CodeSnippetExpression("null"); //thêm cho việc kiểm thử COM
549 cm.Statements.Add(new CodeMethodReturnStatement(objReturnStub));
550 objReturnStub = null;
551 AddUpClassesMethods();
552 cg.GenerateCodeFromNamespace(cnamespace, t, null);
553 DocFileCSPROJ(clsName, DUTAsm);
554 }
555 private void BatDauCodeDom(Assembly DUT)
556 {
557 TestUnit = new CodeCompileUnit();
558
559 types = DUT.GetTypes();
560 codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
561 foreach (Type ty in types)
562 {
563 nameSpace = ty.Namespace + "Test";
564 }
565 cnamespace = new CodeNamespace(nameSpace);
566
567 clsName = "Test" + DUTAsm.FullName.Substring(0, DUTAsm.FullName.IndexOf(", "));
568
569 cg = codeProvider.CreateGenerator();
570 }
571
572 private void ThemNamespaces(Assembly DUT)
573 {
574 TestUnit.Namespaces.Add(cnamespace);
575 cnamespace.Imports.Add(new CodeNamespaceImport("System"));
576 cnamespace.Imports.Add(new CodeNamespaceImport("System.IO"));
577 cnamespace.Imports.Add(new CodeNamespaceImport("Excel=Microsoft.Office.Interop.Excel"));
578 cnamespace.Imports.Add(new CodeNamespaceImport("System.Reflection"));
579 AssemblyName[] asms = null;
580 asms = DUT.GetReferencedAssemblies();
581 foreach (AssemblyName asm in asms)
582 {
583 if (asm.Name.ToString() != "mscorlib")
584 {
585 if (asm.Name.IndexOf(".") > 0 && asm.Name != "")
586 cnamespace.Imports.Add(new CodeNamespaceImport(asm.Name));
587 }
588 }
589 }
590
591 private void PhuongThucLopDauTien()
592 {
593 //add class name
594 co = new CodeTypeDeclaration(clsName);
595 cnamespace.Types.Add(co);
596 co.Attributes = (System.CodeDom.MemberAttributes)TypeAttributes.Public;
597
598 //add main mehtod
599 cm = new CodeMemberMethod();
600 cm.Name = "StartTest";//"Main";
601 cm.ReturnType = new CodeTypeReference(typeof(object));//added for integration
602 cm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
603 }
604 private void TaoMaSheet(CodeMemberMethod cm)
605 {
606 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Application), "xApp = new Excel.Application()"));
607 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Workbook), "xBook = xApp.Workbooks.Open(fileName, 0, false, 1, \"\", \"\", true, 1, 0, true, 1, 0, 0, 0, 0)"));
608 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Worksheet), "xSheet = (Excel.Worksheet)xBook.ActiveSheet"));
609 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Workbook), "xBook2 = xApp.Workbooks.Add(1)"));
610 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Worksheet), "xResult = (Excel.Worksheet)xBook2.ActiveSheet"));
611 }
612
613 private void ThemMaExcelDauTien(CodeMemberMethod cm)
614 {
615 CodePropertyReferenceExpression pState = null;
616 CodeExpression[] pCode = null;
617
618 pState =
619 new CodePropertyReferenceExpression(null, "xResult");
620 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 1, \"PHƯƠNG THỨC KIỂM THỬ\"") };
621 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
622
623 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 2, \"KẾT QUẢ\"") };
624 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
625
626 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 3, \"NGUYÊN NHÂN LỖI\"") };
627 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
628
629 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 4, \"KẾT QUẢ TRẢ VỀ\"") };
630 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
631
632 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 5, \"KẾT QUẢ MONG ĐỢI\"") };
633 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
634
635 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 6, \"CÁC THAM SỐ VÀ GIÁ TRỊ\"") };
636 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
637 }
638 private void MaCuaCacPhuongThuc(CodeMemberMethod cm)
639 {
640 CodePropertyReferenceExpression pState = null;
641 CodeExpression[] pCode = null;
642 CodeFieldReferenceExpression cLeft = null;
643 CodeFieldReferenceExpression cRight = null;
644
645 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "xApp.Visible") };
646 cLeft = new CodeFieldReferenceExpression(null, "xApp.Visible");
647 cRight = new CodeFieldReferenceExpression(null, " true");//sysbooltrue.ToString().ToLower());
648 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
649
650 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Range), "range"));
651 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Range), "rangeCurr"));
652 cLeft = new CodeFieldReferenceExpression(null, "range");
653 cRight = new CodeFieldReferenceExpression(null, "xResult.get_Range(\"A1\", \"H1\")");
654 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
655
656 cLeft = new CodeFieldReferenceExpression(null, "range.Interior.ColorIndex");
657 cRight = new CodeFieldReferenceExpression(null, "8");
658 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
659
660 cLeft = new CodeFieldReferenceExpression(null, "range.Font.Bold");
661 cRight = new CodeFieldReferenceExpression(null, " true");//sysbooltrue.ToString().ToLower());
662 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
663
664
665 pState = new CodePropertyReferenceExpression(null, "range");
666 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Columns.AutoFit"));
667
668 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(int), "shtRow = 0"));
669 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(string), "mName = null"));
670 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(int), "tempArrayIndex = 0"));
671 }
672
673 //initiate an object for the StartTest method to return an object
674 //in order to use a bottom up approach for integration testing.
675 CodeSnippetExpression objReturnStub;//added for integration
676 private void KhoiTaoCacKieuKiemThu(int i, ref string KieuTruoc)
677 {
678 foreach (Type ty in types)
679 {
680 if (ty.Name.ToString() == KieuTruoc)
681 {
682 typ = ty;
683 }
684 }
685 string nameSPLen = typ.Namespace;
686 if (nameSPLen != null || typ.Namespace != null)
687 cnamespace.Imports.Add(new CodeNamespaceImport(typ.Namespace));
688 if (typ.IsClass)
689 {
690 cm.Statements.Add(new CodeParameterDeclarationExpression(typ.Name, "obj" + typ.Name + " = null"));//modified for constructor
691 objReturnStub = new CodeSnippetExpression("obj" + typ.Name);//added for integration
692 }
693 else if (typ.IsInterface)
694 {
695 cm.Statements.Add(new CodeParameterDeclarationExpression(typ.Name, "obj" + typ.Name + " = null"));
696 foreach (Type ty in types)
697 {
698 if (ty.IsClass)
699 {
700 cm.Statements.Add(new CodeParameterDeclarationExpression(ty.Name, "obj_" + i + ty.Name + " = new " + ty.Name + "()"));
701 cLeft = new CodeFieldReferenceExpression(null, "obj" + typ.Name);
702 cRight = new CodeFieldReferenceExpression(null, "(" + typ.Name + ")obj_" + i + ty.Name);
703 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
704 }
705 }
706 }
707
708 }
709 private int DemCacDongTrongSheet(Excel.Worksheet xSheet)
710 {
711 Excel.Range range = null;
712 int i = 1;
713 range = xSheet.get_Range("A" + i, "A" + i);
714 while (range.Value2 != null)
715 {
716 i++;
717 range = xSheet.get_Range("A" + i, "A" + i);
718 }
719 return i;
720 }
721
722 private void CacKieuMoi(ref int i, ref int j, ref string KieuTruoc)
723 {
724 range = xSheet.get_Range(TestUtility.ConvCHAR(1) + i, TestUtility.ConvCHAR(1) + i);
725 string currentType = range.Value2.ToString();
726 if (KieuTruoc != currentType)
727 {
728 foreach (Type ty in types)
729 {
730 if (ty.Name.ToString() == currentType)
731 {
732 typ = ty;
733 }
734 }
735 KieuTruoc = currentType;
736 //Sửa đổi để thêm khởi tạo
737 cm.Statements.Add(new CodeParameterDeclarationExpression(typ.Name, "obj" + typ.Name + " = null"));
738 }
739 range = xSheet.get_Range(TestUtility.ConvCHAR(2) + i, TestUtility.ConvCHAR(2) + i);
740
741 cLeft = new CodeFieldReferenceExpression(null, "shtRow");
742 cRight = new CodeFieldReferenceExpression(null, "" + i);
743 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
744
745 }
746 private void ThemKhoiMaKiemThu(ref int i, ref int j, ref Excel.Range rng, ref string wholeCellText, ref string[] typeText, ref string strPar, ref string[] arrayPar, ref Type[] AmbiguousOverLoad, ref ConstructorInfo ci)
747 {
748 cLeft = new CodeFieldReferenceExpression(null, "mName");
749 cRight = new CodeFieldReferenceExpression(null, "\"" + typ.Name + "\"");
750 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
751 strPar = ""; //Start a new variable
752 while (rng.Value2 != null)
753 {
754 wholeCellText = rng.Comment.Text("", 1, 0);
755 typeText = wholeCellText.Split(' ');
756 strPar = strPar + typeText[0] + ",";
757 j++;
758 rng = xSheet.get_Range(TestUtility.ConvCHAR(j) + i, TestUtility.ConvCHAR(j) + i);
759 }
760 if (strPar != null)
761 {
762 strPar = strPar.Replace("Expect,", "");
763 arrayPar = strPar.Split(',');
764 AmbiguousOverLoad = new Type[arrayPar.Length - 1];
765 for (int parPos = 0; parPos < arrayPar.Length - 1; parPos++)//enumerate parameters
766 {
767 TestUtility.ConvertStringToType(arrayPar[parPos], ref AmbiguousOverLoad[parPos]);
768 }
769 ci = typ.GetConstructor(AmbiguousOverLoad);
770 }
771 else//if (strPar == "")
772 ci = typ.GetConstructor(new Type[0]);
773
774 if (ci != null)
775 {
776 ParameterInfo[] pars = ci.GetParameters();
777 foreach (ParameterInfo p in pars)
778 {
779 ThemMaChoCacThamSo(p, cm, i);
780 }
781
782 ThemCacKhoiMa(typ, ci, cm, i);
783 }
784 pState = new CodePropertyReferenceExpression(null, "xResult");
785 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 4, \"Test Constructor\"") };
786 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
787
788 }
789 private void ThemMaChoCacThamSo(ParameterInfo p, CodeMemberMethod cm, int i)
790 {
791 Excel.Range rng = xSheet.get_Range(TestUtility.ConvCHAR(p.Position + 3) + i, TestUtility.ConvCHAR(p.Position + 3) + i); //added for pass parameter by object
792
793 CodeFieldReferenceExpression cLeft = new CodeFieldReferenceExpression(null, "range");
794 CodeFieldReferenceExpression cRight = new CodeFieldReferenceExpression(null, "xSheet.get_Range(\"" + TestUtility.ConvCHAR(p.Position + 3) + i + "\", \"" + TestUtility.ConvCHAR(p.Position + 3) + i + "\")");
795 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
796 //int errorCode = int.Parse(range.Value2.ToString());
797 cLeft = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString()) + " " + p.Name + "_" + i);
798 //cRight=new CodeFieldReferenceExpression(null, "new System.Text.StringBuilder()");
799 if (p.ParameterType.ToString().StartsWith("System.String") || p.ParameterType.ToString().StartsWith("System.Object"))
800 {
801 cRight = new CodeFieldReferenceExpression(null, "range.Value2.ToString()");
802 }
803 else if (p.ParameterType.ToString().IndexOf("[]") > 0)
804 {
805 //cRight=new CodeFieldReferenceExpression(null, "{" + TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]","")) + ".Parse(range.Value2.ToString())}"); //commented to read array
806 if (TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) == "string")
807 {
808 cRight = new CodeFieldReferenceExpression(null, "range.Value2.ToString().Split(',')");
809 }
810 else
811 {
812 cRight = new CodeFieldReferenceExpression(null, " null");
813 //cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
814
815 //cLeft=new CodeFieldReferenceExpression(null, "tempArray");
816 cRight = new CodeFieldReferenceExpression(null, "new " + TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + "[range.Value2.ToString().Split(',').Length]");
817 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
818 //foreach (string z in x.Split(',')){a[i]=int.Parse(z);i++;};
819 cLeft = new CodeFieldReferenceExpression(null, "foreach (string z in range.Value2.ToString().Split(',')){" + p.Name + "_" + i + "[tempArrayIndex]");
820 cRight = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + ".Parse(z); tempArrayIndex++;}");
821 //cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
822 }
823 }
824 else if (p.ParameterType.ToString().IndexOf("Text.StringBuilder") > 0)
825 {
826 cRight = new CodeFieldReferenceExpression(null, "new System.Text.StringBuilder()");
827 }
828 else if (rng.Value2.ToString() == "new")
829 {
830 cRight = new CodeFieldReferenceExpression(null, "new " + p.ParameterType.ToString() + "()");
831 }
832 else
833 {
834 cRight = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + ".Parse(range.Value2.ToString())");
835 }
836 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
837 if (p.ParameterType.ToString().IndexOf("[]") > 0)
838 {
839 cLeft = new CodeFieldReferenceExpression(null, "tempArrayIndex");
840 cRight = new CodeFieldReferenceExpression(null, "0");
841 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
842 }
843 }
844 private void ThemCacKhoiMa(Type typ, ConstructorInfo ci, CodeMemberMethod cm, int i)
845 {
846 string pCodeStr = "";
847
848 CodeStatement[] trySt;
849 CodeExpression[] passPar = new CodeExpression[] { new CodeFieldReferenceExpression(null, "xResult, shtRow, mName") };
850
851 ParameterInfo[] pis = ci.GetParameters();
852 foreach (ParameterInfo pi in pis)
853 {
854 pCodeStr += pi.Name + "_" + i + ", ";
855 }
856 if (pCodeStr.IndexOf(",") > 0)
857 {
858 pCodeStr += "xxxx";
859 pCodeStr = pCodeStr.Replace(", xxxx", "");
860 }
861 CodeExpression[] pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, pCodeStr) };
862
863 trySt = new CodeStatement[] {new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "obj" + typ.Name + " = new " + typ.Name, pCode)),
864 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestPass", passPar)),
865 };
866
867 //TestFail(xResult, shtRow, mName, err.Message);
868 passPar = new CodeExpression[] { new CodeFieldReferenceExpression(null, "xResult, shtRow, mName, err.Message") };
869 CodeCatchClause catchCl = new CodeCatchClause("err", new CodeTypeReference(typeof(Exception)), new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestFail", passPar)));
870
871 CodeCatchClause[] catchSt = new CodeCatchClause[]{ catchCl
872 };
873 cm.Statements.Add(new CodeTryCatchFinallyStatement(trySt, catchSt));
874 }
875
876 private void ThemMaPhuongThucKiemThu(ref int i, ref int j, ref MethodInfo mi, ref Excel.Range rng, ref string wholeCellText, ref string[] typeText, ref string strPar, ref string[] arrayPar, ref Type[] AmbiguousOverLoad)
877 {
878 try
879 {
880 mi = typ.GetMethod(range.Value2.ToString());
881 }
882 catch (Exception err)
883 {
884 Console.WriteLine(err.Message);
885 strPar = ""; //Start a new variable
886 while (rng.Value2 != null)
887 {
888 //wholeCellText = rng.Value2.ToString();
889 wholeCellText = rng.Comment.Text("", 1, 0);
890 typeText = wholeCellText.Split(' ');
891 strPar = strPar + typeText[0] + ",";
892 j++;
893 rng = xSheet.get_Range(TestUtility.ConvCHAR(j) + i, TestUtility.ConvCHAR(j) + i);
894 }
895
896 if (strPar == "Expect,")
897 strPar = null;
898
899 if (strPar != null)
900 {
901 strPar = strPar.Replace("Expect,", "");
902 arrayPar = strPar.Split(',');
903 AmbiguousOverLoad = new Type[arrayPar.Length - 1];
904 for (int parPos = 0; parPos < arrayPar.Length - 1; parPos++)//enumerate parameters
905 {
906 TestUtility.ConvertStringToType(arrayPar[parPos], ref AmbiguousOverLoad[parPos]);
907 }
908 mi = typ.GetMethod(range.Value2.ToString(), AmbiguousOverLoad);
909 }
910 else//if (strPar == "")
911 mi = typ.GetMethod(range.Value2.ToString(), new Type[0]);
912 }
913 cLeft = new CodeFieldReferenceExpression(null, "mName");
914 cRight = new CodeFieldReferenceExpression(null, "\"" + mi.Name + "\"");
915 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
916 }
917
918 private void ThuThapCacThamSochoKiemThu(ref int i, ref int j, ref Excel.Range rng, ref ParameterInfo[] ps, ref string parStr)
919 {
920 foreach (ParameterInfo p in ps)
921 {
922 rng = xSheet.get_Range(TestUtility.ConvCHAR(p.Position + 3) + i, TestUtility.ConvCHAR(p.Position + 3) + i); //added for pass parameter by object
923 cLeft = new CodeFieldReferenceExpression(null, "range");
924 cRight = new CodeFieldReferenceExpression(null, "xSheet.get_Range(\"" + TestUtility.ConvCHAR(p.Position + 3) + i + "\", \"" + TestUtility.ConvCHAR(p.Position + 3) + i + "\")");
925 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
926 cLeft = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString()) + " " + p.Name + "_" + i);
927
928 if (rng.Value2.ToString().ToUpper().StartsWith("WINREG"))
929 {
930 NeedWinReg = true;
931 if (p.ParameterType == typeof(string) || p.ParameterType.ToString() == "System.String&")
932 cRight = new CodeFieldReferenceExpression(null, "(string)GetWinRegValue(range.Value2.ToString())");
933 else if (p.ParameterType == typeof(bool) || p.ParameterType.ToString() == "System.Boolean&")
934 cRight = new CodeFieldReferenceExpression(null, "(bool)GetWinRegValue(range.Value2.ToString())");
935 else if (p.ParameterType == typeof(object) || p.ParameterType.ToString() == "System.Object&")
936 cRight = new CodeFieldReferenceExpression(null, "GetWinRegValue(range.Value2.ToString())");
937 else
938 cRight = new CodeFieldReferenceExpression(null, "(int)GetWinRegValue(range.Value2.ToString())");
939 }
940 else if (p.ParameterType.ToString().StartsWith("System.String") || p.ParameterType.ToString().StartsWith("System.Object"))
941 {
942 cRight = new CodeFieldReferenceExpression(null, "range.Value2.ToString()");
943 }
944 else if (p.ParameterType.IsEnum)
945 {
946 cRight = new CodeFieldReferenceExpression(null, p.ParameterType.ToString() + "." + rng.Value2);
947 }
948 else if (p.ParameterType.ToString().IndexOf("[]") > 0)
949 {
950 if (TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) == "string")
951 {
952 cRight = new CodeFieldReferenceExpression(null, "range.Value2.ToString().Split(',')");
953 }
954 else
955 {
956 cRight = new CodeFieldReferenceExpression(null, " null");
957 cRight = new CodeFieldReferenceExpression(null, "new " + TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + "[range.Value2.ToString().Split(',').Length]");
958 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
959 cLeft = new CodeFieldReferenceExpression(null, "foreach (string z in range.Value2.ToString().Split(',')){" + p.Name + "_" + i + "[tempArrayIndex]");
960 cRight = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + ".Parse(z); tempArrayIndex++;}");
961 }
962 }
963 else if (p.ParameterType.ToString().IndexOf("Text.StringBuilder") > 0)
964 {
965 cRight = new CodeFieldReferenceExpression(null, "new System.Text.StringBuilder()");
966 }
967 else if (rng.Value2.ToString() == "new")
968 {
969 TaoThongSoDoiTuong(ref i, p);
970 }
971 else
972 {
973 cRight = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + ".Parse(range.Value2.ToString())");
974 }
975
976 AddStubDecision(rng);
977 if (p.ParameterType.ToString().IndexOf("[]") > 0)
978 {
979 cLeft = new CodeFieldReferenceExpression(null, "tempArrayIndex");
980 cRight = new CodeFieldReferenceExpression(null, "0");
981 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
982 }
983
984 if (p.ParameterType.ToString().IndexOf("Text.StringBuilder") > 0)
985 {
986 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "range.Value2.ToString()") };
987 cm.Statements.Add(new CodeMethodInvokeExpression(null, p.Name.ToString() + "_" + i + ".Append", pCode));
988 }
989
990 if (p.Position != 0)
991 {
992 if (p.ParameterType.ToString().IndexOf("&") > 0)
993 {
994 if (!p.IsOut)
995 parStr = parStr + ", ref " + p.Name + "_" + i;
996 else
997 parStr = parStr + ", out " + p.Name + "_" + i;
998 }
999 else
1000 parStr = parStr + ", " + p.Name + "_" + i;
1001 }
1002 else if (p.ParameterType.ToString().IndexOf("&") > 0)
1003 {
1004 if (!p.IsOut)
1005 parStr = parStr + "ref " + p.Name + "_" + i;
1006 else
1007 parStr = parStr + "out " + p.Name + "_" + i;
1008 }
1009 else
1010 parStr = parStr + p.Name + "_" + i;
1011 }
1012 }
1013 private void AddInvokeTestMethodCallCode(ref int i, ref string parStr, ref MethodInfo mi, ref CodeStatement[] trySt, ref CodeExpression[] passPar)
1014 {
1015 if (mi.ReturnType.ToString() == "System.Void")
1016 {
1017 string propertySETname = "xxx" + mi.Name.ToString();
1018 if (propertySETname.Trim().StartsWith("xxxset_"))
1019 {
1020 trySt = new CodeStatement[] {new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "obj" + typ.Name + "." + mi.Name.Replace("set_", "") + " = ", pCode)),
1021 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestPass", passPar)),
1022 };
1023 }
1024 else
1025 {
1026 trySt = new CodeStatement[] {new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "obj" + typ.Name + "." + mi.Name, pCode)),
1027 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestPass", passPar)),
1028 };
1029 }
1030 }
1031 else
1032 {
1033 string propertyname = "xxx" + mi.Name.ToString();
1034 if (propertyname.Trim().StartsWith("xxxget_"))
1035 {
1036 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "" + i + ", " + 4 + ", obj" + typ.Name + "." + mi.Name.Replace("get_", "")) };
1037 trySt = new CodeStatement[] {new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode)),
1038 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestPass", passPar)),
1039 };
1040 }
1041 else
1042 {
1043
1044 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "" + i + ", " + 4 + ", obj" + typ.Name + "." + mi.Name + "(" + parStr + ")"+".ToString()") };
1045 trySt = new CodeStatement[] {new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode)),
1046 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestPass", passPar)),
1047 };
1048 }
1049 }
1050 //TestFail(xResult, shtRow, mName, err.Message);
1051 passPar = new CodeExpression[] { new CodeFieldReferenceExpression(null, "xResult, shtRow, mName, err.Message") };
1052 CodeCatchClause catchCl = new CodeCatchClause("err", new CodeTypeReference(typeof(Exception)), new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestFail", passPar)));
1053 CodeCatchClause[] catchSt = new CodeCatchClause[]{ catchCl
1054 };
1055 cm.Statements.Add(new CodeTryCatchFinallyStatement(trySt, catchSt));
1056 }
1057 private void LogParmResultAndReturnValue(ref int i, int colPosition, ParameterInfo[] ps, ref MethodInfo mi)
1058 {
1059 foreach (ParameterInfo p in ps)
1060 {
1061 colPosition = p.Position + 6;
1062 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow" + ", " + colPosition + ", \"" + p.Name + " = \" + " + p.Name + "_" + i) };
1063 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1064 }
1065 //added to transfer expected return to the result sheet
1066 if (mi.ReturnType.ToString() != "System.Void")
1067 {
1068 if (colPosition > 0)
1069 colPosition -= 6;
1070 else
1071 colPosition -= 1;
1072
1073 AddMethodCodes(cm, colPosition, i);
1074 }
1075 }
1076 private void AddMethodCodes(CodeMemberMethod cm, int colPosition, int i)
1077 {
1078 CodeExpression[] pCode = null;
1079 CodeFieldReferenceExpression cLeft = null;
1080 CodeFieldReferenceExpression cRight = null;
1081
1082 cLeft = new CodeFieldReferenceExpression(null, "range");
1083 cRight = new CodeFieldReferenceExpression(null, "xSheet.get_Range(\"" + TestUtility.ConvCHAR(colPosition + 4) + i + "\", \"" + TestUtility.ConvCHAR(colPosition + 4) + i + "\")");
1084 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1085
1086 //if (range.Value2 != null)
1087 // xResult.Cells.set_Item(shtRow, 5, range.Value2.ToString());
1088 // pCode = new CodeExpression[]{new CodeFieldReferenceExpression(null, "shtRow" + ", " + 5 + ", range.Value2.ToString()")};
1089 // cm.Statements.Add(new CodeMethodInvokeExpression(null, "if (range.Value2 != null) xResult.Cells.set_Item", pCode));
1090 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 5, range.Value2.ToString()") };
1091 CodeConditionStatement ifState = new CodeConditionStatement(new CodeSnippetExpression("range.Value2 != null"), new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode)));
1092 cm.Statements.Add(ifState);
1093
1094
1095
1096 cLeft = new CodeFieldReferenceExpression(null, "rangeCurr");
1097 cRight = new CodeFieldReferenceExpression(null, "xResult.get_Range(\"" + TestUtility.ConvCHAR(4) + i + "\", \"" + TestUtility.ConvCHAR(4) + i + "\")");
1098 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1099 //if (range.Value2.ToString() != range.Value2.ToString() && range.Value2 != null)
1100 // range.Interior.ColorIndex = 3;
1101 cLeft = new CodeFieldReferenceExpression(null, "if (rangeCurr.Value2 != null) if (range.Value2 != null && rangeCurr.Value2.ToString() != range.Value2.ToString()) rangeCurr.Interior.ColorIndex");
1102 cRight = new CodeFieldReferenceExpression(null, "3");
1103 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1104 cLeft = new CodeFieldReferenceExpression(null, "if (rangeCurr.Value2 != null) if (range.Value2 != null && rangeCurr.Value2.ToString() == range.Value2.ToString()) rangeCurr.Interior.ColorIndex");
1105 cRight = new CodeFieldReferenceExpression(null, "4");
1106 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1107
1108 }
1109 string XlsReportFilename = @"C:/Temp"; //textbox10text
1110 string tempTestProjDir = @"C:/Temp";//textbox8text
1111 private void AddOtherCodesPartII(CodeMemberMethod cm, string clsName)
1112 {
1113 CodeExpression[] pCode = null;
1114 CodeFieldReferenceExpression cLeft = null;
1115 CodeFieldReferenceExpression cRight = null;
1116
1117 cLeft = new CodeFieldReferenceExpression(null, "string datetime");
1118 cRight = new CodeFieldReferenceExpression(null, "DateTime.Now.Date.ToShortDateString() + DateTime.Now.Hour.ToString()+DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString()");
1119 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1120
1121 //datetime = datetime.Replace("/", "");
1122 cLeft = new CodeFieldReferenceExpression(null, "datetime");
1123 cRight = new CodeFieldReferenceExpression(null, "datetime.Replace(\"/\", \"\")");
1124 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1125
1126 //datetime = datetime.Replace(":", "");
1127 cLeft = new CodeFieldReferenceExpression(null, "datetime");
1128 cRight = new CodeFieldReferenceExpression(null, "datetime.Replace(\":\", \"\")");
1129 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1130 //string resultFile =System.IO.Path.Combine(Environment.CurrentDirectory, "xyz" + x.GetDate().Replace("/","") + x.GetTime().Replace(":","") + ".xls");
1131 cLeft = new CodeFieldReferenceExpression(null, "string resultFile");
1132 cRight = new CodeFieldReferenceExpression(null, "System.IO.Path.Combine(\"" + XlsReportFilename + "\", \"" + clsName + "\" + datetime + \".xls\")");
1133 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1134 // xBook2.SaveAs(resultFile, -4143, "", "", false, false, 0, "", 0, "", "", "");
1135 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "resultFile, -4143, \"\", \"\", false, false, 0, \"\", 0, \"\", \"\", \"\"") };
1136 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xBook2.SaveAs", pCode));
1137 // xBook.Close(null, null, null);
1138 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, " false, null, false") };
1139 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xBook.Close", pCode));
1140 // xBook2.Close(null, null, null);
1141 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xBook2.Close", pCode));
1142 // xApp.Quit();
1143 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xApp.Quit"));
1144 // xSheet = null;
1145 cLeft = new CodeFieldReferenceExpression(null, "xSheet");
1146 cRight = new CodeFieldReferenceExpression(null, " null");
1147 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1148 // xResult = null;
1149 cLeft = new CodeFieldReferenceExpression(null, "xResult");
1150 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1151 // xBook = null;
1152 cLeft = new CodeFieldReferenceExpression(null, "xBook");
1153 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1154 // xBook2 = null;
1155 cLeft = new CodeFieldReferenceExpression(null, "xBook2");
1156 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1157 // xApp = null;
1158 cLeft = new CodeFieldReferenceExpression(null, "xApp");
1159 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1160 }
1161
1162 private void AddUpClassesMethods()
1163 {
1164 co.Members.Add(cm);
1165
1166 CreateTestPassMethod(cm, "TestPass");
1167 CreateTestFailMethod(cm, "TestFail");
1168
1169 //add a file name field
1170 AddFilenameField(co);
1171 //add a constructor
1172 AddCstorCodes(co);
1173 //add a class to start the Main method
1174 CodeTypeDeclaration eco = new CodeTypeDeclaration("Start" + clsName);
1175 eco.TypeAttributes = TypeAttributes.Public;
1176 cnamespace.Types.Add(eco);
1177
1178 //add the Main method
1179
1180 AddMainMethod(eco, clsName);
1181 //eco.Members.Add(cm);
1182 }
1183 private void AddFilenameField(CodeTypeDeclaration co)
1184 {
1185 CodeMemberField cf = new CodeMemberField();
1186 cf.Name = "fileName = \"" + xlsDataStoreFilename + "\"";
1187 cf.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1188 cf.Type = new CodeTypeReference(typeof(string));
1189 co.Members.Add(cf);
1190 }
1191 private void AddCstorCodes(CodeTypeDeclaration co)
1192 {
1193 CodeFieldReferenceExpression cLeft = null;
1194 CodeFieldReferenceExpression cRight = null;
1195
1196
1197 CodeConstructor cc = new CodeConstructor();
1198 cc.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1199 co.Members.Add(cc);
1200
1201 //overload a constructor to load a data store file
1202 cc = new CodeConstructor();
1203 cc.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1204 cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "fileName"));
1205 cLeft = new CodeFieldReferenceExpression(null, "this.fileName");
1206 cRight = new CodeFieldReferenceExpression(null, "fileName");
1207 cc.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1208 co.Members.Add(cc);
1209 }
1210
1211 private void AddMainMethod(CodeTypeDeclaration eco, string clsName)
1212 {
1213 CodeEntryPointMethod entryCM = new CodeEntryPointMethod();// CodeMemberMethod();
1214 CodeFieldReferenceExpression cLeft = null;
1215 CodeFieldReferenceExpression cRight = null;
1216
1217 //entryCM.Name = "Main";
1218 //cm.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
1219 //entryCM.Parameters.Add(new CodeParameterDeclarationExpression("System.String[]", "agrs"));
1220 //cm.ReturnType = new CodeTypeReference(typeof(void));
1221
1222 //string rootDir = Environment.CurrentDirectory;
1223 cLeft = new CodeFieldReferenceExpression(null, "string rootDir");
1224 cRight = new CodeFieldReferenceExpression(null, "Environment.CurrentDirectory");
1225 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1226
1227 //tested //string [] fileArray = null;
1228 entryCM.Statements.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.String", 1), "fileArray = null"));
1229 //StreamReader sr = File.OpenText("fileArray.txt");
1230 cLeft = new CodeFieldReferenceExpression(null, "StreamReader sr");
1231 cRight = new CodeFieldReferenceExpression(null, "File.OpenText(System.IO.Path.Combine(\"" + tempTestProjDir + "/" + dirName + "/Bin/Debug" + "\", \"fileArray.txt\"))");
1232 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1233 //string input = null
1234 cLeft = new CodeFieldReferenceExpression(null, "string input");
1235 cRight = new CodeFieldReferenceExpression(null, " null");
1236 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1237 //string fStr = null;
1238 cLeft = new CodeFieldReferenceExpression(null, "string fStr");
1239 cRight = new CodeFieldReferenceExpression(null, " null");
1240 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1241
1242 //tested //while((input = sr.ReadLine()) != null) fStr = fStr + input + ",";
1243 cLeft = new CodeFieldReferenceExpression(null, "while ((input = sr.ReadLine()) != null) fStr");
1244 cRight = new CodeFieldReferenceExpression(null, "fStr + input + \",\"");
1245 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1246
1247 //Tested //sr.Close();
1248 entryCM.Statements.Add(new CodeMethodInvokeExpression(null, "sr.Close"));
1249 //fStr = fStr.Replace("/", "\\")
1250 cLeft = new CodeFieldReferenceExpression(null, "fStr");
1251 cRight = new CodeFieldReferenceExpression(null, "fStr.Replace(\"/\", \"\\\\\")");
1252 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1253
1254 //fileArray = fStr.Split(',');
1255 cLeft = new CodeFieldReferenceExpression(null, "fileArray");
1256 cRight = new CodeFieldReferenceExpression(null, "fStr.Split(\',\')");
1257 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1258
1259 //TestDotNetClassLib test = null;
1260 cLeft = new CodeFieldReferenceExpression(null, clsName + " test");
1261 cRight = new CodeFieldReferenceExpression(null, " null");
1262 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1263
1264 //for (int i = 0; i < fileArray.Length; i++)
1265 //{
1266 // test =new TestDotNetClassLib(fileArra[i]);
1267 // test.StartTest();
1268 //}
1269 cLeft = new CodeFieldReferenceExpression(null, "test");
1270 cRight = new CodeFieldReferenceExpression(null, "new " + clsName + "(System.IO.Path.Combine(rootDir, fileArray[i]))");
1271 CodeIterationStatement loop = new CodeIterationStatement(
1272 new CodeVariableDeclarationStatement("System.Int32", "i", new CodePrimitiveExpression(0)),
1273 new CodeBinaryOperatorExpression(
1274 new CodeFieldReferenceExpression(null, "i"),
1275 CodeBinaryOperatorType.LessThan,
1276 new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(null, "fileArray"), "Length - 1")
1277 ),
1278 new CodeAssignStatement(
1279 new CodeFieldReferenceExpression(null, "i"),
1280 new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(null, "i"),
1281 CodeBinaryOperatorType.Add,
1282 new CodePrimitiveExpression(1))
1283 ),
1284 new CodeStatement[]
1285 {
1286 new CodeAssignStatement(cLeft, cRight),
1287 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "test.StartTest"))
1288 }
1289 );
1290 entryCM.Statements.Add(loop);
1291 eco.Members.Add(entryCM);
1292
1293 }
1294
1295
1296 private void TaoThongSoDoiTuong(ref int i, ParameterInfo p)
1297 {
1298 if (chckManualStub.Checked)
1299 {
1300 Excel.Range stubRang = xSheet.get_Range(TestUtility.ConvCHAR(p.Position + 3) + i, TestUtility.ConvCHAR(p.Position + 3) + i);
1301 string[] stubType = stubRang.Comment.Text("", 1, 0).Split(' ');
1302 OBJStub(stubType[0], p.Name, i);
1303
1304 if (stubForm.txtDllToStub.Text.Length > 0)//added for integration
1305 {
1306 stubForm.MakeNewObjOfStub(stubForm.txtDllToStub.Text, i, p);
1307 }
1308 if (stubForm.m_RealObject != "" || stubForm.m_RealObject != null)
1309 {
1310 cm.Statements.Add(new CodeSnippetStatement(stubForm.m_RealObject));// CodeMethodInvokeExpression(pState, stubForm.txtConstructor.Text));
1311 stubForm.m_RealObject = "";
1312 stubForm.txtDllToStub.Text = "";
1313 }
1314
1315 if (stubForm.txtConstructor.Text.Trim() != "")
1316 {
1317 cm.Statements.Add(new CodeSnippetStatement(stubForm.txtConstructor.Text));// CodeMethodInvokeExpression(pState, stubForm.txtConstructor.Text));
1318 }
1319 if (stubForm.txtMethod.Text.Trim() != "")
1320 {
1321 cm.Statements.Add(new CodeSnippetStatement(stubForm.txtMethod.Text));// CodeMethodInvokeExpression(pState, stubForm.txtConstructor.Text));
1322 }
1323 }
1324 else
1325 {
1326 cRight = new CodeFieldReferenceExpression(null, "new " + p.ParameterType.ToString() + "()");
1327 }
1328
1329 }
1330
1331 private StubForm stubForm = new StubForm();
1332 private void OBJStub(string typeStr, string pName, int i)
1333 {
1334 ThucHienBangTay(typeStr);
1335
1336 string PathStr = null;
1337
1338 ChuyenDenFileKiemThu(out PathStr, typeStr);
1339
1340 try
1341 {
1342 Assembly asm = Assembly.LoadFrom(PathStr);
1343 Type type = asm.GetType(typeStr);// + "." + nameSPStr[nameSPStr.Length-1]);
1344 string list1Str = "";
1345 ConstructorInfo[] cis = type.GetConstructors();
1346 foreach (ConstructorInfo ci in cis)
1347 {
1348 list1Str += type.Name + "(";
1349 ParameterInfo[] ps = ci.GetParameters();
1350 foreach (ParameterInfo p in ps)
1351 {
1352 list1Str += p.ParameterType + " " + p.Name + ", ";
1353 }
1354 if (list1Str.IndexOf(",") > 0)
1355 {
1356 list1Str += "Xtra";
1357 list1Str = list1Str.Replace(", Xtra", ")");
1358 }
1359 if (list1Str.EndsWith("("))
1360 list1Str += ")";
1361 list1Str = type.Name.ToString() + " " + pName + "_" + i + " = new " + list1Str + ";";
1362 stubForm.lstConstructors.Items.Add(list1Str);
1363 list1Str = "";
1364 }
1365 MethodInfo[] mis = type.GetMethods();
1366 foreach (MethodInfo mi in mis)
1367 {
1368 list1Str += mi.Name + "(";
1369 ParameterInfo[] ps = mi.GetParameters();
1370 foreach (ParameterInfo p in ps)
1371 {
1372 list1Str += p.ParameterType + " " + p.Name + ", ";
1373 }
1374 if (list1Str.EndsWith(", "))
1375 {
1376 list1Str += "Xtra";
1377 list1Str = list1Str.Replace(", Xtra", ")");
1378 }
1379 if (list1Str.Trim().EndsWith("("))
1380 list1Str += ")";
1381 if (list1Str.Trim().StartsWith("set_"))
1382 {
1383 list1Str = list1Str.Replace("set_", "");
1384 list1Str = list1Str.Replace("(", " = ");
1385 list1Str = list1Str.Replace(")", "");
1386 }
1387 list1Str = pName + "_" + i + "." + list1Str + ";";
1388 stubForm.lstMethods.Items.Add(list1Str);
1389 list1Str = "";
1390 }
1391 stubForm.ShowDialog(this);
1392 }
1393 catch
1394 {
1395 stubForm.txtDllToStub.Text = PathStr;
1396
1397 if (!stubForm.TestClassFound)
1398 {
1399 stubForm.txtDllToStub.Text = "";
1400 MessageBox.Show("The assembly you selected is neither a test script object nor an already referenced instance. Pleae click OK to write C# code in the right text areas to make the Automated Software Test generate a precise test project.\n\nOr, if you are not sure, please restart the Automated Software Test. Make sure the Manual Stub checkbox is not checked before you create script.", "Wrong Stub Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
1401 stubForm.ShowDialog();
1402 }
1403 stubForm.TestClassFound = false;
1404 }
1405 }
1406
1407 private void ThucHienBangTay(string typeStr)
1408 {
1409 stubForm.Text = typeStr + " Stub";
1410 stubForm.txtConstructor.Text = "";
1411 stubForm.txtMethod.Text = "";
1412 stubForm.lstConstructors.Items.Clear();
1413 stubForm.lstMethods.Items.Clear();
1414 stubForm.ControlBox = false;
1415 }
1416 private void ChuyenDenFileKiemThu(out string PathStr, string typeStr)
1417 {
1418 PathStr = null;
1419 openFileDialog1.Title = "Locate the " + typeStr;
1420 openFileDialog1.Filter = "DLL Files(*.dll)|*.dll|All Files|*.*";
1421 if (openFileDialog1.ShowDialog() == DialogResult.OK)
1422 PathStr = openFileDialog1.FileName;
1423 }
1424 private void AddStubDecision(Excel.Range rng)
1425 {
1426 if (!(rng.Value2.ToString() == "new" && chckManualStub.Checked))
1427 {
1428 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1429 }
1430 }
1431
1432 private void CreateTestPassMethod(CodeMemberMethod cm, string MethodName)
1433 {
1434 cm = new CodeMemberMethod();
1435
1436 CodeExpression[] pCode = null;
1437 CodeFieldReferenceExpression cLeft = null;
1438 CodeFieldReferenceExpression cRight = null;
1439
1440 cm.Name = MethodName;//"TestPass";
1441 cm.ReturnType = new CodeTypeReference(typeof(void));
1442
1443 cm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1444 cm.Parameters.Add(new CodeParameterDeclarationExpression("Excel.Worksheet", "xResult"));
1445 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.Int32", "shtRow"));
1446 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "mName"));
1447
1448 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Range), "range"));
1449
1450 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 1, mName") };
1451 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1452
1453 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 2, \"PASS\"") };
1454 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1455
1456 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 3, \"NO ERROR\"") };
1457 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1458
1459 cLeft = new CodeFieldReferenceExpression(null, "range");
1460 cRight = new CodeFieldReferenceExpression(null, "xResult.get_Range(\"B\" + shtRow, \"B\" + shtRow)");
1461 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1462
1463 cLeft = new CodeFieldReferenceExpression(null, "range.Interior.ColorIndex");
1464 cRight = new CodeFieldReferenceExpression(null, "10");
1465 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1466 co.Members.Add(cm);
1467 }
1468 private void CreateTestFailMethod(CodeMemberMethod cm, string MethodName)
1469 {
1470 CodeExpression[] pCode = null;
1471 CodeFieldReferenceExpression cLeft = null;
1472 CodeFieldReferenceExpression cRight = null;
1473 cm = new CodeMemberMethod();
1474
1475 cm.Name = MethodName;//"TestFail";
1476 cm.ReturnType = new CodeTypeReference(typeof(void));
1477 cm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1478 cm.Parameters.Add(new CodeParameterDeclarationExpression("Excel.Worksheet", "xResult"));
1479 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.Int32", "shtRow"));
1480 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "mName"));
1481 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "errMsg"));
1482
1483 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Range), "range"));
1484
1485 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 1, mName") };
1486 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1487
1488 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 2, \"FAIL\"") };
1489 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1490
1491 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 3, errMsg") };
1492 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1493
1494 cLeft = new CodeFieldReferenceExpression(null, "range");
1495 cRight = new CodeFieldReferenceExpression(null, "xResult.get_Range(\"B\" + shtRow, \"B\" + shtRow)");
1496 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1497
1498 cLeft = new CodeFieldReferenceExpression(null, "range.Interior.ColorIndex");
1499 cRight = new CodeFieldReferenceExpression(null, "3");
1500 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1501 co.Members.Add(cm);
1502 }
1503
1504
1505 string dirName;
1506 string AssemblyNameUT;
1507 string testResultStr;
1508 string TestScriptCSFilename;
1509 string CSProjFilename;
1510 string AsmInfoFilename;
1511 string AppIconFilename;
1512 private void InitConstStrings()
1513 {
1514 try
1515 {
1516 dirName = openFileDialog1.FileName;
1517 dirName = dirName.Replace("\\", "/");
1518 string[] DirName = dirName.Split('/');
1519 dirName = DirName[DirName.Length - 1];
1520 dirName = dirName.Replace(".dll", "");
1521 }
1522 catch (Exception err)
1523 {
1524 MessageBox.Show("Select a DLL file\n" + err.Message, "XOA Software Tester");
1525 }
1526
1527 if (txtTargetProj.Text == "textBox8")
1528 {
1529 txtTargetProj.Text = "C:/Temp";//textbox8text=tempTestProjDir
1530 }
1531 tempTestProjDir = txtTargetProj.Text.Replace("\\", "/");
1532
1533 AssemblyNameUT = openFileDialog1.FileName; //textbox1
1534 xlsDataStoreFilename = tempTestProjDir + "/" + dirName + "/Bin/Debug/test" + dirName + "Data.xls"; //textbox2
1535 testResultStr = tempTestProjDir + "/" + dirName + "/TestResult.xls";//textbox3
1536 //TestScriptCSFilename = tempTestProjDir + "/" + dirName + "/test" + dirName + ".cs";//textbox4
1537 TestScriptCSFilename = tempTestProjDir + "/" + dirName + "/OATLS1TESTRep.cs";
1538 CSProjFilename = tempTestProjDir + "/" + dirName + "/Test" + dirName + ".csproj";//textbox5
1539 AsmInfoFilename = tempTestProjDir + "/" + dirName + "/AssemblyInfo.cs";//textbox6
1540 AppIconFilename = tempTestProjDir + "/" + dirName + "/App.ico";//textbox7
1541 if (txtCurrDir.Text == "Current Directory") //textbox10
1542 txtCurrDir.Text = txtTargetProj.Text;
1543 XlsReportFilename = txtCurrDir.Text.Replace("\\", "/");
1544 }
1545 private void TaoThuMucKiemThu()
1546 {
1547 DirectoryInfo dir = new DirectoryInfo(tempTestProjDir);
1548 try
1549 {
1550 if (dirName != null)
1551 dir.CreateSubdirectory(dirName);
1552 }
1553 catch (IOException err) { MessageBox.Show(err.Message); }
1554 dir = new DirectoryInfo(tempTestProjDir + "/" + dirName);
1555 try
1556 {
1557 dir.CreateSubdirectory("Bin");
1558 }
1559 catch (IOException err) { MessageBox.Show(err.Message); }
1560 dir = new DirectoryInfo(tempTestProjDir + "/" + dirName + "/Bin");
1561 try
1562 {
1563 dir.CreateSubdirectory("Debug");
1564 }
1565 catch (IOException err) { MessageBox.Show(err.Message); }
1566 }
1567
1568 private void TaoNguonThuThapDuLieu(string Content)
1569 {
1570 FileInfo f = new FileInfo(System.IO.Path.Combine(tempTestProjDir + "/" + dirName + "/Bin/Debug", "fileArray.txt"));
1571 StreamWriter sw = f.CreateText();
1572 sw.Write(Content);
1573 sw.Close();
1574 }
1575
1576 string rootDir = Environment.CurrentDirectory;
1577 private void ThaoTacCopyFile(string LoaiFile)
1578 {
1579 FileInfo f = null;
1580 if (LoaiFile == "ico")
1581 {
1582 f = new FileInfo(rootDir + "/testApp.ico");
1583 try
1584 {
1585 FileInfo AppF = f.CopyTo(AppIconFilename, true);
1586 }
1587 catch (Exception err) { MessageBox.Show(err.Message); }
1588 }
1589 else
1590 {
1591 f = new FileInfo(rootDir + "/TestAssemblyInfo.cs");
1592 try
1593 {
1594 FileInfo AppF = f.CopyTo(AsmInfoFilename, true);
1595 }
1596 catch (Exception err) { MessageBox.Show(err.Message); }
1597 }
1598 }
1599
1600 //add references tự động
1601 //public bool AddReference(EnvDTE.Project project, string reference)
1602 //{
1603 // VSProject proj = m_Project.Object as VSProject;
1604 // System.Diagnostics.Debug.Assert(proj != null); // This project is not a VSProject
1605 // if (proj == null)
1606 // return false;
1607 // try
1608 // {
1609 // proj.References.Add(reference);
1610 // }
1611 // catch (Exception ex)
1612 // {
1613 // string message = String.Format("Could not add {0}. \n Exception: {1}", reference, ex.Message);
1614 // System.Diagnostics.Trace.WriteLine(message);
1615 // return false;
1616 // }
1617
1618 // return true;
1619 //}
1620
1621
1622 private void Copytatca(string sourceDir, string targetDir)
1623 {
1624 foreach(var file in Directory.GetFiles(sourceDir))
1625
1626 File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
1627
1628 foreach(var directory in Directory.GetDirectories(sourceDir))
1629 Copytatca(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
1630 }
1631
1632 private void DocFileCSPROJ(string clsName, Assembly asm)
1633 {
1634 StreamReader sr = File.OpenText(rootDir + "/OATestProj.csproj");
1635 string input = null;
1636 string output = null;
1637 string refStr = "";
1638 string relPath = TestScriptCSFilename;//textBox4.Text;
1639 string[] RelPath = relPath.Split('/');
1640 relPath = RelPath[RelPath.Length - 1];
1641
1642
1643 //dirName = dirName.Replace("\\", "/");
1644 // string[] DirName = dirName.Split('/');
1645 // dirName = DirName[DirName.Length - 1];
1646 // dirName = dirName.Replace(".dll", "");
1647
1648
1649 //string filedll=tempTestProjDir+"/"+dirName+"/Bin/Debug"+dirName+".dll";
1650
1651
1652
1653 while (null != (input = sr.ReadLine()))
1654 {
1655 //input = sr.ReadLine();
1656 if (input.IndexOf("OATLStest") > 0)
1657 {
1658 input = input.Replace("OATLStest", clsName);
1659 }
1660 if (input.IndexOf("</References>") > 0)
1661 {
1662 AssemblyName[] asmRefs = asm.GetReferencedAssemblies();
1663
1664 foreach (AssemblyName aRef in asmRefs)
1665 {
1666 if (aRef.FullName.IndexOf("mscorlib") < 0)
1667 {
1668 refStr = refStr + "<Reference\n";
1669 refStr = refStr + "Name = \"" + aRef.Name + "\"\n";
1670 refStr = refStr + "AssemblyName = \"" + aRef.Name + "\"\n";
1671 refStr = refStr + "HintPath = \"" + aRef.CodeBase + "\"\n" + "/>\n";
1672 }
1673 }
1674 refStr = refStr + "<Reference\n" +
1675 "Name = \"" + asm.FullName.Substring(0, asm.FullName.IndexOf(", ")) + "\"\n" +
1676 "AssemblyName = \"" + asm.FullName.Substring(0, asm.FullName.IndexOf(", ")) + "\"\n" +
1677 "HintPath = \"" + asm.CodeBase + "\"\n" +
1678 "/>\n";
1679
1680
1681 refStr = refStr + "<Reference\n" +
1682 "Name = \"" + dirName + "\"\n" +
1683 "AssemblyName = \"" + dirName + "\"\n" +
1684 "HintPath = \"" + tempTestProjDir + "/" + dirName + "/Bin/Debug" + dirName + ".dll" + "\"\n" +
1685 "/>\n";
1686
1687 if (stubForm.m_CreateReference != "") //added for integration
1688 {
1689 refStr += stubForm.m_CreateReference;
1690 stubForm.m_CreateReference = "";
1691 }
1692
1693 refStr = refStr.Replace("file:///", "");
1694 refStr = refStr.Replace("/", "\\");
1695 input = refStr + input + "\n";
1696 }
1697
1698 if (input.IndexOf("RelPath = \"OATLS1TESTRep.cs\"") > 0)
1699 {
1700 input = input.Replace("OATLS1TESTRep.cs", relPath);
1701 }
1702 output = output + input + "\n";
1703 }
1704 FileInfo f = new FileInfo(CSProjFilename);
1705 StreamWriter write = f.CreateText();
1706 write.Write(output);
1707 write.Close();
1708 sr.Close();
1709 }
1710
1711 private void BatDauDOTNETIDE(string fileName, string args)
1712 {
1713 try
1714 {
1715 Process shell = new Process();
1716 shell.StartInfo.FileName = fileName;
1717 shell.StartInfo.Arguments = args;
1718 shell.Start();
1719 }
1720 catch (Exception er)
1721 { MessageBox.Show(er.Message); }
1722 }
1723
1724 private void TestForm_Load(object sender, EventArgs e)
1725 {
1726 try
1727 {
1728 string DevenvPath = Environment.ExpandEnvironmentVariables(
1729 @"%VSCOMNTOOLS%devenv.exe").Replace(@"Tools", "IDE").Replace("\"", "");
1730
1731 if (!File.Exists(DevenvPath)) //dùng cho visual studio 2008
1732 {
1733 DevenvPath = Environment.ExpandEnvironmentVariables(
1734 @"%VS90COMNTOOLS%devenv.exe").Replace(@"Tools", "IDE");
1735 }
1736
1737 txtDotNETLocation.Text = DevenvPath;
1738 }
1739 catch
1740 {
1741 }
1742
1743 btnStart.Focus();
1744
1745
1746 }
1747
1748 private void btnStart_Click(object sender, EventArgs e)
1749 {
1750 //mở file dll hoặc file exe.
1751 GetAssemblyName();
1752 //tạo các thư mục để chứa các file .cs, .csproj..trong ổ C
1753 InitConstStrings();
1754 //Tạo thư mục kiểm thử
1755 TaoThuMucKiemThu();
1756 //
1757 GetTypesOfAssemblyUnderTest();
1758 //khởi tạo phương thức kiểm thử
1759 Khoitaophuongthuckiemthu();
1760
1761 if (chckXMLDataDoc.Checked)
1762 {
1763 ThaoTacDulieuXML();
1764 btnCreateScript_Click(sender, e);
1765 }
1766
1767 //btnCreateScript.Focus();
1768 }
1769
1770 private void btnCreateScript_Click(object sender, EventArgs e)
1771 {
1772 btnStart.Focus();
1773 if (dirName == null || xApp == null)
1774 {
1775 MessageBox.Show("Click the Start button to collect test information first.");
1776 return;
1777 }
1778 //Create a TextWriter object to save the script
1779 TextWriter t = null;
1780
1781 t = new StreamWriter(new FileStream(TestScriptCSFilename, FileMode.Create));
1782 //start generating script
1783 try
1784 {
1785 TaoMaKiemThu(DUTAsm, t);
1786 }
1787 catch (Exception err)
1788 { MessageBox.Show(err.Message); }
1789 finally
1790 {
1791 t.Close();
1792 }
1793
1794 DongExcelSheet();
1795 ThaoTacCopyFile("ico");
1796 ThaoTacCopyFile("cs");
1797 TaoNguonThuThapDuLieu(xlsDataStoreFilename);
1798 txtDataStore.Text = xlsDataStoreFilename;
1799 BatDauDOTNETIDE(txtDotNETLocation.Text, CSProjFilename);
1800 coppyfile();
1801 //coppydll();
1802 string nguon = @"D:/thao" + "/" + dirName + "/" + dirName + "/Bin/Debug";
1803 string targetPath = tempTestProjDir + "/" + dirName + "/Bin/Debug";
1804 //tatcafilecopy(nguon, targetPath);
1805 Copytatca(nguon, targetPath);
1806 }
1807
1808
1809
1810 private void coppyfile()
1811 {
1812 string fileName = "Interop.Microsoft.Office.Interop.Excel.dll";
1813 string sourcePath = @"D:\thao\de tai\AutomatedTest\AutomatedTest\bin\Debug";
1814 string targetPath = tempTestProjDir + "/" + dirName + "/Bin/Debug";
1815
1816 string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
1817 string destFile = System.IO.Path.Combine(targetPath, fileName);
1818 File.Copy(sourceFile, destFile);
1819 }
1820
1821
1822
1823 //thao tac regedit
1824 bool NeedWinReg;
1825 private void MakeIfStatementForAccessRegKey(CodeMemberMethod cm, string strCondition, string strLeft, string strRight)
1826 {
1827 CodeFieldReferenceExpression cLeft = null;
1828 CodeFieldReferenceExpression cRight = null;
1829 cLeft = new CodeFieldReferenceExpression(null, strLeft);
1830 cRight = new CodeFieldReferenceExpression(null, strRight);
1831 CodeConditionStatement ifState = new CodeConditionStatement(new CodeSnippetExpression(strCondition), new CodeAssignStatement(cLeft, cRight));
1832 cm.Statements.Add(ifState);
1833 }
1834
1835 private void CreateAccessRegKeyMethod(CodeMemberMethod cm, string MethodName)
1836 {
1837 cm = new CodeMemberMethod();
1838
1839 cm.Name = MethodName;
1840 cm.ReturnType = new CodeTypeReference(typeof(void));
1841 cm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1842
1843 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "locHive"));
1844 cm.Parameters.Add(new CodeParameterDeclarationExpression("ref RegistryKey", "key"));
1845
1846
1847 CodeFieldReferenceExpression cLeft = null;
1848 CodeFieldReferenceExpression cRight = null;
1849
1850 cLeft = new CodeFieldReferenceExpression(null, "locHive");
1851 cRight = new CodeFieldReferenceExpression(null, "locHive.Trim()");
1852 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1853
1854 MakeIfStatementForAccessRegKey(cm, "locHive == \"HKEY_CURRENT_CONFIG\"", "key", "Registry.CurrentConfig");
1855 MakeIfStatementForAccessRegKey(cm, "locHive == \"HKEY_LOCAL_MACHINE\"", "key", "Registry.LocalMachine");
1856 MakeIfStatementForAccessRegKey(cm, "locHive == \"HKEY_CURRENT_USER\"", "key", "Registry.CurrentUser");
1857 MakeIfStatementForAccessRegKey(cm, "locHive == \"HKEY_CLASSES_ROOT\"", "key", "Registry.ClassesRoot");
1858 MakeIfStatementForAccessRegKey(cm, "locHive == \"HKEY_USERS\"", "key", "Registry.Users");
1859
1860 co.Members.Add(cm);
1861 }
1862
1863 private void CreateGetWinRegValueMethod(CodeMemberMethod cm, string MethodName)
1864 {
1865 cm = new CodeMemberMethod();
1866
1867 cm.Name = MethodName;
1868 cm.ReturnType = new CodeTypeReference(typeof(object));
1869 cm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1870
1871 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "WinRegKey"));
1872
1873 CodeFieldReferenceExpression cLeft = null;
1874 CodeFieldReferenceExpression cRight = null;
1875
1876 cLeft = new CodeFieldReferenceExpression(null, "WinRegKey");
1877 cRight = new CodeFieldReferenceExpression(null, "WinRegKey.ToUpper().Replace(\"WINREG:\", \"\")");
1878 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1879
1880 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Microsoft.Win32.RegistryKey), "key = null"));
1881
1882 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(object), "WinRegVal = \"\""));
1883
1884 cLeft = new CodeFieldReferenceExpression(null, "string[] HiveSubs");
1885 cRight = new CodeFieldReferenceExpression(null, "WinRegKey.Split('\\\\')");
1886 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1887
1888 cLeft = new CodeFieldReferenceExpression(null, "WinRegKey");
1889 cRight = new CodeFieldReferenceExpression(null, "WinRegKey.Replace(HiveSubs[0]+@\"\\\", \"\").Replace(@\"\\\"+HiveSubs[HiveSubs.Length-1], \"\")");
1890 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1891
1892
1893 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "HiveSubs[0], ref key") };
1894 cm.Statements.Add(new CodeMethodInvokeExpression(null, "AccessRegKey", pCode));
1895
1896 cLeft = new CodeFieldReferenceExpression(null, "key");
1897 cRight = new CodeFieldReferenceExpression(null, "key.OpenSubKey(WinRegKey)");
1898 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1899
1900
1901 cLeft = new CodeFieldReferenceExpression(null, "WinRegVal");
1902 cRight = new CodeFieldReferenceExpression(null, "key.GetValue(HiveSubs[HiveSubs.Length-1])");
1903 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1904
1905
1906 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, null) };
1907 cm.Statements.Add(new CodeMethodInvokeExpression(null, "key.Close", pCode));
1908
1909
1910 cm.Statements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("WinRegVal")));
1911 co.Members.Add(cm);
1912 }
1913
1914
1915
1916
1917
1918
1919 private void btnExit_Click_1(object sender, EventArgs e)
1920 {
1921 Application.Exit();
1922 }
1923
1924 private void btnAddDataStore_Click(object sender, EventArgs e)
1925 {
1926 if (dirName == null)
1927 {
1928 MessageBox.Show("Please click Start button, then Create Script button to generate a test script first.");
1929 return;
1930 }
1931 openFileDialog1.Title = "Add more data store";
1932 openFileDialog1.Filter = "Excel Files (*.xls)|*.xls";
1933 openFileDialog1.Multiselect = true;
1934 if (openFileDialog1.ShowDialog() == DialogResult.OK)
1935 {
1936 foreach (string fn in openFileDialog1.FileNames)
1937 {
1938 txtDataStore.Text += "\n" + fn;
1939 }
1940 }
1941 }
1942
1943 private void btnSaveDataStore_Click(object sender, EventArgs e)
1944 {
1945 if (txtDataStore.Text.Trim() == "")
1946 return;
1947 TaoNguonThuThapDuLieu(txtDataStore.Text);
1948 }
1949 }
1950 }
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.Reflection;
10 using System.Xml;
11 using System.Xml.XPath;
12 using System.IO;
13 using System.CodeDom;
14 using System.CodeDom.Compiler;
15 using System.Diagnostics;
16 using Excel = Microsoft.Office.Interop.Excel;
17
18 namespace AutomatedTest
19 {
20 public partial class TestForm : Form
21 {
22 public TestForm()
23 {
24 InitializeComponent();
25 }
26 private string AssemblyNameToTest;
27 private void GetAssemblyName()
28 {
29 openFileDialog1.Title = "DLL under test";
30 openFileDialog1.Filter = "DLL files (*.dll)|*.dll|Executable files (*.exe)|*.exe|All files (*.*)|*.*";
31
32
33 if (openFileDialog1.ShowDialog() == DialogResult.OK)
34 {
35 AssemblyNameToTest = openFileDialog1.FileName;
36 }
37 else
38 {
39 AssemblyNameToTest = "";
40 }
41 }
42 private void GetTypesOfAssemblyUnderTest()
43 {
44 if (AssemblyNameToTest.Length <= 0)
45 {
46 return;
47 }
48 TypeUnderTest typeDUT = new TypeUnderTest();
49 try
50 {
51 Assembly asm = Assembly.LoadFrom(AssemblyNameToTest);
52 Type[] tys = asm.GetTypes();
53 foreach (Type ty in tys)
54 {
55 typeDUT.chckListType.Items.Add(ty.Name);
56 }
57
58 }
59 catch (Exception ex)
60 {
61 MessageBox.Show(ex.Message);
62 return;
63 }
64 typeDUT.lblTypeAvailable.Text = "Thư mục chứa các lớp để kiểm thử:\n" + AssemblyNameToTest;
65 typeDUT.ShowDialog();
66
67 PassSelectedTypesUT(typeDUT);
68 }
69
70 private string m_typesDUT;
71 private void PassSelectedTypesUT(TypeUnderTest typeDUT)
72 {
73 if (typeDUT.TypeState == DialogResult.OK)
74 {
75 m_typesDUT = "";
76 for (int i = 0; i < typeDUT.chckListType.Items.Count; i++)
77 {
78 if (typeDUT.chckListType.GetItemChecked(i))
79 m_typesDUT = m_typesDUT + typeDUT.chckListType.GetItemText(typeDUT.chckListType.Items[i]) + " ";
80 }
81 }
82 else
83 {
84 m_typesDUT = "";
85 }
86 }
87
88 private Assembly DUTAsm;
89 private string xlsDataStoreFilename = @"C:/temp/SoftTestDataStore.xls"; //textbox2.text
90 private int Tongsodong;
91 private void Khoitaophuongthuckiemthu()
92 {
93
94 int i = 2;
95 if (m_typesDUT.Length > 1)
96 {
97 //mở sheet trong Excel
98 TaoSheet();
99
100 //load file dll
101 try
102 {
103 DUTAsm = Assembly.LoadFrom(AssemblyNameToTest);
104 }
105 catch (Exception err)
106 {
107 MessageBox.Show(err.Message);
108 }
109
110 Type[] types = null;
111 types = DUTAsm.GetTypes();
112
113 foreach (Type t in types)
114 {
115 if (m_typesDUT.IndexOf(t.Name) > -1)
116 {
117 ConstructorInfo[] cis = t.GetConstructors();
118 foreach (ConstructorInfo ci in cis)
119 {
120 LayCacCell(xSheet, i, 1, t.Name, null);
121 LayCacCell(xSheet, i, 2, t.Name, null);
122 ParameterInfo[] ps = ci.GetParameters();
123 foreach (ParameterInfo p in ps)
124 {
125 LayCacCell(xSheet, i, p.Position + 3, p.Name, p);
126 }
127 i++;
128 }
129
130 MethodInfo[] ms = t.GetMethods();
131
132 foreach (MethodInfo m in ms)
133 {
134 LayCacCell(xSheet, i, 1, t.Name, null);
135 LayCacCell(xSheet, i, 2, m.Name, null);
136 ParameterInfo[] ps = m.GetParameters();
137 foreach (ParameterInfo p in ps)
138 {
139 LayCacCell(xSheet, i, p.Position + 3, p.Name, p);
140 }
141 if (m.ReturnType.ToString() == "System.Void")
142 {
143 }
144 else
145 {
146 ThemGiaTriMongDoi(xSheet, i, m);
147 }
148 i++;
149 }
150 }
151 }
152
153 try
154 {
155 xBook.SaveAs(xlsDataStoreFilename, -4143, "", "", false, false, 0, "", 0, "", "", "");
156 }
157 catch (Exception err) { MessageBox.Show(err.Message); }
158 }
159 Tongsodong = i;
160 }
161
162 Excel.Application xApp;
163 Excel.Workbook xBook;
164 Excel.Worksheet xSheet;
165 private void TaoSheet()
166 {
167 xApp = new Excel.Application();
168 xBook = xApp.Workbooks.Add(1);
169 xSheet = (Excel.Worksheet)xBook.ActiveSheet;
170 xSheet.Cells.set_Item(1, 1, "TÊN LỚP");
171 xSheet.Cells.set_Item(1, 2, "TÊN PHƯƠNG THỨC");
172 xSheet.Cells.set_Item(1, 3, "CÁC THAM SỐ ĐẦU VÀO");
173 Excel.Range range;
174 range = xSheet.get_Range("A1", "Z1");
175 range.Interior.ColorIndex = 8;
176 range.Columns.AutoFit();
177 range.Font.Bold = true;
178 xApp.Visible = true;
179 }
180
181 private void ThemGiaTriMongDoi(Excel.Worksheet xs, int shtRow, MethodInfo mi)
182 {
183 Excel.Range range = null;
184 int parCount = 0;
185 try
186 {
187 foreach (ParameterInfo pi in mi.GetParameters())
188 {
189 parCount++;
190 }
191 string ColChar = TestUtility.ConvCHAR(parCount + 3);
192
193 range = xs.get_Range(ColChar + shtRow, ColChar + shtRow);
194 range.AddComment("giá trị mong đợi " + mi.ReturnType.ToString());
195 range.Interior.ColorIndex = 43;
196 range.Font.ColorIndex = 3;
197 range.Font.Bold = true;
198 }
199 catch { }
200 }
201
202 private void LayCacCell(Excel.Worksheet xs, int shtRow, int shtCol, string setText, ParameterInfo p)
203 {
204 string ColChar = TestUtility.ConvCHAR(shtCol);
205 Excel.Range range = null;
206 //Giá trị mong đợi trả giá trị trả về của tham số đưa vào
207 range = xs.get_Range(ColChar + shtRow, ColChar + shtRow);
208
209 if (null != p)
210 {
211 range.Value2 = TestUtility.SysToCSPro(p.ParameterType.ToString()) + " " + setText;
212 }
213 else
214 range.Value2 = setText;
215
216 if (p != null)
217 {
218 DuaVaoThamSoTuDong(p, range);
219 }
220
221 try
222 {
223 if (p == null)
224 range.Font.ColorIndex = 3;
225 else if (p != null)
226 range.AddComment(TestUtility.SysToCSPro(p.ParameterType.ToString()) + " " + setText);
227 if (p != null)
228 if (p.ParameterType.ToString().IndexOf("&") > 0)
229 {
230 if (p.IsOut)
231 range.Interior.ColorIndex = 8; //set color to a out parameter cell
232 else
233 range.Interior.ColorIndex = 6; //set color to a ref parameter cell
234 }
235 }
236 catch { }
237
238 string formulaStr = null;
239 string[] tempShort = null;
240 bool defaultEnumIsSet = false;
241
242 if (p != null)
243 {
244 if (p.ParameterType.IsEnum)
245 {
246 FieldInfo[] enumMembers = p.ParameterType.GetFields();
247 foreach (FieldInfo fs in enumMembers)
248 {
249 tempShort = fs.ToString().Trim().Split(' ');
250 if (tempShort[tempShort.Length - 1] != "value__")
251 {
252 formulaStr = formulaStr + tempShort[tempShort.Length - 1] + ",";
253 if (!defaultEnumIsSet)
254 {
255 defaultEnumIsSet = true;
256 range.Value2 = tempShort[tempShort.Length - 1];
257 }
258 }
259 }
260 defaultEnumIsSet = false;
261 formulaStr = formulaStr + "xxxx";
262 formulaStr = formulaStr.Replace(" ", ".");
263 formulaStr = formulaStr.Replace(",xxxx", "");
264
265 try
266 {
267 range.Validation.Delete();
268 range.Validation.Add(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, formulaStr, "");
269 }
270 catch { }
271 }
272 }
273 }
274
275 private void DuaVaoThamSoTuDong(ParameterInfo p, Excel.Range range)
276 {
277 Random thamso = new Random();
278
279 if (p.ParameterType.ToString().IndexOf("Boolean") > 0)
280 range.Value2 = "true";
281 if (p.ParameterType.ToString().IndexOf("Boolean") > 0 && p.ParameterType.ToString().IndexOf("&") > 0)
282 range.Value2 = "false";
283
284 if (CacKieuSo(TestUtility.SysToCSPro(p.ParameterType.ToString())))
285 {
286 if (p.ParameterType.ToString().IndexOf("Double") > 0 || p.ParameterType.ToString().IndexOf("Decimal") > 0)
287 range.Value2 = (double)thamso.Next() / 1000000;
288 else
289 range.Value2 = (int)thamso.Next() / 1000000;
290 }
291 }
292
293 private bool CacKieuSo(string typeStr)
294 {
295 if (typeStr.StartsWith("int") ||
296 typeStr.StartsWith("double") ||
297 typeStr.StartsWith("long") ||
298 typeStr.StartsWith("short") ||
299 typeStr.StartsWith("uint") ||
300 typeStr.StartsWith("float") ||
301 typeStr.StartsWith("decimal") ||
302 typeStr.StartsWith("ulong") ||
303 typeStr.StartsWith("ushort"))
304 return true;
305
306 return false;
307 }
308
309 //Start coding XML documentation
310 private void ThaoTacDulieuXML()
311 {
312 XmlDocument xmldoc = MoFileXML();
313
314 //add code to read XML data into Excel data store
315
316 for (int RowC = 2; RowC < Tongsodong; RowC++)
317 {
318 //Get the Column with data;
319 int ColC = 0;
320 Excel.Range colRange = xSheet.get_Range(TestUtility.ConvCHAR(1) + RowC, TestUtility.ConvCHAR(1) + RowC);
321 while (colRange.Value2 != null || colRange.Comment != null)
322 {
323 ColC++;
324 colRange = xSheet.get_Range(TestUtility.ConvCHAR(ColC) + RowC, TestUtility.ConvCHAR(ColC) + RowC);
325 }
326 if (ColC > 3)
327 {
328 //parameter starts from column 3
329 for (int ColCou = 3; ColCou < ColC; ColCou++)
330 {
331 DocDuLieuXMLTrongNguon(xmldoc, RowC, ColCou);
332 }
333 }
334 }
335
336 try
337 {
338 xBook.Save();
339 }
340 catch (Exception err)
341 {
342 MessageBox.Show(err.Message);
343 }
344 }
345
346 private XmlDocument MoFileXML()
347 {
348 string[] TenDuongDanThuMuc = AssemblyNameToTest.Split('\\');
349 string ThuMucGocxml = AssemblyNameToTest.Replace(TenDuongDanThuMuc[TenDuongDanThuMuc.Length - 1], "");
350 DirectoryInfo ThuMucxml = null;
351 try
352 {
353 ThuMucxml = new DirectoryInfo(ThuMucGocxml);
354 }
355 catch (Exception e)
356 {
357 MessageBox.Show(e.Message + "\n\n Nguyên nhân có thể: Tập tin XML không phải trong cùng thư mục với việc kiểm thử, hoặc thuộc tính không được thiết lập để xây dựng một đầu ra XML được đặt tên", "Không thể tìm thấy tập tin XML");
358 return null;
359 }
360 FileInfo[] TatCaFile = ThuMucxml.GetFiles();
361 FileInfo xmlFile = null;
362 foreach (FileInfo xmlF in TatCaFile)
363 {
364 if (xmlF.Extension == ".xml")
365 {
366 xmlFile = xmlF;
367 break;
368 }
369 }
370
371 if (xmlFile != null)
372 {
373 XmlReader Docfilexml = new XmlTextReader(File.OpenRead(xmlFile.FullName));
374 XmlDocument Tailieuxml = new XmlDocument();
375 Tailieuxml.Load(Docfilexml);
376 Docfilexml.Close();
377
378 return Tailieuxml;
379 }
380
381 return null;
382 }
383
384 private void DocDuLieuXMLTrongNguon(XmlDocument xmlDoc, int RowC, int ColC)
385 {
386 Excel.Range xmlRange = xSheet.get_Range(TestUtility.ConvCHAR(ColC) + RowC, TestUtility.ConvCHAR(ColC) + RowC);//LocateRangeForXML(RowC, ColC);
387
388 XmlNodeList memNames = xmlDoc.GetElementsByTagName("member");
389
390 for (int memCount = 0; memCount < memNames.Count; memCount++)
391 {
392 XmlAttributeCollection memAtt = memNames[memCount].Attributes;
393
394 string classMem = (string)xSheet.get_Range(TestUtility.ConvCHAR(1) + RowC, TestUtility.ConvCHAR(1) + RowC).Value2;//LocateRangeForXML(RowC, 1).Value2;
395 string methodMem = (string)xSheet.get_Range(TestUtility.ConvCHAR(2) + RowC, TestUtility.ConvCHAR(2) + RowC).Value2;//LocateRangeForXML(RowC, 2).Value2;
396
397 if (memAtt[0].Value.IndexOf(classMem + "." + methodMem) > 0 || memAtt[0].Value.IndexOf(classMem + ".#ctor(") > 0)//("LowLevelObj.SimpleMath") > 0)
398 {
399 XmlNodeList paramNodes = memNames[memCount].ChildNodes;
400
401 for (int paramCount = 0; paramCount < paramNodes.Count; paramCount++)
402 {
403 if (paramNodes[paramCount].Name == "param")// || paramNodes[2].Name == "returns")
404 {
405 XmlAttributeCollection paramAtt = paramNodes[paramCount].Attributes;
406
407 string[] commentStr = null;
408 try
409 {
410 commentStr = xmlRange.Comment.Shape.AlternativeText.Split(' ');
411 }
412 catch { }
413 if (commentStr != null)
414 {
415 if (paramAtt[0].Value == commentStr[commentStr.Length - 1])// "x")
416 {
417
418 DuaDuLieuXMLLenExcel(paramNodes[paramCount].InnerXml, xmlRange);
419 break;
420 }
421 }
422 }
423
424 if (paramNodes[paramCount].Name == "returns")
425 {
426 if (xmlRange.Comment.Shape.AlternativeText.IndexOf("Expect to return a") >= 0)
427 {
428
429 DuaDuLieuXMLLenExcel(paramNodes[paramCount].InnerXml, xmlRange);
430 break;
431 }
432 }
433 }
434 }
435 }
436 }
437
438 private void DuaDuLieuXMLLenExcel(string TuVanBanXML, Excel.Range PhamViXML)
439 {
440 string DenCell = TuVanBanXML;//[paramCount].InnerXml;
441 int DuLieuDauTien = DenCell.IndexOf("e.g.,");
442 //int dataLen = GotoCell.Length - startData;
443 try
444 {
445 DenCell = DenCell.Substring(DuLieuDauTien);
446 }
447 catch { }
448 DenCell = DenCell.Replace("e.g.,", "").Trim();
449 PhamViXML.Value2 = DenCell;
450 }
451
452 //Start coding chapter 7
453 private void btnExit_Click(object sender, System.EventArgs e)
454 {
455 Application.Exit();
456 }
457 private void DongExcelSheet()
458 {
459 xBook.Close(false, Missing.Value, false);
460 xApp.Quit();
461 xSheet = null;
462 xBook = null;
463 xApp = null;
464 }
465
466 Excel.Range range = null;
467 Type typ = null;
468 Type[] types = null;
469 CodeMemberMethod cm = null;
470 CodeDomProvider codeProvider = null;
471 ICodeGenerator cg = null;
472 string nameSpace = null;
473 CodeCompileUnit TestUnit;
474 CodeNamespace cnamespace;
475 string clsName;
476 CodeTypeDeclaration co;
477 CodePropertyReferenceExpression pState = null;
478 CodeExpression[] pCode = null;
479 CodeFieldReferenceExpression cLeft = null;
480 CodeFieldReferenceExpression cRight = null;
481
482 private void TaoMaKiemThu(Assembly DUT, TextWriter t)
483 {
484 BatDauCodeDom(DUT);
485 ThemNamespaces(DUT);
486 PhuongThucLopDauTien();
487 TaoMaSheet(cm);
488 ThemMaExcelDauTien(cm);
489 MaCuaCacPhuongThuc(cm);
490
491 //Thông tin bắt đầu từ dòng 2 của Excel sheet
492 int i = 2;
493
494 range = xSheet.get_Range(TestUtility.ConvCHAR(1) + i, TestUtility.ConvCHAR(1) + i);
495 string previousType = range.Value2.ToString();
496 KhoiTaoCacKieuKiemThu(i, ref previousType);
497
498 int totalRows = DemCacDongTrongSheet(xSheet);
499
500 MethodInfo mi = null;
501 ConstructorInfo ci = null; //khởi tạo
502 Type[] AmbiguousOverLoad = null;
503 string wholeCellText = null;
504 string[] typeText = null;
505 string strPar = null;
506 string[] arrayPar = null;
507 Excel.Range rng;
508 Excel.Range rngCstr;
509
510 for (i = 2; i < totalRows; i++)//while (range.Value2.ToString() != "")
511 {
512 int j = 3;
513
514 CacKieuMoi(ref i, ref j, ref previousType);
515
516 rng = xSheet.get_Range(TestUtility.ConvCHAR(j) + i, TestUtility.ConvCHAR(j) + i);
517 rngCstr = xSheet.get_Range(TestUtility.ConvCHAR(1) + i, TestUtility.ConvCHAR(1) + i);
518
519 if (range.Value2.ToString() == rngCstr.Value2.ToString())//kiểm tra xem nó được khởi tạo
520 {
521 ThemKhoiMaKiemThu(ref i, ref j, ref rng, ref wholeCellText, ref typeText, ref strPar, ref arrayPar, ref AmbiguousOverLoad, ref ci);
522 }
523 else
524 {
525 ThemMaPhuongThucKiemThu(ref i, ref j, ref mi, ref rng, ref wholeCellText, ref typeText, ref strPar, ref arrayPar, ref AmbiguousOverLoad);
526
527 ParameterInfo[] ps = mi.GetParameters();
528 string parStr = "";
529
530 ThuThapCacThamSochoKiemThu(ref i, ref j, ref rng, ref ps, ref parStr);
531
532 pState = new CodePropertyReferenceExpression(null, "obj" + typ.Name);
533 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, parStr) };
534 CodeStatement[] trySt = null;
535 CodeExpression[] passPar = new CodeExpression[] { new CodeFieldReferenceExpression(null, "xResult, shtRow, mName") };
536
537 AddInvokeTestMethodCallCode(ref i, ref parStr, ref mi, ref trySt, ref passPar);
538
539 //add log result code
540 int colPosition = 0;
541 LogParmResultAndReturnValue(ref i, colPosition, ps, ref mi);
542 }
543 range = xSheet.get_Range(TestUtility.ConvCHAR(1) + i, TestUtility.ConvCHAR(1) + i);
544 }
545 AddOtherCodesPartII(cm, clsName);
546
547 if (objReturnStub == null)//Thêm cho việc kiểm thử COM
548 objReturnStub = new CodeSnippetExpression("null"); //thêm cho việc kiểm thử COM
549 cm.Statements.Add(new CodeMethodReturnStatement(objReturnStub));
550 objReturnStub = null;
551 AddUpClassesMethods();
552 cg.GenerateCodeFromNamespace(cnamespace, t, null);
553 DocFileCSPROJ(clsName, DUTAsm);
554 }
555 private void BatDauCodeDom(Assembly DUT)
556 {
557 TestUnit = new CodeCompileUnit();
558
559 types = DUT.GetTypes();
560 codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
561 foreach (Type ty in types)
562 {
563 nameSpace = ty.Namespace + "Test";
564 }
565 cnamespace = new CodeNamespace(nameSpace);
566
567 clsName = "Test" + DUTAsm.FullName.Substring(0, DUTAsm.FullName.IndexOf(", "));
568
569 cg = codeProvider.CreateGenerator();
570 }
571
572 private void ThemNamespaces(Assembly DUT)
573 {
574 TestUnit.Namespaces.Add(cnamespace);
575 cnamespace.Imports.Add(new CodeNamespaceImport("System"));
576 cnamespace.Imports.Add(new CodeNamespaceImport("System.IO"));
577 cnamespace.Imports.Add(new CodeNamespaceImport("Excel=Microsoft.Office.Interop.Excel"));
578 cnamespace.Imports.Add(new CodeNamespaceImport("System.Reflection"));
579 AssemblyName[] asms = null;
580 asms = DUT.GetReferencedAssemblies();
581 foreach (AssemblyName asm in asms)
582 {
583 if (asm.Name.ToString() != "mscorlib")
584 {
585 if (asm.Name.IndexOf(".") > 0 && asm.Name != "")
586 cnamespace.Imports.Add(new CodeNamespaceImport(asm.Name));
587 }
588 }
589 }
590
591 private void PhuongThucLopDauTien()
592 {
593 //add class name
594 co = new CodeTypeDeclaration(clsName);
595 cnamespace.Types.Add(co);
596 co.Attributes = (System.CodeDom.MemberAttributes)TypeAttributes.Public;
597
598 //add main mehtod
599 cm = new CodeMemberMethod();
600 cm.Name = "StartTest";//"Main";
601 cm.ReturnType = new CodeTypeReference(typeof(object));//added for integration
602 cm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
603 }
604 private void TaoMaSheet(CodeMemberMethod cm)
605 {
606 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Application), "xApp = new Excel.Application()"));
607 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Workbook), "xBook = xApp.Workbooks.Open(fileName, 0, false, 1, \"\", \"\", true, 1, 0, true, 1, 0, 0, 0, 0)"));
608 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Worksheet), "xSheet = (Excel.Worksheet)xBook.ActiveSheet"));
609 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Workbook), "xBook2 = xApp.Workbooks.Add(1)"));
610 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Worksheet), "xResult = (Excel.Worksheet)xBook2.ActiveSheet"));
611 }
612
613 private void ThemMaExcelDauTien(CodeMemberMethod cm)
614 {
615 CodePropertyReferenceExpression pState = null;
616 CodeExpression[] pCode = null;
617
618 pState =
619 new CodePropertyReferenceExpression(null, "xResult");
620 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 1, \"PHƯƠNG THỨC KIỂM THỬ\"") };
621 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
622
623 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 2, \"KẾT QUẢ\"") };
624 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
625
626 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 3, \"NGUYÊN NHÂN LỖI\"") };
627 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
628
629 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 4, \"KẾT QUẢ TRẢ VỀ\"") };
630 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
631
632 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 5, \"KẾT QUẢ MONG ĐỢI\"") };
633 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
634
635 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "1, 6, \"CÁC THAM SỐ VÀ GIÁ TRỊ\"") };
636 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
637 }
638 private void MaCuaCacPhuongThuc(CodeMemberMethod cm)
639 {
640 CodePropertyReferenceExpression pState = null;
641 CodeExpression[] pCode = null;
642 CodeFieldReferenceExpression cLeft = null;
643 CodeFieldReferenceExpression cRight = null;
644
645 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "xApp.Visible") };
646 cLeft = new CodeFieldReferenceExpression(null, "xApp.Visible");
647 cRight = new CodeFieldReferenceExpression(null, " true");//sysbooltrue.ToString().ToLower());
648 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
649
650 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Range), "range"));
651 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Range), "rangeCurr"));
652 cLeft = new CodeFieldReferenceExpression(null, "range");
653 cRight = new CodeFieldReferenceExpression(null, "xResult.get_Range(\"A1\", \"H1\")");
654 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
655
656 cLeft = new CodeFieldReferenceExpression(null, "range.Interior.ColorIndex");
657 cRight = new CodeFieldReferenceExpression(null, "8");
658 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
659
660 cLeft = new CodeFieldReferenceExpression(null, "range.Font.Bold");
661 cRight = new CodeFieldReferenceExpression(null, " true");//sysbooltrue.ToString().ToLower());
662 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
663
664
665 pState = new CodePropertyReferenceExpression(null, "range");
666 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Columns.AutoFit"));
667
668 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(int), "shtRow = 0"));
669 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(string), "mName = null"));
670 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(int), "tempArrayIndex = 0"));
671 }
672
673 //initiate an object for the StartTest method to return an object
674 //in order to use a bottom up approach for integration testing.
675 CodeSnippetExpression objReturnStub;//added for integration
676 private void KhoiTaoCacKieuKiemThu(int i, ref string KieuTruoc)
677 {
678 foreach (Type ty in types)
679 {
680 if (ty.Name.ToString() == KieuTruoc)
681 {
682 typ = ty;
683 }
684 }
685 string nameSPLen = typ.Namespace;
686 if (nameSPLen != null || typ.Namespace != null)
687 cnamespace.Imports.Add(new CodeNamespaceImport(typ.Namespace));
688 if (typ.IsClass)
689 {
690 cm.Statements.Add(new CodeParameterDeclarationExpression(typ.Name, "obj" + typ.Name + " = null"));//modified for constructor
691 objReturnStub = new CodeSnippetExpression("obj" + typ.Name);//added for integration
692 }
693 else if (typ.IsInterface)
694 {
695 cm.Statements.Add(new CodeParameterDeclarationExpression(typ.Name, "obj" + typ.Name + " = null"));
696 foreach (Type ty in types)
697 {
698 if (ty.IsClass)
699 {
700 cm.Statements.Add(new CodeParameterDeclarationExpression(ty.Name, "obj_" + i + ty.Name + " = new " + ty.Name + "()"));
701 cLeft = new CodeFieldReferenceExpression(null, "obj" + typ.Name);
702 cRight = new CodeFieldReferenceExpression(null, "(" + typ.Name + ")obj_" + i + ty.Name);
703 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
704 }
705 }
706 }
707
708 }
709 private int DemCacDongTrongSheet(Excel.Worksheet xSheet)
710 {
711 Excel.Range range = null;
712 int i = 1;
713 range = xSheet.get_Range("A" + i, "A" + i);
714 while (range.Value2 != null)
715 {
716 i++;
717 range = xSheet.get_Range("A" + i, "A" + i);
718 }
719 return i;
720 }
721
722 private void CacKieuMoi(ref int i, ref int j, ref string KieuTruoc)
723 {
724 range = xSheet.get_Range(TestUtility.ConvCHAR(1) + i, TestUtility.ConvCHAR(1) + i);
725 string currentType = range.Value2.ToString();
726 if (KieuTruoc != currentType)
727 {
728 foreach (Type ty in types)
729 {
730 if (ty.Name.ToString() == currentType)
731 {
732 typ = ty;
733 }
734 }
735 KieuTruoc = currentType;
736 //Sửa đổi để thêm khởi tạo
737 cm.Statements.Add(new CodeParameterDeclarationExpression(typ.Name, "obj" + typ.Name + " = null"));
738 }
739 range = xSheet.get_Range(TestUtility.ConvCHAR(2) + i, TestUtility.ConvCHAR(2) + i);
740
741 cLeft = new CodeFieldReferenceExpression(null, "shtRow");
742 cRight = new CodeFieldReferenceExpression(null, "" + i);
743 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
744
745 }
746 private void ThemKhoiMaKiemThu(ref int i, ref int j, ref Excel.Range rng, ref string wholeCellText, ref string[] typeText, ref string strPar, ref string[] arrayPar, ref Type[] AmbiguousOverLoad, ref ConstructorInfo ci)
747 {
748 cLeft = new CodeFieldReferenceExpression(null, "mName");
749 cRight = new CodeFieldReferenceExpression(null, "\"" + typ.Name + "\"");
750 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
751 strPar = ""; //Start a new variable
752 while (rng.Value2 != null)
753 {
754 wholeCellText = rng.Comment.Text("", 1, 0);
755 typeText = wholeCellText.Split(' ');
756 strPar = strPar + typeText[0] + ",";
757 j++;
758 rng = xSheet.get_Range(TestUtility.ConvCHAR(j) + i, TestUtility.ConvCHAR(j) + i);
759 }
760 if (strPar != null)
761 {
762 strPar = strPar.Replace("Expect,", "");
763 arrayPar = strPar.Split(',');
764 AmbiguousOverLoad = new Type[arrayPar.Length - 1];
765 for (int parPos = 0; parPos < arrayPar.Length - 1; parPos++)//enumerate parameters
766 {
767 TestUtility.ConvertStringToType(arrayPar[parPos], ref AmbiguousOverLoad[parPos]);
768 }
769 ci = typ.GetConstructor(AmbiguousOverLoad);
770 }
771 else//if (strPar == "")
772 ci = typ.GetConstructor(new Type[0]);
773
774 if (ci != null)
775 {
776 ParameterInfo[] pars = ci.GetParameters();
777 foreach (ParameterInfo p in pars)
778 {
779 ThemMaChoCacThamSo(p, cm, i);
780 }
781
782 ThemCacKhoiMa(typ, ci, cm, i);
783 }
784 pState = new CodePropertyReferenceExpression(null, "xResult");
785 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 4, \"Test Constructor\"") };
786 cm.Statements.Add(new CodeMethodInvokeExpression(pState, "Cells.set_Item", pCode));
787
788 }
789 private void ThemMaChoCacThamSo(ParameterInfo p, CodeMemberMethod cm, int i)
790 {
791 Excel.Range rng = xSheet.get_Range(TestUtility.ConvCHAR(p.Position + 3) + i, TestUtility.ConvCHAR(p.Position + 3) + i); //added for pass parameter by object
792
793 CodeFieldReferenceExpression cLeft = new CodeFieldReferenceExpression(null, "range");
794 CodeFieldReferenceExpression cRight = new CodeFieldReferenceExpression(null, "xSheet.get_Range(\"" + TestUtility.ConvCHAR(p.Position + 3) + i + "\", \"" + TestUtility.ConvCHAR(p.Position + 3) + i + "\")");
795 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
796 //int errorCode = int.Parse(range.Value2.ToString());
797 cLeft = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString()) + " " + p.Name + "_" + i);
798 //cRight=new CodeFieldReferenceExpression(null, "new System.Text.StringBuilder()");
799 if (p.ParameterType.ToString().StartsWith("System.String") || p.ParameterType.ToString().StartsWith("System.Object"))
800 {
801 cRight = new CodeFieldReferenceExpression(null, "range.Value2.ToString()");
802 }
803 else if (p.ParameterType.ToString().IndexOf("[]") > 0)
804 {
805 //cRight=new CodeFieldReferenceExpression(null, "{" + TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]","")) + ".Parse(range.Value2.ToString())}"); //commented to read array
806 if (TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) == "string")
807 {
808 cRight = new CodeFieldReferenceExpression(null, "range.Value2.ToString().Split(',')");
809 }
810 else
811 {
812 cRight = new CodeFieldReferenceExpression(null, " null");
813 //cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
814
815 //cLeft=new CodeFieldReferenceExpression(null, "tempArray");
816 cRight = new CodeFieldReferenceExpression(null, "new " + TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + "[range.Value2.ToString().Split(',').Length]");
817 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
818 //foreach (string z in x.Split(',')){a[i]=int.Parse(z);i++;};
819 cLeft = new CodeFieldReferenceExpression(null, "foreach (string z in range.Value2.ToString().Split(',')){" + p.Name + "_" + i + "[tempArrayIndex]");
820 cRight = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + ".Parse(z); tempArrayIndex++;}");
821 //cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
822 }
823 }
824 else if (p.ParameterType.ToString().IndexOf("Text.StringBuilder") > 0)
825 {
826 cRight = new CodeFieldReferenceExpression(null, "new System.Text.StringBuilder()");
827 }
828 else if (rng.Value2.ToString() == "new")
829 {
830 cRight = new CodeFieldReferenceExpression(null, "new " + p.ParameterType.ToString() + "()");
831 }
832 else
833 {
834 cRight = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + ".Parse(range.Value2.ToString())");
835 }
836 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
837 if (p.ParameterType.ToString().IndexOf("[]") > 0)
838 {
839 cLeft = new CodeFieldReferenceExpression(null, "tempArrayIndex");
840 cRight = new CodeFieldReferenceExpression(null, "0");
841 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
842 }
843 }
844 private void ThemCacKhoiMa(Type typ, ConstructorInfo ci, CodeMemberMethod cm, int i)
845 {
846 string pCodeStr = "";
847
848 CodeStatement[] trySt;
849 CodeExpression[] passPar = new CodeExpression[] { new CodeFieldReferenceExpression(null, "xResult, shtRow, mName") };
850
851 ParameterInfo[] pis = ci.GetParameters();
852 foreach (ParameterInfo pi in pis)
853 {
854 pCodeStr += pi.Name + "_" + i + ", ";
855 }
856 if (pCodeStr.IndexOf(",") > 0)
857 {
858 pCodeStr += "xxxx";
859 pCodeStr = pCodeStr.Replace(", xxxx", "");
860 }
861 CodeExpression[] pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, pCodeStr) };
862
863 trySt = new CodeStatement[] {new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "obj" + typ.Name + " = new " + typ.Name, pCode)),
864 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestPass", passPar)),
865 };
866
867 //TestFail(xResult, shtRow, mName, err.Message);
868 passPar = new CodeExpression[] { new CodeFieldReferenceExpression(null, "xResult, shtRow, mName, err.Message") };
869 CodeCatchClause catchCl = new CodeCatchClause("err", new CodeTypeReference(typeof(Exception)), new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestFail", passPar)));
870
871 CodeCatchClause[] catchSt = new CodeCatchClause[]{ catchCl
872 };
873 cm.Statements.Add(new CodeTryCatchFinallyStatement(trySt, catchSt));
874 }
875
876 private void ThemMaPhuongThucKiemThu(ref int i, ref int j, ref MethodInfo mi, ref Excel.Range rng, ref string wholeCellText, ref string[] typeText, ref string strPar, ref string[] arrayPar, ref Type[] AmbiguousOverLoad)
877 {
878 try
879 {
880 mi = typ.GetMethod(range.Value2.ToString());
881 }
882 catch (Exception err)
883 {
884 Console.WriteLine(err.Message);
885 strPar = ""; //Start a new variable
886 while (rng.Value2 != null)
887 {
888 //wholeCellText = rng.Value2.ToString();
889 wholeCellText = rng.Comment.Text("", 1, 0);
890 typeText = wholeCellText.Split(' ');
891 strPar = strPar + typeText[0] + ",";
892 j++;
893 rng = xSheet.get_Range(TestUtility.ConvCHAR(j) + i, TestUtility.ConvCHAR(j) + i);
894 }
895
896 if (strPar == "Expect,")
897 strPar = null;
898
899 if (strPar != null)
900 {
901 strPar = strPar.Replace("Expect,", "");
902 arrayPar = strPar.Split(',');
903 AmbiguousOverLoad = new Type[arrayPar.Length - 1];
904 for (int parPos = 0; parPos < arrayPar.Length - 1; parPos++)//enumerate parameters
905 {
906 TestUtility.ConvertStringToType(arrayPar[parPos], ref AmbiguousOverLoad[parPos]);
907 }
908 mi = typ.GetMethod(range.Value2.ToString(), AmbiguousOverLoad);
909 }
910 else//if (strPar == "")
911 mi = typ.GetMethod(range.Value2.ToString(), new Type[0]);
912 }
913 cLeft = new CodeFieldReferenceExpression(null, "mName");
914 cRight = new CodeFieldReferenceExpression(null, "\"" + mi.Name + "\"");
915 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
916 }
917
918 private void ThuThapCacThamSochoKiemThu(ref int i, ref int j, ref Excel.Range rng, ref ParameterInfo[] ps, ref string parStr)
919 {
920 foreach (ParameterInfo p in ps)
921 {
922 rng = xSheet.get_Range(TestUtility.ConvCHAR(p.Position + 3) + i, TestUtility.ConvCHAR(p.Position + 3) + i); //added for pass parameter by object
923 cLeft = new CodeFieldReferenceExpression(null, "range");
924 cRight = new CodeFieldReferenceExpression(null, "xSheet.get_Range(\"" + TestUtility.ConvCHAR(p.Position + 3) + i + "\", \"" + TestUtility.ConvCHAR(p.Position + 3) + i + "\")");
925 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
926 cLeft = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString()) + " " + p.Name + "_" + i);
927
928 if (rng.Value2.ToString().ToUpper().StartsWith("WINREG"))
929 {
930 NeedWinReg = true;
931 if (p.ParameterType == typeof(string) || p.ParameterType.ToString() == "System.String&")
932 cRight = new CodeFieldReferenceExpression(null, "(string)GetWinRegValue(range.Value2.ToString())");
933 else if (p.ParameterType == typeof(bool) || p.ParameterType.ToString() == "System.Boolean&")
934 cRight = new CodeFieldReferenceExpression(null, "(bool)GetWinRegValue(range.Value2.ToString())");
935 else if (p.ParameterType == typeof(object) || p.ParameterType.ToString() == "System.Object&")
936 cRight = new CodeFieldReferenceExpression(null, "GetWinRegValue(range.Value2.ToString())");
937 else
938 cRight = new CodeFieldReferenceExpression(null, "(int)GetWinRegValue(range.Value2.ToString())");
939 }
940 else if (p.ParameterType.ToString().StartsWith("System.String") || p.ParameterType.ToString().StartsWith("System.Object"))
941 {
942 cRight = new CodeFieldReferenceExpression(null, "range.Value2.ToString()");
943 }
944 else if (p.ParameterType.IsEnum)
945 {
946 cRight = new CodeFieldReferenceExpression(null, p.ParameterType.ToString() + "." + rng.Value2);
947 }
948 else if (p.ParameterType.ToString().IndexOf("[]") > 0)
949 {
950 if (TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) == "string")
951 {
952 cRight = new CodeFieldReferenceExpression(null, "range.Value2.ToString().Split(',')");
953 }
954 else
955 {
956 cRight = new CodeFieldReferenceExpression(null, " null");
957 cRight = new CodeFieldReferenceExpression(null, "new " + TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + "[range.Value2.ToString().Split(',').Length]");
958 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
959 cLeft = new CodeFieldReferenceExpression(null, "foreach (string z in range.Value2.ToString().Split(',')){" + p.Name + "_" + i + "[tempArrayIndex]");
960 cRight = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + ".Parse(z); tempArrayIndex++;}");
961 }
962 }
963 else if (p.ParameterType.ToString().IndexOf("Text.StringBuilder") > 0)
964 {
965 cRight = new CodeFieldReferenceExpression(null, "new System.Text.StringBuilder()");
966 }
967 else if (rng.Value2.ToString() == "new")
968 {
969 TaoThongSoDoiTuong(ref i, p);
970 }
971 else
972 {
973 cRight = new CodeFieldReferenceExpression(null, TestUtility.SysToCSPro(p.ParameterType.ToString().Replace("[]", "")) + ".Parse(range.Value2.ToString())");
974 }
975
976 AddStubDecision(rng);
977 if (p.ParameterType.ToString().IndexOf("[]") > 0)
978 {
979 cLeft = new CodeFieldReferenceExpression(null, "tempArrayIndex");
980 cRight = new CodeFieldReferenceExpression(null, "0");
981 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
982 }
983
984 if (p.ParameterType.ToString().IndexOf("Text.StringBuilder") > 0)
985 {
986 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "range.Value2.ToString()") };
987 cm.Statements.Add(new CodeMethodInvokeExpression(null, p.Name.ToString() + "_" + i + ".Append", pCode));
988 }
989
990 if (p.Position != 0)
991 {
992 if (p.ParameterType.ToString().IndexOf("&") > 0)
993 {
994 if (!p.IsOut)
995 parStr = parStr + ", ref " + p.Name + "_" + i;
996 else
997 parStr = parStr + ", out " + p.Name + "_" + i;
998 }
999 else
1000 parStr = parStr + ", " + p.Name + "_" + i;
1001 }
1002 else if (p.ParameterType.ToString().IndexOf("&") > 0)
1003 {
1004 if (!p.IsOut)
1005 parStr = parStr + "ref " + p.Name + "_" + i;
1006 else
1007 parStr = parStr + "out " + p.Name + "_" + i;
1008 }
1009 else
1010 parStr = parStr + p.Name + "_" + i;
1011 }
1012 }
1013 private void AddInvokeTestMethodCallCode(ref int i, ref string parStr, ref MethodInfo mi, ref CodeStatement[] trySt, ref CodeExpression[] passPar)
1014 {
1015 if (mi.ReturnType.ToString() == "System.Void")
1016 {
1017 string propertySETname = "xxx" + mi.Name.ToString();
1018 if (propertySETname.Trim().StartsWith("xxxset_"))
1019 {
1020 trySt = new CodeStatement[] {new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "obj" + typ.Name + "." + mi.Name.Replace("set_", "") + " = ", pCode)),
1021 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestPass", passPar)),
1022 };
1023 }
1024 else
1025 {
1026 trySt = new CodeStatement[] {new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "obj" + typ.Name + "." + mi.Name, pCode)),
1027 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestPass", passPar)),
1028 };
1029 }
1030 }
1031 else
1032 {
1033 string propertyname = "xxx" + mi.Name.ToString();
1034 if (propertyname.Trim().StartsWith("xxxget_"))
1035 {
1036 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "" + i + ", " + 4 + ", obj" + typ.Name + "." + mi.Name.Replace("get_", "")) };
1037 trySt = new CodeStatement[] {new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode)),
1038 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestPass", passPar)),
1039 };
1040 }
1041 else
1042 {
1043
1044 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "" + i + ", " + 4 + ", obj" + typ.Name + "." + mi.Name + "(" + parStr + ")"+".ToString()") };
1045 trySt = new CodeStatement[] {new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode)),
1046 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestPass", passPar)),
1047 };
1048 }
1049 }
1050 //TestFail(xResult, shtRow, mName, err.Message);
1051 passPar = new CodeExpression[] { new CodeFieldReferenceExpression(null, "xResult, shtRow, mName, err.Message") };
1052 CodeCatchClause catchCl = new CodeCatchClause("err", new CodeTypeReference(typeof(Exception)), new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "TestFail", passPar)));
1053 CodeCatchClause[] catchSt = new CodeCatchClause[]{ catchCl
1054 };
1055 cm.Statements.Add(new CodeTryCatchFinallyStatement(trySt, catchSt));
1056 }
1057 private void LogParmResultAndReturnValue(ref int i, int colPosition, ParameterInfo[] ps, ref MethodInfo mi)
1058 {
1059 foreach (ParameterInfo p in ps)
1060 {
1061 colPosition = p.Position + 6;
1062 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow" + ", " + colPosition + ", \"" + p.Name + " = \" + " + p.Name + "_" + i) };
1063 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1064 }
1065 //added to transfer expected return to the result sheet
1066 if (mi.ReturnType.ToString() != "System.Void")
1067 {
1068 if (colPosition > 0)
1069 colPosition -= 6;
1070 else
1071 colPosition -= 1;
1072
1073 AddMethodCodes(cm, colPosition, i);
1074 }
1075 }
1076 private void AddMethodCodes(CodeMemberMethod cm, int colPosition, int i)
1077 {
1078 CodeExpression[] pCode = null;
1079 CodeFieldReferenceExpression cLeft = null;
1080 CodeFieldReferenceExpression cRight = null;
1081
1082 cLeft = new CodeFieldReferenceExpression(null, "range");
1083 cRight = new CodeFieldReferenceExpression(null, "xSheet.get_Range(\"" + TestUtility.ConvCHAR(colPosition + 4) + i + "\", \"" + TestUtility.ConvCHAR(colPosition + 4) + i + "\")");
1084 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1085
1086 //if (range.Value2 != null)
1087 // xResult.Cells.set_Item(shtRow, 5, range.Value2.ToString());
1088 // pCode = new CodeExpression[]{new CodeFieldReferenceExpression(null, "shtRow" + ", " + 5 + ", range.Value2.ToString()")};
1089 // cm.Statements.Add(new CodeMethodInvokeExpression(null, "if (range.Value2 != null) xResult.Cells.set_Item", pCode));
1090 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 5, range.Value2.ToString()") };
1091 CodeConditionStatement ifState = new CodeConditionStatement(new CodeSnippetExpression("range.Value2 != null"), new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode)));
1092 cm.Statements.Add(ifState);
1093
1094
1095
1096 cLeft = new CodeFieldReferenceExpression(null, "rangeCurr");
1097 cRight = new CodeFieldReferenceExpression(null, "xResult.get_Range(\"" + TestUtility.ConvCHAR(4) + i + "\", \"" + TestUtility.ConvCHAR(4) + i + "\")");
1098 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1099 //if (range.Value2.ToString() != range.Value2.ToString() && range.Value2 != null)
1100 // range.Interior.ColorIndex = 3;
1101 cLeft = new CodeFieldReferenceExpression(null, "if (rangeCurr.Value2 != null) if (range.Value2 != null && rangeCurr.Value2.ToString() != range.Value2.ToString()) rangeCurr.Interior.ColorIndex");
1102 cRight = new CodeFieldReferenceExpression(null, "3");
1103 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1104 cLeft = new CodeFieldReferenceExpression(null, "if (rangeCurr.Value2 != null) if (range.Value2 != null && rangeCurr.Value2.ToString() == range.Value2.ToString()) rangeCurr.Interior.ColorIndex");
1105 cRight = new CodeFieldReferenceExpression(null, "4");
1106 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1107
1108 }
1109 string XlsReportFilename = @"C:/Temp"; //textbox10text
1110 string tempTestProjDir = @"C:/Temp";//textbox8text
1111 private void AddOtherCodesPartII(CodeMemberMethod cm, string clsName)
1112 {
1113 CodeExpression[] pCode = null;
1114 CodeFieldReferenceExpression cLeft = null;
1115 CodeFieldReferenceExpression cRight = null;
1116
1117 cLeft = new CodeFieldReferenceExpression(null, "string datetime");
1118 cRight = new CodeFieldReferenceExpression(null, "DateTime.Now.Date.ToShortDateString() + DateTime.Now.Hour.ToString()+DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString()");
1119 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1120
1121 //datetime = datetime.Replace("/", "");
1122 cLeft = new CodeFieldReferenceExpression(null, "datetime");
1123 cRight = new CodeFieldReferenceExpression(null, "datetime.Replace(\"/\", \"\")");
1124 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1125
1126 //datetime = datetime.Replace(":", "");
1127 cLeft = new CodeFieldReferenceExpression(null, "datetime");
1128 cRight = new CodeFieldReferenceExpression(null, "datetime.Replace(\":\", \"\")");
1129 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1130 //string resultFile =System.IO.Path.Combine(Environment.CurrentDirectory, "xyz" + x.GetDate().Replace("/","") + x.GetTime().Replace(":","") + ".xls");
1131 cLeft = new CodeFieldReferenceExpression(null, "string resultFile");
1132 cRight = new CodeFieldReferenceExpression(null, "System.IO.Path.Combine(\"" + XlsReportFilename + "\", \"" + clsName + "\" + datetime + \".xls\")");
1133 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1134 // xBook2.SaveAs(resultFile, -4143, "", "", false, false, 0, "", 0, "", "", "");
1135 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "resultFile, -4143, \"\", \"\", false, false, 0, \"\", 0, \"\", \"\", \"\"") };
1136 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xBook2.SaveAs", pCode));
1137 // xBook.Close(null, null, null);
1138 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, " false, null, false") };
1139 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xBook.Close", pCode));
1140 // xBook2.Close(null, null, null);
1141 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xBook2.Close", pCode));
1142 // xApp.Quit();
1143 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xApp.Quit"));
1144 // xSheet = null;
1145 cLeft = new CodeFieldReferenceExpression(null, "xSheet");
1146 cRight = new CodeFieldReferenceExpression(null, " null");
1147 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1148 // xResult = null;
1149 cLeft = new CodeFieldReferenceExpression(null, "xResult");
1150 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1151 // xBook = null;
1152 cLeft = new CodeFieldReferenceExpression(null, "xBook");
1153 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1154 // xBook2 = null;
1155 cLeft = new CodeFieldReferenceExpression(null, "xBook2");
1156 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1157 // xApp = null;
1158 cLeft = new CodeFieldReferenceExpression(null, "xApp");
1159 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1160 }
1161
1162 private void AddUpClassesMethods()
1163 {
1164 co.Members.Add(cm);
1165
1166 CreateTestPassMethod(cm, "TestPass");
1167 CreateTestFailMethod(cm, "TestFail");
1168
1169 //add a file name field
1170 AddFilenameField(co);
1171 //add a constructor
1172 AddCstorCodes(co);
1173 //add a class to start the Main method
1174 CodeTypeDeclaration eco = new CodeTypeDeclaration("Start" + clsName);
1175 eco.TypeAttributes = TypeAttributes.Public;
1176 cnamespace.Types.Add(eco);
1177
1178 //add the Main method
1179
1180 AddMainMethod(eco, clsName);
1181 //eco.Members.Add(cm);
1182 }
1183 private void AddFilenameField(CodeTypeDeclaration co)
1184 {
1185 CodeMemberField cf = new CodeMemberField();
1186 cf.Name = "fileName = \"" + xlsDataStoreFilename + "\"";
1187 cf.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1188 cf.Type = new CodeTypeReference(typeof(string));
1189 co.Members.Add(cf);
1190 }
1191 private void AddCstorCodes(CodeTypeDeclaration co)
1192 {
1193 CodeFieldReferenceExpression cLeft = null;
1194 CodeFieldReferenceExpression cRight = null;
1195
1196
1197 CodeConstructor cc = new CodeConstructor();
1198 cc.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1199 co.Members.Add(cc);
1200
1201 //overload a constructor to load a data store file
1202 cc = new CodeConstructor();
1203 cc.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1204 cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "fileName"));
1205 cLeft = new CodeFieldReferenceExpression(null, "this.fileName");
1206 cRight = new CodeFieldReferenceExpression(null, "fileName");
1207 cc.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1208 co.Members.Add(cc);
1209 }
1210
1211 private void AddMainMethod(CodeTypeDeclaration eco, string clsName)
1212 {
1213 CodeEntryPointMethod entryCM = new CodeEntryPointMethod();// CodeMemberMethod();
1214 CodeFieldReferenceExpression cLeft = null;
1215 CodeFieldReferenceExpression cRight = null;
1216
1217 //entryCM.Name = "Main";
1218 //cm.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
1219 //entryCM.Parameters.Add(new CodeParameterDeclarationExpression("System.String[]", "agrs"));
1220 //cm.ReturnType = new CodeTypeReference(typeof(void));
1221
1222 //string rootDir = Environment.CurrentDirectory;
1223 cLeft = new CodeFieldReferenceExpression(null, "string rootDir");
1224 cRight = new CodeFieldReferenceExpression(null, "Environment.CurrentDirectory");
1225 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1226
1227 //tested //string [] fileArray = null;
1228 entryCM.Statements.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.String", 1), "fileArray = null"));
1229 //StreamReader sr = File.OpenText("fileArray.txt");
1230 cLeft = new CodeFieldReferenceExpression(null, "StreamReader sr");
1231 cRight = new CodeFieldReferenceExpression(null, "File.OpenText(System.IO.Path.Combine(\"" + tempTestProjDir + "/" + dirName + "/Bin/Debug" + "\", \"fileArray.txt\"))");
1232 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1233 //string input = null
1234 cLeft = new CodeFieldReferenceExpression(null, "string input");
1235 cRight = new CodeFieldReferenceExpression(null, " null");
1236 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1237 //string fStr = null;
1238 cLeft = new CodeFieldReferenceExpression(null, "string fStr");
1239 cRight = new CodeFieldReferenceExpression(null, " null");
1240 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1241
1242 //tested //while((input = sr.ReadLine()) != null) fStr = fStr + input + ",";
1243 cLeft = new CodeFieldReferenceExpression(null, "while ((input = sr.ReadLine()) != null) fStr");
1244 cRight = new CodeFieldReferenceExpression(null, "fStr + input + \",\"");
1245 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1246
1247 //Tested //sr.Close();
1248 entryCM.Statements.Add(new CodeMethodInvokeExpression(null, "sr.Close"));
1249 //fStr = fStr.Replace("/", "\\")
1250 cLeft = new CodeFieldReferenceExpression(null, "fStr");
1251 cRight = new CodeFieldReferenceExpression(null, "fStr.Replace(\"/\", \"\\\\\")");
1252 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1253
1254 //fileArray = fStr.Split(',');
1255 cLeft = new CodeFieldReferenceExpression(null, "fileArray");
1256 cRight = new CodeFieldReferenceExpression(null, "fStr.Split(\',\')");
1257 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1258
1259 //TestDotNetClassLib test = null;
1260 cLeft = new CodeFieldReferenceExpression(null, clsName + " test");
1261 cRight = new CodeFieldReferenceExpression(null, " null");
1262 entryCM.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1263
1264 //for (int i = 0; i < fileArray.Length; i++)
1265 //{
1266 // test =new TestDotNetClassLib(fileArra[i]);
1267 // test.StartTest();
1268 //}
1269 cLeft = new CodeFieldReferenceExpression(null, "test");
1270 cRight = new CodeFieldReferenceExpression(null, "new " + clsName + "(System.IO.Path.Combine(rootDir, fileArray[i]))");
1271 CodeIterationStatement loop = new CodeIterationStatement(
1272 new CodeVariableDeclarationStatement("System.Int32", "i", new CodePrimitiveExpression(0)),
1273 new CodeBinaryOperatorExpression(
1274 new CodeFieldReferenceExpression(null, "i"),
1275 CodeBinaryOperatorType.LessThan,
1276 new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(null, "fileArray"), "Length - 1")
1277 ),
1278 new CodeAssignStatement(
1279 new CodeFieldReferenceExpression(null, "i"),
1280 new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(null, "i"),
1281 CodeBinaryOperatorType.Add,
1282 new CodePrimitiveExpression(1))
1283 ),
1284 new CodeStatement[]
1285 {
1286 new CodeAssignStatement(cLeft, cRight),
1287 new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "test.StartTest"))
1288 }
1289 );
1290 entryCM.Statements.Add(loop);
1291 eco.Members.Add(entryCM);
1292
1293 }
1294
1295
1296 private void TaoThongSoDoiTuong(ref int i, ParameterInfo p)
1297 {
1298 if (chckManualStub.Checked)
1299 {
1300 Excel.Range stubRang = xSheet.get_Range(TestUtility.ConvCHAR(p.Position + 3) + i, TestUtility.ConvCHAR(p.Position + 3) + i);
1301 string[] stubType = stubRang.Comment.Text("", 1, 0).Split(' ');
1302 OBJStub(stubType[0], p.Name, i);
1303
1304 if (stubForm.txtDllToStub.Text.Length > 0)//added for integration
1305 {
1306 stubForm.MakeNewObjOfStub(stubForm.txtDllToStub.Text, i, p);
1307 }
1308 if (stubForm.m_RealObject != "" || stubForm.m_RealObject != null)
1309 {
1310 cm.Statements.Add(new CodeSnippetStatement(stubForm.m_RealObject));// CodeMethodInvokeExpression(pState, stubForm.txtConstructor.Text));
1311 stubForm.m_RealObject = "";
1312 stubForm.txtDllToStub.Text = "";
1313 }
1314
1315 if (stubForm.txtConstructor.Text.Trim() != "")
1316 {
1317 cm.Statements.Add(new CodeSnippetStatement(stubForm.txtConstructor.Text));// CodeMethodInvokeExpression(pState, stubForm.txtConstructor.Text));
1318 }
1319 if (stubForm.txtMethod.Text.Trim() != "")
1320 {
1321 cm.Statements.Add(new CodeSnippetStatement(stubForm.txtMethod.Text));// CodeMethodInvokeExpression(pState, stubForm.txtConstructor.Text));
1322 }
1323 }
1324 else
1325 {
1326 cRight = new CodeFieldReferenceExpression(null, "new " + p.ParameterType.ToString() + "()");
1327 }
1328
1329 }
1330
1331 private StubForm stubForm = new StubForm();
1332 private void OBJStub(string typeStr, string pName, int i)
1333 {
1334 ThucHienBangTay(typeStr);
1335
1336 string PathStr = null;
1337
1338 ChuyenDenFileKiemThu(out PathStr, typeStr);
1339
1340 try
1341 {
1342 Assembly asm = Assembly.LoadFrom(PathStr);
1343 Type type = asm.GetType(typeStr);// + "." + nameSPStr[nameSPStr.Length-1]);
1344 string list1Str = "";
1345 ConstructorInfo[] cis = type.GetConstructors();
1346 foreach (ConstructorInfo ci in cis)
1347 {
1348 list1Str += type.Name + "(";
1349 ParameterInfo[] ps = ci.GetParameters();
1350 foreach (ParameterInfo p in ps)
1351 {
1352 list1Str += p.ParameterType + " " + p.Name + ", ";
1353 }
1354 if (list1Str.IndexOf(",") > 0)
1355 {
1356 list1Str += "Xtra";
1357 list1Str = list1Str.Replace(", Xtra", ")");
1358 }
1359 if (list1Str.EndsWith("("))
1360 list1Str += ")";
1361 list1Str = type.Name.ToString() + " " + pName + "_" + i + " = new " + list1Str + ";";
1362 stubForm.lstConstructors.Items.Add(list1Str);
1363 list1Str = "";
1364 }
1365 MethodInfo[] mis = type.GetMethods();
1366 foreach (MethodInfo mi in mis)
1367 {
1368 list1Str += mi.Name + "(";
1369 ParameterInfo[] ps = mi.GetParameters();
1370 foreach (ParameterInfo p in ps)
1371 {
1372 list1Str += p.ParameterType + " " + p.Name + ", ";
1373 }
1374 if (list1Str.EndsWith(", "))
1375 {
1376 list1Str += "Xtra";
1377 list1Str = list1Str.Replace(", Xtra", ")");
1378 }
1379 if (list1Str.Trim().EndsWith("("))
1380 list1Str += ")";
1381 if (list1Str.Trim().StartsWith("set_"))
1382 {
1383 list1Str = list1Str.Replace("set_", "");
1384 list1Str = list1Str.Replace("(", " = ");
1385 list1Str = list1Str.Replace(")", "");
1386 }
1387 list1Str = pName + "_" + i + "." + list1Str + ";";
1388 stubForm.lstMethods.Items.Add(list1Str);
1389 list1Str = "";
1390 }
1391 stubForm.ShowDialog(this);
1392 }
1393 catch
1394 {
1395 stubForm.txtDllToStub.Text = PathStr;
1396
1397 if (!stubForm.TestClassFound)
1398 {
1399 stubForm.txtDllToStub.Text = "";
1400 MessageBox.Show("The assembly you selected is neither a test script object nor an already referenced instance. Pleae click OK to write C# code in the right text areas to make the Automated Software Test generate a precise test project.\n\nOr, if you are not sure, please restart the Automated Software Test. Make sure the Manual Stub checkbox is not checked before you create script.", "Wrong Stub Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
1401 stubForm.ShowDialog();
1402 }
1403 stubForm.TestClassFound = false;
1404 }
1405 }
1406
1407 private void ThucHienBangTay(string typeStr)
1408 {
1409 stubForm.Text = typeStr + " Stub";
1410 stubForm.txtConstructor.Text = "";
1411 stubForm.txtMethod.Text = "";
1412 stubForm.lstConstructors.Items.Clear();
1413 stubForm.lstMethods.Items.Clear();
1414 stubForm.ControlBox = false;
1415 }
1416 private void ChuyenDenFileKiemThu(out string PathStr, string typeStr)
1417 {
1418 PathStr = null;
1419 openFileDialog1.Title = "Locate the " + typeStr;
1420 openFileDialog1.Filter = "DLL Files(*.dll)|*.dll|All Files|*.*";
1421 if (openFileDialog1.ShowDialog() == DialogResult.OK)
1422 PathStr = openFileDialog1.FileName;
1423 }
1424 private void AddStubDecision(Excel.Range rng)
1425 {
1426 if (!(rng.Value2.ToString() == "new" && chckManualStub.Checked))
1427 {
1428 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1429 }
1430 }
1431
1432 private void CreateTestPassMethod(CodeMemberMethod cm, string MethodName)
1433 {
1434 cm = new CodeMemberMethod();
1435
1436 CodeExpression[] pCode = null;
1437 CodeFieldReferenceExpression cLeft = null;
1438 CodeFieldReferenceExpression cRight = null;
1439
1440 cm.Name = MethodName;//"TestPass";
1441 cm.ReturnType = new CodeTypeReference(typeof(void));
1442
1443 cm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1444 cm.Parameters.Add(new CodeParameterDeclarationExpression("Excel.Worksheet", "xResult"));
1445 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.Int32", "shtRow"));
1446 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "mName"));
1447
1448 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Range), "range"));
1449
1450 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 1, mName") };
1451 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1452
1453 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 2, \"PASS\"") };
1454 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1455
1456 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 3, \"NO ERROR\"") };
1457 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1458
1459 cLeft = new CodeFieldReferenceExpression(null, "range");
1460 cRight = new CodeFieldReferenceExpression(null, "xResult.get_Range(\"B\" + shtRow, \"B\" + shtRow)");
1461 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1462
1463 cLeft = new CodeFieldReferenceExpression(null, "range.Interior.ColorIndex");
1464 cRight = new CodeFieldReferenceExpression(null, "10");
1465 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1466 co.Members.Add(cm);
1467 }
1468 private void CreateTestFailMethod(CodeMemberMethod cm, string MethodName)
1469 {
1470 CodeExpression[] pCode = null;
1471 CodeFieldReferenceExpression cLeft = null;
1472 CodeFieldReferenceExpression cRight = null;
1473 cm = new CodeMemberMethod();
1474
1475 cm.Name = MethodName;//"TestFail";
1476 cm.ReturnType = new CodeTypeReference(typeof(void));
1477 cm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1478 cm.Parameters.Add(new CodeParameterDeclarationExpression("Excel.Worksheet", "xResult"));
1479 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.Int32", "shtRow"));
1480 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "mName"));
1481 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "errMsg"));
1482
1483 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Excel.Range), "range"));
1484
1485 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 1, mName") };
1486 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1487
1488 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 2, \"FAIL\"") };
1489 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1490
1491 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "shtRow, 3, errMsg") };
1492 cm.Statements.Add(new CodeMethodInvokeExpression(null, "xResult.Cells.set_Item", pCode));
1493
1494 cLeft = new CodeFieldReferenceExpression(null, "range");
1495 cRight = new CodeFieldReferenceExpression(null, "xResult.get_Range(\"B\" + shtRow, \"B\" + shtRow)");
1496 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1497
1498 cLeft = new CodeFieldReferenceExpression(null, "range.Interior.ColorIndex");
1499 cRight = new CodeFieldReferenceExpression(null, "3");
1500 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1501 co.Members.Add(cm);
1502 }
1503
1504
1505 string dirName;
1506 string AssemblyNameUT;
1507 string testResultStr;
1508 string TestScriptCSFilename;
1509 string CSProjFilename;
1510 string AsmInfoFilename;
1511 string AppIconFilename;
1512 private void InitConstStrings()
1513 {
1514 try
1515 {
1516 dirName = openFileDialog1.FileName;
1517 dirName = dirName.Replace("\\", "/");
1518 string[] DirName = dirName.Split('/');
1519 dirName = DirName[DirName.Length - 1];
1520 dirName = dirName.Replace(".dll", "");
1521 }
1522 catch (Exception err)
1523 {
1524 MessageBox.Show("Select a DLL file\n" + err.Message, "XOA Software Tester");
1525 }
1526
1527 if (txtTargetProj.Text == "textBox8")
1528 {
1529 txtTargetProj.Text = "C:/Temp";//textbox8text=tempTestProjDir
1530 }
1531 tempTestProjDir = txtTargetProj.Text.Replace("\\", "/");
1532
1533 AssemblyNameUT = openFileDialog1.FileName; //textbox1
1534 xlsDataStoreFilename = tempTestProjDir + "/" + dirName + "/Bin/Debug/test" + dirName + "Data.xls"; //textbox2
1535 testResultStr = tempTestProjDir + "/" + dirName + "/TestResult.xls";//textbox3
1536 //TestScriptCSFilename = tempTestProjDir + "/" + dirName + "/test" + dirName + ".cs";//textbox4
1537 TestScriptCSFilename = tempTestProjDir + "/" + dirName + "/OATLS1TESTRep.cs";
1538 CSProjFilename = tempTestProjDir + "/" + dirName + "/Test" + dirName + ".csproj";//textbox5
1539 AsmInfoFilename = tempTestProjDir + "/" + dirName + "/AssemblyInfo.cs";//textbox6
1540 AppIconFilename = tempTestProjDir + "/" + dirName + "/App.ico";//textbox7
1541 if (txtCurrDir.Text == "Current Directory") //textbox10
1542 txtCurrDir.Text = txtTargetProj.Text;
1543 XlsReportFilename = txtCurrDir.Text.Replace("\\", "/");
1544 }
1545 private void TaoThuMucKiemThu()
1546 {
1547 DirectoryInfo dir = new DirectoryInfo(tempTestProjDir);
1548 try
1549 {
1550 if (dirName != null)
1551 dir.CreateSubdirectory(dirName);
1552 }
1553 catch (IOException err) { MessageBox.Show(err.Message); }
1554 dir = new DirectoryInfo(tempTestProjDir + "/" + dirName);
1555 try
1556 {
1557 dir.CreateSubdirectory("Bin");
1558 }
1559 catch (IOException err) { MessageBox.Show(err.Message); }
1560 dir = new DirectoryInfo(tempTestProjDir + "/" + dirName + "/Bin");
1561 try
1562 {
1563 dir.CreateSubdirectory("Debug");
1564 }
1565 catch (IOException err) { MessageBox.Show(err.Message); }
1566 }
1567
1568 private void TaoNguonThuThapDuLieu(string Content)
1569 {
1570 FileInfo f = new FileInfo(System.IO.Path.Combine(tempTestProjDir + "/" + dirName + "/Bin/Debug", "fileArray.txt"));
1571 StreamWriter sw = f.CreateText();
1572 sw.Write(Content);
1573 sw.Close();
1574 }
1575
1576 string rootDir = Environment.CurrentDirectory;
1577 private void ThaoTacCopyFile(string LoaiFile)
1578 {
1579 FileInfo f = null;
1580 if (LoaiFile == "ico")
1581 {
1582 f = new FileInfo(rootDir + "/testApp.ico");
1583 try
1584 {
1585 FileInfo AppF = f.CopyTo(AppIconFilename, true);
1586 }
1587 catch (Exception err) { MessageBox.Show(err.Message); }
1588 }
1589 else
1590 {
1591 f = new FileInfo(rootDir + "/TestAssemblyInfo.cs");
1592 try
1593 {
1594 FileInfo AppF = f.CopyTo(AsmInfoFilename, true);
1595 }
1596 catch (Exception err) { MessageBox.Show(err.Message); }
1597 }
1598 }
1599
1600 //add references tự động
1601 //public bool AddReference(EnvDTE.Project project, string reference)
1602 //{
1603 // VSProject proj = m_Project.Object as VSProject;
1604 // System.Diagnostics.Debug.Assert(proj != null); // This project is not a VSProject
1605 // if (proj == null)
1606 // return false;
1607 // try
1608 // {
1609 // proj.References.Add(reference);
1610 // }
1611 // catch (Exception ex)
1612 // {
1613 // string message = String.Format("Could not add {0}. \n Exception: {1}", reference, ex.Message);
1614 // System.Diagnostics.Trace.WriteLine(message);
1615 // return false;
1616 // }
1617
1618 // return true;
1619 //}
1620
1621
1622 private void Copytatca(string sourceDir, string targetDir)
1623 {
1624 foreach(var file in Directory.GetFiles(sourceDir))
1625
1626 File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
1627
1628 foreach(var directory in Directory.GetDirectories(sourceDir))
1629 Copytatca(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
1630 }
1631
1632 private void DocFileCSPROJ(string clsName, Assembly asm)
1633 {
1634 StreamReader sr = File.OpenText(rootDir + "/OATestProj.csproj");
1635 string input = null;
1636 string output = null;
1637 string refStr = "";
1638 string relPath = TestScriptCSFilename;//textBox4.Text;
1639 string[] RelPath = relPath.Split('/');
1640 relPath = RelPath[RelPath.Length - 1];
1641
1642
1643 //dirName = dirName.Replace("\\", "/");
1644 // string[] DirName = dirName.Split('/');
1645 // dirName = DirName[DirName.Length - 1];
1646 // dirName = dirName.Replace(".dll", "");
1647
1648
1649 //string filedll=tempTestProjDir+"/"+dirName+"/Bin/Debug"+dirName+".dll";
1650
1651
1652
1653 while (null != (input = sr.ReadLine()))
1654 {
1655 //input = sr.ReadLine();
1656 if (input.IndexOf("OATLStest") > 0)
1657 {
1658 input = input.Replace("OATLStest", clsName);
1659 }
1660 if (input.IndexOf("</References>") > 0)
1661 {
1662 AssemblyName[] asmRefs = asm.GetReferencedAssemblies();
1663
1664 foreach (AssemblyName aRef in asmRefs)
1665 {
1666 if (aRef.FullName.IndexOf("mscorlib") < 0)
1667 {
1668 refStr = refStr + "<Reference\n";
1669 refStr = refStr + "Name = \"" + aRef.Name + "\"\n";
1670 refStr = refStr + "AssemblyName = \"" + aRef.Name + "\"\n";
1671 refStr = refStr + "HintPath = \"" + aRef.CodeBase + "\"\n" + "/>\n";
1672 }
1673 }
1674 refStr = refStr + "<Reference\n" +
1675 "Name = \"" + asm.FullName.Substring(0, asm.FullName.IndexOf(", ")) + "\"\n" +
1676 "AssemblyName = \"" + asm.FullName.Substring(0, asm.FullName.IndexOf(", ")) + "\"\n" +
1677 "HintPath = \"" + asm.CodeBase + "\"\n" +
1678 "/>\n";
1679
1680
1681 refStr = refStr + "<Reference\n" +
1682 "Name = \"" + dirName + "\"\n" +
1683 "AssemblyName = \"" + dirName + "\"\n" +
1684 "HintPath = \"" + tempTestProjDir + "/" + dirName + "/Bin/Debug" + dirName + ".dll" + "\"\n" +
1685 "/>\n";
1686
1687 if (stubForm.m_CreateReference != "") //added for integration
1688 {
1689 refStr += stubForm.m_CreateReference;
1690 stubForm.m_CreateReference = "";
1691 }
1692
1693 refStr = refStr.Replace("file:///", "");
1694 refStr = refStr.Replace("/", "\\");
1695 input = refStr + input + "\n";
1696 }
1697
1698 if (input.IndexOf("RelPath = \"OATLS1TESTRep.cs\"") > 0)
1699 {
1700 input = input.Replace("OATLS1TESTRep.cs", relPath);
1701 }
1702 output = output + input + "\n";
1703 }
1704 FileInfo f = new FileInfo(CSProjFilename);
1705 StreamWriter write = f.CreateText();
1706 write.Write(output);
1707 write.Close();
1708 sr.Close();
1709 }
1710
1711 private void BatDauDOTNETIDE(string fileName, string args)
1712 {
1713 try
1714 {
1715 Process shell = new Process();
1716 shell.StartInfo.FileName = fileName;
1717 shell.StartInfo.Arguments = args;
1718 shell.Start();
1719 }
1720 catch (Exception er)
1721 { MessageBox.Show(er.Message); }
1722 }
1723
1724 private void TestForm_Load(object sender, EventArgs e)
1725 {
1726 try
1727 {
1728 string DevenvPath = Environment.ExpandEnvironmentVariables(
1729 @"%VSCOMNTOOLS%devenv.exe").Replace(@"Tools", "IDE").Replace("\"", "");
1730
1731 if (!File.Exists(DevenvPath)) //dùng cho visual studio 2008
1732 {
1733 DevenvPath = Environment.ExpandEnvironmentVariables(
1734 @"%VS90COMNTOOLS%devenv.exe").Replace(@"Tools", "IDE");
1735 }
1736
1737 txtDotNETLocation.Text = DevenvPath;
1738 }
1739 catch
1740 {
1741 }
1742
1743 btnStart.Focus();
1744
1745
1746 }
1747
1748 private void btnStart_Click(object sender, EventArgs e)
1749 {
1750 //mở file dll hoặc file exe.
1751 GetAssemblyName();
1752 //tạo các thư mục để chứa các file .cs, .csproj..trong ổ C
1753 InitConstStrings();
1754 //Tạo thư mục kiểm thử
1755 TaoThuMucKiemThu();
1756 //
1757 GetTypesOfAssemblyUnderTest();
1758 //khởi tạo phương thức kiểm thử
1759 Khoitaophuongthuckiemthu();
1760
1761 if (chckXMLDataDoc.Checked)
1762 {
1763 ThaoTacDulieuXML();
1764 btnCreateScript_Click(sender, e);
1765 }
1766
1767 //btnCreateScript.Focus();
1768 }
1769
1770 private void btnCreateScript_Click(object sender, EventArgs e)
1771 {
1772 btnStart.Focus();
1773 if (dirName == null || xApp == null)
1774 {
1775 MessageBox.Show("Click the Start button to collect test information first.");
1776 return;
1777 }
1778 //Create a TextWriter object to save the script
1779 TextWriter t = null;
1780
1781 t = new StreamWriter(new FileStream(TestScriptCSFilename, FileMode.Create));
1782 //start generating script
1783 try
1784 {
1785 TaoMaKiemThu(DUTAsm, t);
1786 }
1787 catch (Exception err)
1788 { MessageBox.Show(err.Message); }
1789 finally
1790 {
1791 t.Close();
1792 }
1793
1794 DongExcelSheet();
1795 ThaoTacCopyFile("ico");
1796 ThaoTacCopyFile("cs");
1797 TaoNguonThuThapDuLieu(xlsDataStoreFilename);
1798 txtDataStore.Text = xlsDataStoreFilename;
1799 BatDauDOTNETIDE(txtDotNETLocation.Text, CSProjFilename);
1800 coppyfile();
1801 //coppydll();
1802 string nguon = @"D:/thao" + "/" + dirName + "/" + dirName + "/Bin/Debug";
1803 string targetPath = tempTestProjDir + "/" + dirName + "/Bin/Debug";
1804 //tatcafilecopy(nguon, targetPath);
1805 Copytatca(nguon, targetPath);
1806 }
1807
1808
1809
1810 private void coppyfile()
1811 {
1812 string fileName = "Interop.Microsoft.Office.Interop.Excel.dll";
1813 string sourcePath = @"D:\thao\de tai\AutomatedTest\AutomatedTest\bin\Debug";
1814 string targetPath = tempTestProjDir + "/" + dirName + "/Bin/Debug";
1815
1816 string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
1817 string destFile = System.IO.Path.Combine(targetPath, fileName);
1818 File.Copy(sourceFile, destFile);
1819 }
1820
1821
1822
1823 //thao tac regedit
1824 bool NeedWinReg;
1825 private void MakeIfStatementForAccessRegKey(CodeMemberMethod cm, string strCondition, string strLeft, string strRight)
1826 {
1827 CodeFieldReferenceExpression cLeft = null;
1828 CodeFieldReferenceExpression cRight = null;
1829 cLeft = new CodeFieldReferenceExpression(null, strLeft);
1830 cRight = new CodeFieldReferenceExpression(null, strRight);
1831 CodeConditionStatement ifState = new CodeConditionStatement(new CodeSnippetExpression(strCondition), new CodeAssignStatement(cLeft, cRight));
1832 cm.Statements.Add(ifState);
1833 }
1834
1835 private void CreateAccessRegKeyMethod(CodeMemberMethod cm, string MethodName)
1836 {
1837 cm = new CodeMemberMethod();
1838
1839 cm.Name = MethodName;
1840 cm.ReturnType = new CodeTypeReference(typeof(void));
1841 cm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1842
1843 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "locHive"));
1844 cm.Parameters.Add(new CodeParameterDeclarationExpression("ref RegistryKey", "key"));
1845
1846
1847 CodeFieldReferenceExpression cLeft = null;
1848 CodeFieldReferenceExpression cRight = null;
1849
1850 cLeft = new CodeFieldReferenceExpression(null, "locHive");
1851 cRight = new CodeFieldReferenceExpression(null, "locHive.Trim()");
1852 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1853
1854 MakeIfStatementForAccessRegKey(cm, "locHive == \"HKEY_CURRENT_CONFIG\"", "key", "Registry.CurrentConfig");
1855 MakeIfStatementForAccessRegKey(cm, "locHive == \"HKEY_LOCAL_MACHINE\"", "key", "Registry.LocalMachine");
1856 MakeIfStatementForAccessRegKey(cm, "locHive == \"HKEY_CURRENT_USER\"", "key", "Registry.CurrentUser");
1857 MakeIfStatementForAccessRegKey(cm, "locHive == \"HKEY_CLASSES_ROOT\"", "key", "Registry.ClassesRoot");
1858 MakeIfStatementForAccessRegKey(cm, "locHive == \"HKEY_USERS\"", "key", "Registry.Users");
1859
1860 co.Members.Add(cm);
1861 }
1862
1863 private void CreateGetWinRegValueMethod(CodeMemberMethod cm, string MethodName)
1864 {
1865 cm = new CodeMemberMethod();
1866
1867 cm.Name = MethodName;
1868 cm.ReturnType = new CodeTypeReference(typeof(object));
1869 cm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1870
1871 cm.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "WinRegKey"));
1872
1873 CodeFieldReferenceExpression cLeft = null;
1874 CodeFieldReferenceExpression cRight = null;
1875
1876 cLeft = new CodeFieldReferenceExpression(null, "WinRegKey");
1877 cRight = new CodeFieldReferenceExpression(null, "WinRegKey.ToUpper().Replace(\"WINREG:\", \"\")");
1878 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1879
1880 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(Microsoft.Win32.RegistryKey), "key = null"));
1881
1882 cm.Statements.Add(new CodeParameterDeclarationExpression(typeof(object), "WinRegVal = \"\""));
1883
1884 cLeft = new CodeFieldReferenceExpression(null, "string[] HiveSubs");
1885 cRight = new CodeFieldReferenceExpression(null, "WinRegKey.Split('\\\\')");
1886 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1887
1888 cLeft = new CodeFieldReferenceExpression(null, "WinRegKey");
1889 cRight = new CodeFieldReferenceExpression(null, "WinRegKey.Replace(HiveSubs[0]+@\"\\\", \"\").Replace(@\"\\\"+HiveSubs[HiveSubs.Length-1], \"\")");
1890 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1891
1892
1893 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, "HiveSubs[0], ref key") };
1894 cm.Statements.Add(new CodeMethodInvokeExpression(null, "AccessRegKey", pCode));
1895
1896 cLeft = new CodeFieldReferenceExpression(null, "key");
1897 cRight = new CodeFieldReferenceExpression(null, "key.OpenSubKey(WinRegKey)");
1898 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1899
1900
1901 cLeft = new CodeFieldReferenceExpression(null, "WinRegVal");
1902 cRight = new CodeFieldReferenceExpression(null, "key.GetValue(HiveSubs[HiveSubs.Length-1])");
1903 cm.Statements.Add(new CodeAssignStatement(cLeft, cRight));
1904
1905
1906 pCode = new CodeExpression[] { new CodeFieldReferenceExpression(null, null) };
1907 cm.Statements.Add(new CodeMethodInvokeExpression(null, "key.Close", pCode));
1908
1909
1910 cm.Statements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("WinRegVal")));
1911 co.Members.Add(cm);
1912 }
1913
1914
1915
1916
1917
1918
1919 private void btnExit_Click_1(object sender, EventArgs e)
1920 {
1921 Application.Exit();
1922 }
1923
1924 private void btnAddDataStore_Click(object sender, EventArgs e)
1925 {
1926 if (dirName == null)
1927 {
1928 MessageBox.Show("Please click Start button, then Create Script button to generate a test script first.");
1929 return;
1930 }
1931 openFileDialog1.Title = "Add more data store";
1932 openFileDialog1.Filter = "Excel Files (*.xls)|*.xls";
1933 openFileDialog1.Multiselect = true;
1934 if (openFileDialog1.ShowDialog() == DialogResult.OK)
1935 {
1936 foreach (string fn in openFileDialog1.FileNames)
1937 {
1938 txtDataStore.Text += "\n" + fn;
1939 }
1940 }
1941 }
1942
1943 private void btnSaveDataStore_Click(object sender, EventArgs e)
1944 {
1945 if (txtDataStore.Text.Trim() == "")
1946 return;
1947 TaoNguonThuThapDuLieu(txtDataStore.Text);
1948 }
1949 }
1950 }