welcome to Qijie's Blog 薛其杰

Key words: Verify default path , EULA, CodeSign of SFX file

Key words: Extract SFX files and Submit them to VCS

Key words: Asynchronous callback of delegation

 

I meet an issue when taking my job, everyday i had to spend a lot of time on checking SFX files' default path, EULA and code sign, so i write a tool, this tool can get all the SFX files under give folder,then it get the comment of each SFX file,then analyze the default path , copy right year in EULA, and use check trust to verify wether SFX is code signed. Another thing, I also used asynchronic callback of delegate, by using this, it can response to user's action even when it running the big job.

 

Form1:

 

代码
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Collections;
  4 using System.ComponentModel;
  5 using System.Data;
  6 using System.Drawing;
  7 using System.Linq;
  8 using System.Text;
  9 using System.IO;
 10 using System.Text.RegularExpressions;
 11 using System.Windows.Forms;
 12 using System.Diagnostics;
 13 using System.Threading;
 14 using System.Timers;
 15 
 16 namespace CloudCDTool
 17 {
 18     public partial class CloudCDTool1 : Form
 19     {
 20         #region delegate
 21         public delegate bool del_ExtraxctAllfiles(string filename,out string buildPath);
 22         public delegate void del_SubmitToVCS(string build);
 23         public delegate void del_Elapse();
 24         public delegate void delegate_RunCase(string buildFolder, string defaulpath, string copyyear);
 25         public delegate void delegate_SetProgressMaxmum(int totalCount);
 26         public delegate void delegate_UpdateProgressValue();
 27         #endregion
 28 
 29         #region Field
 30         ArrayList exeLists = null;
 31         System.Timers.Timer etimer = null;
 32         string statusinfo = "Status";
 33         #endregion
 34 
 35         public CloudCDTool1()
 36         {
 37             InitializeComponent();
 38             exeLists = new ArrayList();
 39             etimer = new System.Timers.Timer();
 40             etimer.Elapsed += new ElapsedEventHandler(etimer_Elapsed);
 41             etimer.Interval = 1000;
 42             etimer.Start();
 43         }
 44 
 45         void etimer_Elapsed(object sender, ElapsedEventArgs e)
 46         {
 47             del_Elapse del = new del_Elapse(elaps_StatusBox);
 48             Invoke(del, new object[] { });
 49         }
 50 
 51         void elaps_StatusBox()
 52         {
 53             StatusLabel.Text = statusinfo;
 54         }
 55        
 56         private void Test_Click(object sender, EventArgs e)
 57         {
 58             string filename = @"D:\AutoTool\VAN-EX1.exe";// @"\\mslt-10\baseimages\ENU\Split\Base10C-W7-HV\Base10C-W7-HV.part01.exe";
 59             HelpRAR rarClass = new HelpRAR();
 60             bool pathPath = PathMatch(filename,"");
 61             bool eulaMath = EULAMath(filename,"");
 62         }
 63         //Test if default path match with expected one
 64         private bool PathMatch(string filename,string expectdPath)
 65         {
 66             bool pass = true;
 67             string actualPath = string.Empty;
 68             HelpRAR rarClass = new HelpRAR();
 69             string rarInfo = rarClass.rarInfo(filename);
 70             int path = rarInfo.IndexOf(@"Path=");
 71             if (path == -1)
 72             {
 73                 //No DefaultPath
 74                 pass = false;
 75                 return pass;
 76             }
 77             else
 78             {
 79                 string pattern = @"\w\:\\[\w\\\d ]+"//match c:\program files\microsoft learning\base
 80                 MatchCollection MC = Regex.Matches(rarInfo, pattern);
 81                 if (MC.Count > 0)
 82                 {
 83                     actualPath = MC[0].Value.ToString();
 84                     string expectedPath = expectdPath;
 85                     if (expectedPath.ToLower() != actualPath.ToLower())
 86                     {
 87                         pass = false;
 88                     }
 89                     return pass;
 90                 }
 91                 else //No Default Path
 92                 {
 93                     pass = false;
 94                     return pass;
 95                 }
 96             }
 97         }
 98         //Test if SFX contains EULA? EULA exists, then verify copyright year is correct?
 99         private bool EULAMath(string filename, string expectedCopyYear)
100         {
101             bool pass = true;
102             HelpRAR rarClass = new HelpRAR();
103             string rarInfo = rarClass.rarInfo(filename);
104             int eula = rarInfo.IndexOf(@"License=");
105             if (eula == -1)
106             {
107                 //No EULA
108                 pass = false;
109                 return pass;
110             }
111             else
112             {
113                 string EULA = rarInfo.Substring(rarInfo.IndexOf(@"License="), rarInfo.Length - rarInfo.IndexOf(@"License="));
114                 string copryrightYear = expectedCopyYear;
115                 if (!EULA.Contains(copryrightYear))
116                 {
117                     pass = false;
118                 }
119                 return pass;
120             }
121         }
122 
123         private void tb_CourseNumber_Leave(object sender, EventArgs e)
124         {
125             string enterString = tb_CourseNumber.Text.Trim();
126             string course = Regex.Replace(enterString, @"[^\d]""");
127             tb_DefaultPath.Text = string.Format(@"C:\Program Files\Microsoft Learning\{0}", course);
128         }
129 
130         private void Asyn_Check_Click(string buildFolder, string defaulpath, string copyyear)
131         {
132             if (buildFolder == "")
133             {
134                 return;
135             }
136             DirectoryInfo di = new DirectoryInfo(buildFolder);
137             string result = @"C:\CloudCDHelp\testResult.xls";
138             if (File.Exists(result))
139             {
140                 try
141                 {
142                     File.Delete(result);
143                 }
144                 catch { }
145             }
146             FileStream fStream = new FileStream(result, FileMode.OpenOrCreate, FileAccess.Write);
147 
148             StreamWriter sw = new StreamWriter(fStream, Encoding.Unicode);
149             StringBuilder line = new StringBuilder();
150             line.Append("SFX file" + Convert.ToChar(9));
151             line.Append("TC #Default Path" + Convert.ToChar(9));
152             line.Append("TC #EULA" + Convert.ToChar(9));
153             line.Append("TC #CodeSign" + Convert.ToChar(9));
154 
155             sw.WriteLine(line);
156             ArrayList al = new ArrayList();
157             al = Scan_Directory(di);
158             if (al.Count > 0)
159             {
160                 delegate_SetProgressMaxmum delegate_ProgressMax = new delegate_SetProgressMaxmum(Set_ProgressMax);
161                 Invoke(delegate_ProgressMax, new object[] { al.Count });               
162                 
163             }
164             foreach (var item in al)
165             {
166                 ExcuteTestCase(item.ToString(), sw, defaulpath, copyyear);
167                 try
168                 {
169                     delegate_UpdateProgressValue delegate_updateValue = new delegate_UpdateProgressValue(update_ProgressValue);
170                     Invoke(delegate_updateValue, new object[] { });                    
171                 }
172                 catch { }
173             }
174             statusinfo = "Writing results to theResult.xls...";
175             exeLists.Clear();
176             sw.Dispose();
177             sw.Close();
178             statusinfo = "Opening theResult.xls...";
179             Process.Start(result);
180             statusinfo = "theResult.xls was Opened";
181         }
182         private void update_ProgressValue()
183         {
184             progressBar1.Value += 1;
185         }
186         private void Set_ProgressMax(int totalCount)
187         {
188             progressBar1.Maximum = totalCount;
189             progressBar1.Value = 0;
190         }
191 
192         private void check_Result(IAsyncResult ar)
193         {
194             delegate_RunCase del_run = (delegate_RunCase)ar.AsyncState;
195             del_run.EndInvoke(ar);
196         }
197         private void bt_Check_Click(object sender, EventArgs e)
198         {
199             string buildFolder = tb_Folder.Text.Trim();
200             if (!Directory.Exists(buildFolder))
201             {
202                 MessageBox.Show("!Dirctory not exist""Err", MessageBoxButtons.OK, MessageBoxIcon.Error);
203                 return;
204             }
205             statusinfo = "Begining jobs...";
206             string defaulpath = tb_DefaultPath.Text.Trim();
207             string copyyear=tb_CopyrightYear .Text .Trim ();
208             delegate_RunCase del_Runcase = new delegate_RunCase(Asyn_Check_Click);
209             del_Runcase.BeginInvoke(buildFolder, defaulpath, copyyear, new AsyncCallback(check_Result), del_Runcase);
210             //buildfolder, defaultpath, copyyear
211             progressBar1.Value = 0;
212         }
213 
214         private ArrayList Scan_Directory(DirectoryInfo di)
215         {
216             statusinfo = "Scanning files.....";
217             try
218             {
219                 foreach (FileSystemInfo item in di.GetFileSystemInfos())
220                 {
221                     if (item is DirectoryInfo)
222                     {
223                         DirectoryInfo tmpDI = item as DirectoryInfo;
224                         Scan_Directory(tmpDI);
225                     }
226                     else
227                     {
228                         FileInfo fi = item as FileInfo;
229                         FileAttributes fileAttr = File.GetAttributes(fi.FullName);
230                         if ((fileAttr & FileAttributes.System) == FileAttributes.System)
231                         {
232                             continue;
233                         }
234                         else
235                         {
236                             Regex reg = new Regex(@".exe$");
237                             bool match = reg.IsMatch(fi.FullName.ToString());
238                             if (match)
239                             {
240                                 exeLists.Add(fi.FullName.ToString());
241                                 statusinfo = string.Format(@"Find file '{0}'", fi.FullName.ToString());                                
242                             }
243                         }
244                     }
245                 }
246             }
247             catch { }
248             return exeLists;
249         }
250         private void ExcuteTestCase(string filename, StreamWriter sw, string expectedpath, string expectedCopyyear)
251         {
252             StringBuilder line = new StringBuilder();
253             line.Append(filename + Convert.ToChar(9));
254             statusinfo = string.Format(@"Checking path for {0}", filename);           
255             bool pathPass = PathMatch(filename,expectedpath );
256             statusinfo = string.Format(@"Checking EULA for {0}", filename);
257             bool eulaPass = EULAMath(filename,expectedCopyyear );
258             statusinfo = string.Format(@"Checking Codesign for {0}", filename);
259             bool codeSign = (new CheckTrust()).isCodeSign(filename);
260             if (pathPass)
261             {
262                 line.Append("Pass" + Convert.ToChar(9));
263             }
264             else
265                 line.Append("Fail" + Convert.ToChar(9));
266             if (eulaPass)
267             {
268                 line.Append("Pass" + Convert.ToChar(9));
269             }
270             else
271                 line.Append("Fail" + Convert.ToChar(9));
272             if (codeSign)
273             {
274                 line.Append("Pass" + Convert.ToChar(9));
275             }
276             else
277             {
278                 line.Append("Fail" + Convert.ToChar(9));
279             }
280             sw.WriteLine(line);
281 
282         }
283 
284         private void Form1_Load(object sender, EventArgs e)
285         {
286             VCSBrowser1.Navigate(@"http://vcs/request.aspx");
287         }
288 
289         private void VCSBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
290         {
291             VCSBrowser1.Document.GetElementById("txt_contact").InnerText = @"v-qixue";
292         }
293 
294         private void bt_Extract_Click(object sender, EventArgs e)
295         {
296             HelpRAR rarhelp = new HelpRAR();           
297             string buildforVCS = "";
298             string folder = tb_Folder.Text.Trim();
299             if (!Directory.Exists(folder))
300             {
301                 MessageBox.Show("!Dirctory not exist""Err", MessageBoxButtons.OK, MessageBoxIcon.Error);
302                 return;
303             }
304             DirectoryInfo di = new DirectoryInfo(folder);
305             ArrayList al = new ArrayList();
306             al = Scan_Directory(di);
307             string allfileName = "";
308             foreach (var item in al)
309             {
310                 if (item.ToString().ToLower().Contains("allfiles.exe"))
311                 {
312                     allfileName = item.ToString();
313                     break;
314                 }
315             }
316             statusinfo = string.Format(@"Extracting {0}", allfileName);
317             del_ExtraxctAllfiles del = new del_ExtraxctAllfiles(rarhelp.rarExtract);
318             IAsyncResult ar = del.BeginInvoke(allfileName, out buildforVCS, new AsyncCallback(returnResult), del);
319             //rarhelp.rarExtract(allfileName, out buildforVCS);
320             VCSBrowser1.Document.GetElementById("txt_description").InnerText = allfileName.ToString();
321             VCSBrowser1.Document.GetElementById("txt_contact").InnerText = tb_VCSemail .Text .Trim ();
322             progressBar1.Value = progressBar1.Maximum / 4;
323         }
324 
325         public void returnResult(IAsyncResult ar)
326         {
327             string buildforVCS = string.Empty;
328             del_ExtraxctAllfiles del = (del_ExtraxctAllfiles)ar.AsyncState;
329             bool success=del.EndInvoke(out buildforVCS, ar);           
330             MessageBox.Show("Extraction Process finished");
331             if (success)
332             {
333                 statusinfo = string.Format(@"Submitting {0} to VCS", buildforVCS);
334 
335                 del_SubmitToVCS d_sub = new del_SubmitToVCS(submitToVCS);
336                 Invoke(d_sub, new object[] { buildforVCS });
337             }
338             else
339                 statusinfo = "No files were extracted";
340         }
341 
342         public void submitToVCS(string build)
343         {
344             VCSBrowser1.Document.GetElementById("txt_path").InnerText = build;
345             VCSBrowser1.Document.GetElementById("btn_submit_asp").InvokeMember("click");
346             statusinfo = string.Format(@"Submited file {0} to VCS", build );
347             progressBar1.Value = progressBar1.Maximum;
348         }
349 
350         private void label5_Click(object sender, EventArgs e)
351         {
352             if (folderBrowserDialog1.ShowDialog() != DialogResult.Cancel)
353             {
354                 tb_Folder.Text = folderBrowserDialog1.SelectedPath.Trim();
355             }
356         }
357 
358         private void bt_VCS_AllFileEXE_Click(object sender, EventArgs e)
359         {
360             string folder = tb_Folder.Text.Trim();
361             DirectoryInfo di = new DirectoryInfo(folder);
362             ArrayList al = new ArrayList();
363             al = Scan_Directory(di);
364             string allfileName = "";
365             foreach (var item in al)
366             {
367                 if (item.ToString().ToLower().Contains("allfiles.exe"))
368                 {
369                     allfileName = item.ToString();
370                     break;
371                 }
372             }
373             VCSBrowser1.Document.GetElementById("txt_description").InnerText = allfileName.ToString();
374             VCSBrowser1.Document.GetElementById("txt_contact").InnerText = tb_VCSemail.Text.Trim();
375         }
376     }
377 }

 

 

HelpRAR:

 

代码
  1 using System;
  2 using System.Net;
  3 using System.Collections.Generic;
  4 using System.IO;
  5 using System.Text;
  6 using System.Text.RegularExpressions;
  7 using System.Diagnostics;
  8 using System.Configuration ;
  9 
 10 namespace CloudCDTool
 11 {
 12     class HelpRAR
 13     {
 14        
 15         public string rar = ConfigurationManager.AppSettings["Rar"].ToString();
 16         public string rarInfo(string filename)
 17         { 
 18             string info = string.Empty;
 19             StringBuilder theResult = new StringBuilder();
 20             ProcessStartInfo P_rar = new ProcessStartInfo(rar );
 21             P_rar.CreateNoWindow = true;
 22             P_rar.RedirectStandardInput = true;
 23             P_rar.RedirectStandardOutput = true;
 24             P_rar.UseShellExecute = false;
 25             P_rar.Arguments = string.Format(" cw \"{0}", filename);
 26 
 27             Process p = Process.Start(P_rar);
 28             StreamReader reader = p.StandardOutput;
 29             string line = reader.ReadLine();
 30             while (!reader.EndOfStream)
 31             {
 32                 theResult.AppendLine(line);
 33                 line = reader.ReadLine();
 34             }
 35             theResult.AppendLine(line);
 36             info = theResult.ToString();
 37             return info;
 38         }
 39 
 40         public string defaulPath(string filename)
 41         {
 42             string results = string.Empty;
 43             string comments = rarInfo(filename);
 44             string pattern = @"\w\:\\[\w\\\d ]+";
 45             MatchCollection mc = Regex.Matches(comments, pattern);
 46             if (mc.Count > 0)
 47             {
 48                 results = mc[0].Value.ToString();
 49             }
 50             return results;
 51         }
 52 
 53         //Share Folder :  net share auto=d:\autotool /grant:everyone,full
 54         public bool rarExtract(string filename,out string buildPath)
 55         {
 56             string info = string.Empty;
 57             string d_path = defaulPath(filename);
 58             bool success = true;
 59             string shareFolder=d_path .Substring (d_path.LastIndexOf (@"\")+1);
 60             string VCSFolder = string.Format(@"c:\VCSFolder\{0}", shareFolder);
 61             if (Directory.Exists(VCSFolder))
 62             {
 63                 try
 64                 {
 65                     Directory.Delete(VCSFolder, true);
 66                 }
 67                 catch { }
 68             }
 69             StringBuilder theResult = new StringBuilder();
 70             ProcessStartInfo P_rar = new ProcessStartInfo(rar);
 71             P_rar.CreateNoWindow = true;
 72             P_rar.RedirectStandardInput = true;
 73             P_rar.RedirectStandardOutput = true;
 74             P_rar.UseShellExecute = false;
 75             P_rar.Arguments = string.Format(" x -ad \"{0}\" \"{1}\\", filename, VCSFolder);
 76 
 77             Process p = Process.Start(P_rar);
 78             StreamReader reader = p.StandardOutput;
 79             string line = reader.ReadLine();
 80             while (!reader.EndOfStream)
 81             {
 82                 theResult.AppendLine(line);
 83                 line = reader.ReadLine();
 84             }
 85             theResult.Append(line);
 86             info = theResult.ToString();
 87             if (info.Contains("All OK"))
 88             {
 89                 ProcessStartInfo P_share = new ProcessStartInfo(@"net.exe");
 90                 P_share.CreateNoWindow = true;
 91                 P_share.RedirectStandardInput = true;
 92                 P_share.RedirectStandardOutput = true;
 93                 P_share.UseShellExecute = false;
 94                 P_share.Arguments = string.Format(" share {0}=\"{1}\" /grant:everyone,full", shareFolder, VCSFolder);
 95                 Process share = Process.Start(P_share);
 96 
 97                 buildPath = string.Format(@"\\{0}\{1}", Dns.GetHostName(), shareFolder);
 98                 success = true;
 99             }
100             else
101             {
102                 buildPath = "";
103                 success = false;
104             }
105 
106             return success;
107             
108         }
109     }
110 }
111 

 

 

CheckTrust:

 

代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Diagnostics;
 6 using System.Configuration ;
 7 
 8 
 9 namespace CloudCDTool
10 {
11     class CheckTrust
12     {
13         string checktrust = ConfigurationManager.AppSettings["CheckTrust"].ToString();
14         public bool isCodeSign(string filename)
15         {
16             bool codesigned = true;
17             ProcessStartInfo P_code = new ProcessStartInfo(checktrust );
18             P_code.CreateNoWindow = true;
19             P_code.RedirectStandardInput = true;
20             P_code.RedirectStandardOutput = true;
21             P_code.UseShellExecute = false;
22             P_code.Arguments = string.Format(" -v -q \"{0}",filename );
23 
24             Process process = new Process();
25             process.StartInfo = P_code;
26             process.Start();
27             string theResult = process.StandardOutput.ReadToEnd();
28             if(theResult .Contains  ("Failed"))
29             {
30                 codesigned = false;
31             }
32             else if (theResult.Contains ("Succeeded"))
33             {
34                 codesigned = true;
35             }
36             else
37             {
38                 codesigned = false;
39             }
40             return codesigned;
41         }
42     }
43 }
44 

 

 

posted on 2010-11-11 15:52  零点零一  阅读(474)  评论(0编辑  收藏  举报