Exemple #1
0
 /// <summary>
 /// Extract [zipFileName] to [destinationPath]
 /// </summary>
 /// <param name="zipFileName"></param>
 /// <param name="destinationPath"></param>
 /// <param name="fileNameToExtract">need to be the relative path in the zip file</param>
 public static void ExtractSingleFile(string zipFileName, string destinationPath, string fileNameToExtract)
 {
     try
     {
         ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
         fz.ExtractZip(zipFileName, destinationPath, fileNameToExtract);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
 private static PluginExtractionResult UnzipPlugin(FileInfo plugin)
 {
     if (plugin.Extension != ".zip") throw new Exception(string.Format("The {0} extention is not recognized as valid plugin repository item extention. Default extention is .zip",plugin.Extension));
     try {
         ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
         zip.ExtractZip(plugin.FullName, Path.Combine(_pluginsDirectory, plugin.Name), string.Empty);
         return new PluginExtractionResult(ExtractionResult.OK, string.Format("Plugin {0} successfully ",plugin.Name));
     }
     catch (Exception ex)
     {
         return new PluginExtractionResult(ExtractionResult.Error, string.Format("Error while extract {0} plugin from archive",plugin.Name), ex);
     }
 }
        private bool UnzipOSA(string PluginPackagePath)
        {
            string exePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            if (Directory.Exists(exePath + "/tempDir/"))
            {
                Directory.Delete(exePath + "/tempDir/", true);
            }

            string tempfolder = exePath + "/tempDir/";
            string zipFileName = System.IO.Path.GetFullPath(PluginPackagePath);
            string DescPath = null;

            ICSharpCode.SharpZipLib.Zip.FastZip fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();

            fastZip.ExtractZip(zipFileName, tempfolder, null);
            // find all included plugin descriptions and install the plugins
            List<string> osapdFiles = new List<string>();
            List<string> sqlFiles = new List<string>();

            string[] pluginFile = Directory.GetFiles(tempfolder, "*.osapd", SearchOption.TopDirectoryOnly);
            osapdFiles.AddRange(pluginFile);
            string[] sqlFile = Directory.GetFiles(tempfolder, "*.sql", SearchOption.TopDirectoryOnly);
            sqlFiles.AddRange(sqlFile);

            if (osapdFiles.Count == 0)
            {
                MessageBox.Show("No plugin description files found.");
                return false;
            }

            if (osapdFiles.Count > 1)
            {
                MessageBox.Show("More than one plugin description file found.");
                return false;
            }
            if (osapdFiles.Count == 1)
            {

                DescPath = osapdFiles[0];
            }


            if (!string.IsNullOrEmpty(DescPath))
            {
                desc.Deserialize(DescPath);
                return true;
            }
            return false;
        }
Exemple #4
0
 static void Main()
 {
     ICSharpCode.SharpZipLib.Zip.FastZip fz=new ICSharpCode.SharpZipLib.Zip.FastZip();
     string direct = AppDomain.CurrentDomain.BaseDirectory + "\\msg";
     string zipFile = AppDomain.CurrentDomain.BaseDirectory+"\\msg\\msg.zip";
     if (System.IO.File.Exists(zipFile)) {
         killmsg();
         try {
             fz.ExtractZip(zipFile, direct, ICSharpCode.SharpZipLib.Zip.FastZip.Overwrite.Always, null, null, null, false);
             if(!zipFile.Contains("output"))
                 System.IO.File.Delete(zipFile);
         } catch { }
     }
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     DevExpress.UserSkins.OfficeSkins.Register();
     DevExpress.UserSkins.BonusSkins.Register();
     DevExpress.Skins.SkinManager.EnableFormSkins();
     DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = "Xmas 2008 Blue";
     //DevExpress.Utils.Localization.AccLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressUtilsLocalizationCHS();
     DevExpress.XtraBars.Localization.BarLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraBarsLocalizationCHS();
     //DevExpress.XtraCharts.Localization.ChartLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraChartsLocalizationCHS();
     DevExpress.XtraEditors.Controls.Localizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraEditorsLocalizationCHS();
     DevExpress.XtraGrid.Localization.GridLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraGridLocalizationCHS();
     DevExpress.XtraLayout.Localization.LayoutLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraLayoutLocalizationCHS();
     DevExpress.XtraNavBar.NavBarLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraNavBarLocalizationCHS();
     //DevExpress.XtraPivotGrid.Localization.PivotGridLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraPivotGridLocalizationCHS();
     DevExpress.XtraPrinting.Localization.PreviewLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraPrintingLocalizationCHS();
     DevExpress.XtraReports.Localization.ReportLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraReportsLocalizationCHS();
     //DevExpress.XtraRichTextEdit.Localization.XtraRichTextEditLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraRichTextEditLocalizationCHS();
     //DevExpress.XtraRichEdit.Localization.XtraRichEditLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraRichEditLocalizationCHS();
     DevExpress.XtraScheduler.Localization.SchedulerLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraSchedulerLocalizationCHS();
     DevExpress.XtraScheduler.Localization.SchedulerExtensionsLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraSchedulerExtensionsLocalizationCHS();
     DevExpress.XtraSpellChecker.Localization.SpellCheckerLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraSpellCheckerLocalizationCHS();
     DevExpress.XtraTreeList.Localization.TreeListLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraTreeListLocalizationCHS();
     //DevExpress.XtraVerticalGrid.Localization.VGridLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraVerticalGridLocalizationCHS();
     //DevExpress.XtraWizard.Localization.WizardLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraWizardLocalizationCHS();
     //frmLogin dlg = new frmLogin(); 
     //if (dlg.ShowDialog() == DialogResult.OK)
     Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
     Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
     Application.ThreadExit += new EventHandler(Application_ThreadExit);
     //Application.Run(new frmMain2());
     string uc= ConfigurationManager.AppSettings["usercompany"];
     if (!string.IsNullOrEmpty(uc))
         Ebada.Client.Platform.MainHelper.UserCompany = uc;
     Application.Run(new FrmSystem());
 }
        protected void btnAddFile_Click(object sender, EventArgs e)
        {
            if (fuFileUpload.HasFile == true)
            {
                if (Path.GetExtension(fuFileUpload.FileName).ToLower() != ".zip")
                {
                    lblUploadStatus.Text = "Upload failed: please upload .zip files only! Use the File Manager to upload single files.";
                    return;
                }

                string tempFile = Path.GetTempFileName();
                fuFileUpload.SaveAs(tempFile);

                ICSharpCode.SharpZipLib.Zip.FastZip fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();

                string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

                fastZip.ExtractZip(tempFile, tempDirectory, "");

                if (ValidateZipFileContainsOnlyOneLauncher(tempDirectory) == false)
                {
                    lblUploadStatus.Text = "Upload failed: upload package contains multiple launcher.exe files.";
                    return;
                }

                if (ValidateCombinedPackageAndZipFileContainOnlyOneLauncher(this.Target, tempDirectory) == false)
                {
                    lblUploadStatus.Text = "Upload failed: the package contains a launcher.exe that is in a different location in the zip file.";
                    return;
                }

                AutoUpdateManager.CreateBackup("AutoBackup - Uploading " + fuFileUpload.FileName + " to " + this.Target);

                AddUploadedFilesToPackage(this.Target, tempDirectory, tempDirectory);

                File.Delete(tempFile);
                Directory.Delete(tempDirectory, true);

                lblUploadStatus.Text = "Upload for " + fuFileUpload.FileName + " complete.";

                BindData();

                ucPackageContents.BindData();

                CheckPackageForUpdatedLauncher();
            }
        }
Exemple #6
0
 /// <summary>
 /// Extract [zipFileName] to [destinationPath] recursively
 /// </summary>
 /// <param name="zipFileName"></param>
 public static void ExtractRecursively(string zipFileName)
 {
     try
     {
         ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
         fz.ExtractZip(zipFileName, Path.GetDirectoryName(zipFileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(zipFileName), "");
         DirectoryInfo diInputDir = new DirectoryInfo(Path.GetDirectoryName(zipFileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(zipFileName));
         FileInfo[] fiInfoArr = diInputDir.GetFiles("*.zip", SearchOption.AllDirectories);
         foreach (FileInfo fiInfo in fiInfoArr)
         {
             if (string.Compare(Path.GetExtension(fiInfo.FullName), ".zip", true) == 0)
             {
                 ExtractRecursively(fiInfo.FullName);
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        int DownloadAndExtractZipFile()
        {
            #region Download and Extract Zip file
            try
            {





                str = ScriptName;
                str += "_Script";

                Assembly ass = Assembly.GetEntryAssembly();
                // this maybe something like "using Vmuktiapi"
                filename = str + ".zip";

                #region Download Zip File using WCF FileTranserService

                try
                {
                    BasicHttpClient bhcFts = new BasicHttpClient();
                    clientHttpFileTransfer = (IHTTPFileTransferService)bhcFts.OpenClient<IHTTPFileTransferService>("http://" + VMuktiInfo.BootStrapIPs[0] + ":80/VMukti/HttpFileTransferService");
                    clientHttpFileTransfer.svcHTTPFileTransferServiceJoin();
                    DownloadRequest request = new DownloadRequest();
                    RemoteFileInfo rfi = new RemoteFileInfo();

                    request.FileName = filename;
                    request.FolderWhereFileIsStored = "Scripts";
                    rfi = clientHttpFileTransfer.svcHTTPFileTransferServiceDownloadFile(request);

                

                    if (!Directory.Exists(ass.Location.Replace("VMukti.Presentation.exe", @"Scripts")))
                    {
                        Directory.CreateDirectory(ass.Location.Replace("VMukti.Presentation.exe", @"Scripts"));
                    }
                    destination = ass.Location.Replace("VMukti.Presentation.exe", @"Scripts");

                 
                    filePath = destination + "\\" + filename;

                    System.IO.Stream inputStream = rfi.FileByteStream;


                    using (System.IO.FileStream writeStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, FileShare.ReadWrite))
                    {
                        int chunkSize = 2048;
                        byte[] buffer = new byte[chunkSize];

                        do
                        {
                            // read bytes from input stream
                            int bytesRead = inputStream.Read(buffer, 0, chunkSize);
                            if (bytesRead == 0) break;

                            // write bytes to output stream
                            writeStream.Write(buffer, 0, bytesRead);

                        } while (true);
                        writeStream.Close();
                    }
                    //}
                }
                catch (Exception ex)
                {
                   
                    VMuktiAPI.VMuktiHelper.ExceptionHandler(ex, "DownloadAndExtractZipFile", "ctlScriptdesigner.xaml.cs");
                    return -1;
                }

                #endregion

                #region Downloading ZipFile Using WebClient  -----Commented


                #endregion

                #region Extracting

                if (!Directory.Exists(ass.Location.Replace("VMukti.Presentation.exe", @"ScriptModules")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("VMukti.Presentation.exe", @"ScriptModules"));
                }



              
                try
                {
                    str = ScriptName;
                    str += "_Script";

                    Assembly ass2 = Assembly.GetEntryAssembly();

                    strModPath = ass2.Location.Replace("VMukti.Presentation.exe", @"ScriptModules");

                
                    
                  
                   
                }
                catch (Exception e)
                {
                    VMuktiAPI.VMuktiHelper.ExceptionHandler(e, "DownloadAndExtractZipFile", "ctlScriptdesigner.xaml.cs");
                }





            
                ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();

               // if (!Directory.Exists(strModPath + "\\" + str  ))
                {
                    fz.ExtractZip(destination + "\\" + filename, strModPath+ "\\"+str, null);
                   
                }
                
              

                #endregion
            }
            catch (Exception ex)
            {
                VMuktiAPI.VMuktiHelper.ExceptionHandler(ex, "DownloadAndExtractZipFile", "ctlScriptdesigner.xaml.cs");
                return -1;
            }
            #endregion
            return 0;
        }
Exemple #8
0
        public ActionResult Deploy(string payload)
        {
            var sentPayload = JsonConvert.DeserializeObject<JObject>(payload);

            var head = GetHead(sentPayload);
            var commits = GetCommits(sentPayload);

            var sourcesUrl = "https://github.com/lgadi/ZeeBi/zipball/master";
            var logFile = @"C:\ZeeBi\deploy.log";

            System.IO.File.AppendAllText(logFile, "\r\nDeploying starts at " + DateTime.UtcNow);

            var t = Task.Factory.StartNew(() =>
            {
                var client = new WebClient();
                client.DownloadDataCompleted += (s, e) =>
                {
                    System.IO.File.AppendAllText(logFile, "sources arrived\r\n");
                    var output = new StringBuilder();
                    try
                    {
                        var sourcesDir = @"C:\ZeeBi\sources";
                        var sourcesZip = @"C:\ZeeBi\sources.zip";
                        System.IO.File.WriteAllBytes(sourcesZip, e.Result);

                        if (Directory.Exists(sourcesDir)) Directory.Delete(sourcesDir, true);

                        var zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                        zip.ExtractZip(sourcesZip, sourcesDir, string.Empty);
                        System.IO.File.AppendAllText(logFile, "sources unzipped\r\n");

                        // the data is actually in a sub-folder:
                        sourcesDir = Directory.GetDirectories(sourcesDir)[0];

                        var startInfo = new ProcessStartInfo(Path.Combine(sourcesDir,"deploy.bat"))
                        {
                            CreateNoWindow = true,
                            WorkingDirectory = sourcesDir,
                            RedirectStandardOutput = true,
                            RedirectStandardError = true,
                            UseShellExecute = false,
                            ErrorDialog = false,
                        };
                        startInfo.EnvironmentVariables.Add("GIT_COMMIT_HEAD", head);
                        startInfo.EnvironmentVariables.Add("GIT_COMMITS", commits);
                        var p = Process.Start(startInfo);
                        p.OutputDataReceived += (proc, data) => output.AppendLine(data.Data);
                        p.BeginOutputReadLine();
                        p.ErrorDataReceived += (proc, data) => output.AppendLine(data.Data);
                        p.BeginErrorReadLine();
                        p.WaitForExit();
                    }
                    catch (Exception ex)
                    {
                        System.IO.File.AppendAllText(logFile, "\r\n");
                        System.IO.File.AppendAllText(logFile, "EXCEPTION:\r\n");
                        System.IO.File.AppendAllText(logFile, ex.ToString());
                        System.IO.File.AppendAllText(logFile, "\r\n");
                    }
                    finally
                    {
                        System.IO.File.AppendAllText(logFile, "deploy output:\r\n");
                        System.IO.File.AppendAllText(logFile, output + "\r\n");
                        System.IO.File.AppendAllText(logFile, "==============\r\n");
                    }
                };

                client.DownloadDataAsync(new Uri(sourcesUrl));
            });
            System.IO.File.AppendAllText(logFile, "\r\nDownloading sources ... ");

            return Content("OK");
        }
Exemple #9
0
 public static void ExtractZipPassword(string zipFile, string DesPath, string password = "******")
 {
     ICSharpCode.SharpZipLib.Zip.FastZip fastzip = new ICSharpCode.SharpZipLib.Zip.FastZip();
     fastzip.Password = password;
     fastzip.ExtractZip(zipFile, DesPath, "");
 }
Exemple #10
0
        void lv3_DoubleClick(object sender, EventArgs e)
        {
            ListViewItem lvi = lv3.SelectedItems[0];
            ArrayList al = (ArrayList)lvi.Tag;
            FileInfo fi=(FileInfo)al[0];
            zip.Zip.ZipFile zf=(zip.Zip.ZipFile)al[1];
            zip.Zip.ZipEntry ze=(zip.Zip.ZipEntry)al[2];

            string strFName = fi.FullName;

            string strName = ze.Name;
            string strParent = "";

            if (strName.IndexOf("/") != -1)
            {
                string[] strNameArr = strName.Split(Encoding.Default.GetChars(Encoding.Default.GetBytes("/")));
                strName = strNameArr[strNameArr.Length - 1];
                for (int i = 0; i < strNameArr.Length - 2; i++)
                {
                    strParent += "\\" + strNameArr[i];
                }
            }

            if (isZip(strFName))
            {
                zip.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
                fz.ExtractZip(strFName, Application.UserAppDataPath + strParent, ze.Name);
                
                FileInfo[] fins = new FileInfo[1];
                fins.SetValue(new FileInfo(Application.UserAppDataPath + "\\" + ze.Name), 0);
                PropForm pf = new PropForm(fins);
                pf.Show();
            }            
        }
		//protected void Page_Load(object sender, EventArgs e)
		//{
		//    //CifrarStringConexao();
		//    GridViewAcerto.PreRender += GridViewAcerto_PreRender;
		//    GridViewPrevia.PreRender += GridViewPrevia_PreRender;
		//}

		//private void GridViewPrevia_PreRender(object sender, EventArgs e)
		//{
		//    try
		//    {
		//        GridViewPrevia.HeaderRow.TableSection = TableRowSection.TableHeader;
		//    }
		//    catch (Exception)
		//    { }
		//}

		//private void GridViewAcerto_PreRender(object sender, EventArgs e)
		//{
		//    try
		//    {
		//        GridViewAcerto.HeaderRow.TableSection = TableRowSection.TableHeader;
		//    }
		//    catch (Exception)
		//    { }
		//}

		protected void ButtonEnviar_Click(object sender, EventArgs e)
		{
			Cache.Remove("menorAno");
			Cache.Remove("ultima_atualizacao");
			Cache.Remove("tableParlamentar");
			Cache.Remove("tableDespesa");
			Cache.Remove("tablePartido");

			String atualDir = Server.MapPath("Upload");

			if (FileUpload.FileName != "")
			{
				//string ftpUrl = ConfigurationManager.AppSettings["ftpAddress"];
				//string ftpUsername = ConfigurationManager.AppSettings["ftpUsername"];
				//string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"];
				//FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl + "Transactions.zip");
				//request.Proxy = new WebProxy(); //-----The requested FTP command is not supported when using HTTP proxy.
				//request.Method = WebRequestMethods.Ftp.UploadFile;
				//request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
				//StreamReader sourceStream = new StreamReader(fileToBeUploaded);
				//byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
				//sourceStream.Close();
				//request.ContentLength = fileContents.Length;
				//Stream requestStream = request.GetRequestStream();
				//requestStream.Write(fileContents, 0, fileContents.Length);
				//requestStream.Close();
				//FtpWebResponse response = (FtpWebResponse)request.GetResponse();
				//Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
				//response.Close();

				//using (var requestStream = request.GetRequestStream())
				//{
				//    using (var input = File.OpenRead(fileToBeUploaded))
				//    {
				//        input.CopyTo(requestStream);
				//    }
				//}

				if (!Directory.Exists(atualDir))
					Directory.CreateDirectory(atualDir);

				FileUpload.SaveAs(atualDir + "\\" + FileUpload.FileName);

				ICSharpCode.SharpZipLib.Zip.ZipFile file = null;

				try
				{
					file = new ICSharpCode.SharpZipLib.Zip.ZipFile(atualDir + "\\" + FileUpload.FileName);

					if (file.TestArchive(true) == false)
					{
						Response.Write("<script>alert('Erro no Zip. Faça o upload novamente.')</script>");
						return;
					}
				}
				finally
				{
					if (file != null)
						file.Close();
				}

				ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
				zip.ExtractZip(atualDir + "//" + FileUpload.FileName, Server.MapPath("Upload"), null);

				File.Delete(atualDir + "//" + FileUpload.FileName);

				Carregar(atualDir);
			}
			else
			{
				DirectoryInfo dir = new DirectoryInfo(atualDir);

				foreach (FileInfo file in dir.GetFiles("*.zip"))
				{
					ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
					zip.ExtractZip(file.FullName, file.DirectoryName, null);

					File.Delete(file.FullName);

					Carregar(file.DirectoryName);
				}
			}
		}
Exemple #12
0
 /// <summary>
 /// Extrage fisierele din fisierul .zip specificat in destinatia specificata.
 /// </summary>
 /// <param name="filePath">Locatia fisierului .zip</param>
 /// <param name="destPath">Destinatia</param>
 /// <param name="errorMessage">Mesajul de eroare in cazul negasirii fisierului</param>
 private static void Unzip(string filePath, string destPath, string errorMessage)
 {
     if (System.IO.File.Exists(filePath))
     {
         try
         {
             var zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
             zip.ExtractZip(filePath, destPath, "");
             Console.WriteLine("\tOK");
         }
         catch (System.Exception e)
         {
             Console.WriteLine("EROARE {0}", e.Message);
         }
     }
     else
         Console.WriteLine("\tEroare - {0}", errorMessage);
 }
Exemple #13
0
        public bool InstallPlugin(string PluginPackagePath, ref string ErrorText)
        {
            string exePath = Path.GetDirectoryName(Application.ExecutablePath);

            if (Directory.Exists(exePath + "/tempDir/"))
            {
                Directory.Delete(exePath + "/tempDir/", true);
            }

            PluginDescription desc        = new PluginDescription();
            string            tempfolder  = exePath + "/tempDir/";
            string            zipFileName = Path.GetFullPath(PluginPackagePath);
            string            DescPath    = null;

            bool NoError = true;

            ICSharpCode.SharpZipLib.Zip.FastZip fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
            try
            {
                fastZip.ExtractZip(zipFileName, tempfolder, null);
                // find all included plugin descriptions and install the plugins
                List <string> osapdFiles = new List <string>();
                List <string> sqlFiles   = new List <string>();

                string[] pluginFile = Directory.GetFiles(tempfolder, "*.osapd", SearchOption.TopDirectoryOnly);
                osapdFiles.AddRange(pluginFile);
                string[] sqlFile = Directory.GetFiles(tempfolder, "*.sql", SearchOption.TopDirectoryOnly);
                sqlFiles.AddRange(sqlFile);

                if (osapdFiles.Count == 0)
                {
                    MessageBox.Show("No plugin description files found.");
                    return(false);
                }

                if (osapdFiles.Count > 1)
                {
                    MessageBox.Show("More than one plugin description file found.");
                    return(false);
                }
                if (osapdFiles.Count == 1)
                {
                    DescPath = osapdFiles[0];
                }

                if (!string.IsNullOrEmpty(DescPath))
                {
                    desc.Deserialize(DescPath);

                    //NoError = desc.VerifyInstall(ref ErrorText);

                    //uninstall previous plugin and delete the folder
                    if (UninstallPlugin(desc))
                    {
                        MessageBox.Show("Starting 4.");
                        // get the plugin folder path
                        string pluginFolder = desc.Path;
                        if (!string.IsNullOrEmpty(pluginFolder))  //only extract valid plugins
                        {
                            string[] files = System.IO.Directory.GetFiles(tempfolder);

                            string ConnectionString = string.Format("Uid={0};Pwd={1};Server={2};Port={3};Database={4};allow user variables=true",
                                                                    Common.DBUsername, Common.DBPassword, Common.DBConnection, Common.DBPort, Common.DBName);
                            MessageBox.Show("Connecting to DB using:  " + Common.DBUsername + "  " + Common.DBPassword + "  " + Common.DBConnection + "  " + Common.DBPort + "  " + Common.DBName);
                            MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(ConnectionString);
                            connection.Open();
                            foreach (string s in sqlFile)
                            {
                                try
                                {
                                    MySql.Data.MySqlClient.MySqlScript script = new MySql.Data.MySqlClient.MySqlScript(connection, File.ReadAllText(s));
                                    script.Execute();
                                }
                                catch (Exception ex)
                                {
                                    this.Log.Error("Error running sql script: " + s, ex);
                                }
                            }

                            System.IO.Directory.Move(tempfolder, exePath + "/Plugins/" + pluginFolder);

                            //Check if we are running a x64 bit architecture (This is a silly way to do it since I am not sure if every 64 bit machine has this directory...)
                            bool is64bit = Environment.Is64BitOperatingSystem;

                            //Do a check for any x64 assemblies, and prompt the user to install them if they are running a 64 bit machine
                            if (is64bit && (desc.x64Assemblies.Count > 0))
                            {
                                /* x64 assemblies generally have the same name as their x32 counterparts when referenced by the OSA app
                                 * however they are packaged as "filename.ext.x64" so we will replace the 32bit file which is installed by
                                 * default with the 64bit versioin with the same filename.ext
                                 */

                                if (MessageBox.Show(
                                        "You are running an x64 architecture and this plugin has specific assemblies built for 64bit machines." +
                                        " It is highly recommended that you install the 64bit versions to ensure proper compatibility",
                                        "Install 64bit Assemblies?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    //Install the 64bit assemblies over the 32 bit ones...
                                    string[] x64files = System.IO.Directory.GetFiles(exePath + "/Plugins/" + pluginFolder, "*.x64");

                                    foreach (string str in x64files)
                                    {
                                        string destFile = System.IO.Path.Combine(exePath + "/Plugins/" + pluginFolder + "/", System.IO.Path.GetFileNameWithoutExtension(str));
                                        //Copy it to the new destination overwriting the old file if it exists
                                        System.IO.File.Copy(str, destFile, true);
                                    }
                                }
                            }

                            //Delete all the files with .x64 extensions since they aren't needed anymore
                            string[] delfiles = System.IO.Directory.GetFiles(exePath + "/Plugins/" + pluginFolder, "*.x64");
                            foreach (string str in delfiles)
                            {
                                System.IO.File.Delete(str);
                            }

                            this.Log.Info("Sending message to service to load plugin.");
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("catch: " + ex.Message);
                return(false);
            }
            if (Directory.Exists(exePath + "/tempDir/"))
            {
                deleteFolder(exePath + "/tempDir/");
            }

            OSAEMethodManager.MethodQueueAdd("SERVICE-" + Common.ComputerName, "RELOAD PLUGINS", "", "", "Plugin Installer");
            return(NoError);
        }
Exemple #14
0
        public static bool xmlDB_Libraries_ImportFromZip(this TM_Xml_Database tmDatabase, string zipFileToImport, string unzipPassword)
        {
            var result = false;

            try
            {
                var currentLibraryPath = tmDatabase.Path_XmlLibraries;
                if (currentLibraryPath.isNull())
                {
                    return(false);
                }
                if (zipFileToImport.isUri())
                {
                    "[xmlDB_Libraries_ImportFromZip] provided value was an URL so, downloading it: {0}".info(zipFileToImport);
                    zipFileToImport = new Web().downloadBinaryFile(zipFileToImport);
                    //zipFileToImport =  zipFileToImport.uri().download();
                }
                "[xmlDB_Libraries_ImportFromZip] importing library from: {0}".info(zipFileToImport);
                if (zipFileToImport.fileExists().isFalse())
                {
                    "[xmlDB_Libraries_ImportFromZip] could not find file to import".error(zipFileToImport);
                }
                else
                {
                    // handle the zips we get from GitHub

                    var tempDir = @"..\_".add_RandomLetters(3).tempDir(false).fullPath(); //trying to make the unzip path as small as possible
                    var fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip {
                        Password = unzipPassword ?? ""
                    };
                    fastZip.ExtractZip(zipFileToImport, tempDir, "");

                    Files.copyFolder(tempDir, currentLibraryPath, true, true, "");          // just copy all files into Library path
                    result = true;

                    /*
                     * var gitZipFolderName = tempDir.folders().first().folderName();				// the first folder should be the one created by gitHub's zip
                     * var xmlFile_Location1 = tempDir.pathCombine(gitZipFolderName + ".xml");
                     * var xmlFile_Location2 = tempDir.pathCombine(gitZipFolderName).pathCombine(gitZipFolderName + ".xml");
                     * if (xmlFile_Location1.fileExists() || xmlFile_Location2.fileExists())
                     *  // if these exists here, just copy the unziped files directly
                     * {
                     *  Files.copyFolder(tempDir, currentLibraryPath, true, true, ".git");
                     *  if (xmlFile_Location1.fileExists())
                     *      Files.copy(xmlFile_Location1, currentLibraryPath.pathCombine(gitZipFolderName));
                     *  result = true;
                     * }
                     * else
                     * {
                     *  //if (zipFileToImport.extension() == ".master")
                     *  var gitZipDir = tempDir.pathCombine(gitZipFolderName);
                     *  foreach (var libraryFolder in gitZipDir.folders())
                     *  {
                     *      var libraryName = libraryFolder.folderName();
                     *      var targetFolder = currentLibraryPath.pathCombine(libraryName);
                     *
                     *      //default behaviour is to override the existing libraries
                     *      Files.copyFolder(libraryFolder, currentLibraryPath);
                     *
                     *      //handle the case where the xml file is located outside the library folder
                     *      var libraryXmlFile = gitZipDir.pathCombine("{0}.xml".format(libraryName));
                     *      if (libraryXmlFile.fileExists())
                     *          Files.copy(libraryXmlFile, targetFolder);
                     *              // put it in the Library folder which is where it really should be
                     *  }
                     *  var virtualMappings = gitZipDir.pathCombine("Virtual_Articles.xml");
                     *  if (virtualMappings.fileExists())
                     *  {
                     *      Files.copy(virtualMappings, currentLibraryPath); // copy virtual mappings if it exists
                     *      tmDatabase.mapVirtualArticles();
                     *  }
                     *  result = true;
                     * } */
                }
            }
            catch (Exception ex)
            {
                ex.log("[xmlDB_Libraries_ImportFromZip]");
            }

            if (result)
            {
                tmDatabase.reloadGuidanceExplorerObjects();
            }
            //tmDatabase.loadLibraryDataFromDisk();

            return(result);
        }
        private static void PerformCheck(object state)
        {
            try {
                CheckForCodeplexRelease();
            } catch(Exception exc) {
                Terminals.Logging.Log.Error("Failed during CheckForCodeplexRelease.", exc);
            }
            try {
                string autoUpdate = Terminals.MainForm.CommandLineArgs.AutomaticallyUpdate;
                if(autoUpdate != null) {
                    bool update = false;
                    if(bool.TryParse(autoUpdate, out update) && update == true) {
                        string url = Settings.UpdateSource;
                        string contents = Download(url);
                        if(!String.IsNullOrEmpty(contents)) {
                            TerminalsUpdates updates = (TerminalsUpdates)Unified.Serialize.DeSerializeXML(contents, typeof(TerminalsUpdates));
                            if(updates != null) {
                                string currentMD5 = GetMD5HashFromFile("Terminals.exe");
                                if(currentMD5 != null) {
                                    //get the latest build
                                    System.Data.DataRow row = updates.Tables[0].Rows[0];
                                    string md5 = (row["MD5"] as string);
                                    if(!md5.Equals(currentMD5)) {
                                        string version = (row["version"] as string);
                                        if(!System.IO.Directory.Exists("Builds")) System.IO.Directory.CreateDirectory("Builds");
                                        string finalFolder = @"Builds\" + version;
                                        if(!System.IO.Directory.Exists(finalFolder)) System.IO.Directory.CreateDirectory(finalFolder);
                                        string filename = string.Format("{0}.zip", version);
                                        filename = @"Builds\" + filename;
                                        bool downloaded = true;
                                        if(!System.IO.File.Exists(filename)) downloaded = DownloadNewBuild((row["Url"] as string), filename);
                                        if(downloaded && System.IO.File.Exists(filename)) {
                                            //ICSharpCode.SharpZipLib.Zip.FastZipEvents evts = new ICSharpCode.SharpZipLib.Zip.FastZipEvents();
                                            ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
                                            fz.ExtractZip(filename, finalFolder, null);
                                            if(System.Windows.Forms.MessageBox.Show("A new build is available, would you like to install it now", "New Build", System.Windows.Forms.MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK) {

                                                System.IO.DirectoryInfo parent = FindFileInFolder(new DirectoryInfo(finalFolder), "Terminals.exe");
                                                if(parent == null) {
                                                    return;
                                                } else {
                                                    finalFolder = parent.FullName;
                                                }

                                                System.IO.File.Copy("Terminals.config", System.IO.Path.Combine(finalFolder, "Terminals.config"), true);
                                                System.IO.File.Copy("ToolStrip.settings", System.IO.Path.Combine(finalFolder, "ToolStrip.settings"), true);
                                                System.IO.File.Copy("Terminals.log4net.config", System.IO.Path.Combine(finalFolder, "Terminals.log4net.config"), true);

                                                string temp = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                                                string updaterExe = System.IO.Path.Combine(temp, "TerminalsUpdater.exe");
                                                if(System.IO.File.Exists(System.IO.Path.Combine(finalFolder, "TerminalsUpdater.exe"))) {
                                                    System.IO.File.Copy(System.IO.Path.Combine(finalFolder, "TerminalsUpdater.exe"), updaterExe, true);
                                                }
                                                //updaterExe = @"C:\Source\Terminals\Terminals\bin\Debug\";

                                                if(System.IO.File.Exists(updaterExe)) {
                                                    string args = "\"" + finalFolder + "\" \"" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\"";
                                                    System.Diagnostics.Process.Start(updaterExe, args);
                                                    System.Windows.Forms.Application.Exit();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } catch(Exception exc) {
                Terminals.Logging.Log.Error("Failed during update.", exc);
            }
        }
        public static bool xmlDB_Libraries_ImportFromZip(this TM_Xml_Database tmDatabase, string zipFileToImport, string unzipPassword)
        {
            var result = false;
            try
            {
                var currentLibraryPath = tmDatabase.Path_XmlLibraries;
                if (currentLibraryPath.isNull())
                    return false;
                if (zipFileToImport.isUri())
                {
                    "[xmlDB_Libraries_ImportFromZip] provided value was an URL so, downloading it: {0}".info(zipFileToImport);
                    zipFileToImport = new Web().downloadBinaryFile(zipFileToImport);
                    //zipFileToImport =  zipFileToImport.uri().download();
                }
                "[xmlDB_Libraries_ImportFromZip] importing library from: {0}".info(zipFileToImport);
                if (zipFileToImport.fileExists().isFalse())
                    "[xmlDB_Libraries_ImportFromZip] could not find file to import".error(zipFileToImport);
                else
                {
                    // handle the zips we get from GitHub

                    var tempDir = @"..\_".add_RandomLetters(3).tempDir(false).fullPath(); //trying to make the unzip path as small as possible
                    var fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip {Password = unzipPassword ?? ""};
                    fastZip.ExtractZip(zipFileToImport, tempDir, "");

                    Files.copyFolder(tempDir, currentLibraryPath, true, true,"");          // just copy all files into Library path
                    result = true;
                    /*
                    var gitZipFolderName = tempDir.folders().first().folderName();				// the first folder should be the one created by gitHub's zip
                    var xmlFile_Location1 = tempDir.pathCombine(gitZipFolderName + ".xml");
                    var xmlFile_Location2 = tempDir.pathCombine(gitZipFolderName).pathCombine(gitZipFolderName + ".xml");
                    if (xmlFile_Location1.fileExists() || xmlFile_Location2.fileExists())
                        // if these exists here, just copy the unziped files directly
                    {
                        Files.copyFolder(tempDir, currentLibraryPath, true, true, ".git");
                        if (xmlFile_Location1.fileExists())
                            Files.copy(xmlFile_Location1, currentLibraryPath.pathCombine(gitZipFolderName));
                        result = true;
                    }
                    else
                    {
                        //if (zipFileToImport.extension() == ".master")
                        var gitZipDir = tempDir.pathCombine(gitZipFolderName);
                        foreach (var libraryFolder in gitZipDir.folders())
                        {
                            var libraryName = libraryFolder.folderName();
                            var targetFolder = currentLibraryPath.pathCombine(libraryName);

                            //default behaviour is to override the existing libraries
                            Files.copyFolder(libraryFolder, currentLibraryPath);

                            //handle the case where the xml file is located outside the library folder
                            var libraryXmlFile = gitZipDir.pathCombine("{0}.xml".format(libraryName));
                            if (libraryXmlFile.fileExists())
                                Files.copy(libraryXmlFile, targetFolder);
                                    // put it in the Library folder which is where it really should be
                        }
                        var virtualMappings = gitZipDir.pathCombine("Virtual_Articles.xml");
                        if (virtualMappings.fileExists())
                        {
                            Files.copy(virtualMappings, currentLibraryPath); // copy virtual mappings if it exists
                            tmDatabase.mapVirtualArticles();
                        }
                        result = true;
                    } */
                }
            }
            catch (Exception ex)
            {
                ex.log("[xmlDB_Libraries_ImportFromZip]");
            }

            if (result)
                tmDatabase.reloadGuidanceExplorerObjects();
                //tmDatabase.loadLibraryDataFromDisk();

            return result;
        }
Exemple #17
0
        static string GetCallstackFromMinidump(string filename, string symPath)
        {
            string tempDir = Environment.ExpandEnvironmentVariables(@"%TEMP%\CrashGatherer");

            string[] files = System.IO.Directory.GetFiles(tempDir, "*.dmp");
            foreach (string fn in files)
            {
                System.IO.File.Delete(fn);
            }

            ICSharpCode.SharpZipLib.Zip.FastZip extractor = new ICSharpCode.SharpZipLib.Zip.FastZip();
            extractor.ExtractZip(filename, tempDir, "dmp");

            files = System.IO.Directory.GetFiles(tempDir, "*.dmp");
            if (files.Length < 1)
            {
                Console.WriteLine("no *.dmp in {0}!", filename);
                return("@@@@==== NO *.DMP FILE ====@@@@");
            }

            if (IsValidMinidumpFile(files[0]) == false)
            {
                Console.WriteLine("invalid *.dmp file: {0}", filename);
                return("@@@@==== INVALID *.DMP FILE ====@@@@");
            }

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("-z {0} -lines -c \".ecxr;kb;q\" -y {1}", files[0], symPath);

            System.Diagnostics.Process cdb = new System.Diagnostics.Process();
            cdb.StartInfo.UseShellExecute        = false;
            cdb.StartInfo.FileName               = CDBPath;
            cdb.StartInfo.Arguments              = sb.ToString();
            cdb.StartInfo.RedirectStandardOutput = true;
            if (cdb.Start() == false)
            {
                Console.WriteLine("Start CDB.EXE failed: {0}", filename);
                return("@@@@==== START CDB.EXE FAILED ====@@@@");
            }

            string output = cdb.StandardOutput.ReadToEnd();

            if (output.EndsWith("quit:\n") == false)
            {
                Console.WriteLine("output log was corrupted: {0}", filename);
                return("@@@@==== OUTPUT LOG WAS CORRUPTED ====@@@@");
            }
            cdb.WaitForExit();

            // 예외 정보가 없는 경우
            if (output.IndexOf("Minidump doesn't have an exception context") != -1)
            {
                return("@@@@==== THREAD HANG (OR EXCEPTION RECORD NOT FOUND) ====@@@@");
            }

            int pos = output.IndexOf("*** Stack trace");

            if (pos == -1)
            {
                // 스택 트레이스 정보가 없는 경우
                return("@@@@==== UNKNOWN *.DMP FORMAT ====@@@@");
            }

            output = output.Substring(pos);

            return(output);
        }
Exemple #18
0
        static bool ExtractFromFileData(string filename, out int acntUid, out string loginId, out int userUid, out string nickname, out string version, out string uservoice)
        {
            acntUid   = 0;
            userUid   = 0;
            loginId   = "";
            nickname  = "";
            version   = "";
            uservoice = "";

            string tempDir = Environment.ExpandEnvironmentVariables(@"%TEMP%\CrashGatherer");

            ICSharpCode.SharpZipLib.Zip.FastZip extractor = new ICSharpCode.SharpZipLib.Zip.FastZip();
            extractor.ExtractZip(filename, tempDir, "userReport.txt");
            extractor.ExtractZip(filename, tempDir, "stack.log");

            string uservoicePath = tempDir + "\\userReport.txt";

            if (System.IO.File.Exists(uservoicePath))
            {
                using (TextReader reader = new StreamReader(uservoicePath, Encoding.Default))
                {
                    uservoice += reader.ReadToEnd();
                }

                System.IO.File.Delete(uservoicePath);
            }

            string stackLogPath = tempDir + "\\stack.log";

            if (System.IO.File.Exists(stackLogPath) == false)
            {
                return(false);
            }

            using (TextReader reader = new StreamReader(stackLogPath, Encoding.Default))
            {
                string line = reader.ReadLine();
                if (line != null)
                {
                    string[] seps   = new string[] { ", " };
                    string[] series = line.Split(seps, StringSplitOptions.RemoveEmptyEntries);

                    if (series.Length < 5)
                    {
                        series = line.Split(',');
                    }

                    if (series.Length >= 5)
                    {
                        acntUid  = GetIntFromString(series[0]);
                        loginId  = series[1].Trim();
                        userUid  = GetIntFromString(series[2]);
                        nickname = series[3].Trim();
                        if (kBase64Nickname)
                        {
                            byte[] conv = Convert.FromBase64String(nickname);
                            //nickname = Encoding.ASCII.GetString(conv);
                            nickname = Encoding.GetEncoding(0).GetString(conv);
                        }

                        version = series[4].Trim();
                    }
                }

                uservoice += reader.ReadToEnd();
                uservoice  = uservoice.Trim();

                reader.Close();
            }

            return(true);
        }
Exemple #19
0
        static bool ExtractFromFileData(string filename, out int acntUid, out string loginId, out int userUid, out string nickname, out string version, out string uservoice)
        {
            acntUid = 0;
            userUid = 0;
            loginId = "";
            nickname = "";
            version = "";
            uservoice = "";

            string tempDir = Environment.ExpandEnvironmentVariables(@"%TEMP%\CrashGatherer");

            ICSharpCode.SharpZipLib.Zip.FastZip extractor = new ICSharpCode.SharpZipLib.Zip.FastZip();
            extractor.ExtractZip(filename, tempDir, "userReport.txt");
            extractor.ExtractZip(filename, tempDir, "stack.log");

            string uservoicePath = tempDir + "\\userReport.txt";
            if (System.IO.File.Exists(uservoicePath))
            {
                using (TextReader reader = new StreamReader(uservoicePath, Encoding.Default))
                {
                    uservoice += reader.ReadToEnd();
                }

                System.IO.File.Delete(uservoicePath);
            }

            string stackLogPath = tempDir + "\\stack.log";
            if (System.IO.File.Exists(stackLogPath) == false)
            {
                return false;
            }

            using (TextReader reader = new StreamReader(stackLogPath, Encoding.Default))
            {
                string line = reader.ReadLine();
                if (line != null)
                {
                    string[] seps = new string[] {", "};
                    string[] series = line.Split(seps, StringSplitOptions.RemoveEmptyEntries);

                    if (series.Length < 5)
                        series = line.Split(',');

                    if (series.Length >= 5)
                    {
                        acntUid = GetIntFromString(series[0]);
                        loginId = series[1].Trim();
                        userUid = GetIntFromString(series[2]);
                        nickname = series[3].Trim();
                        if (kBase64Nickname)
                        {
                            byte[] conv = Convert.FromBase64String(nickname);
                            //nickname = Encoding.ASCII.GetString(conv);
                            nickname = Encoding.GetEncoding(0).GetString(conv);
                        }

                        version = series[4].Trim();
                    }
                }

                uservoice += reader.ReadToEnd();
                uservoice = uservoice.Trim();

                reader.Close();
            }

            return true;
        }
Exemple #20
0
        public void Refresh()
        {
            Clear();

            var dir = getCachedZipDirectory();

            dir.Create();

#if NET40
            ICSharpCode.SharpZipLib.Zip.FastZip  zf = new ICSharpCode.SharpZipLib.Zip.FastZip();
            zf.ExtractZip(_zipPath, dir.FullName, "*.*");
#else
            ZipFile.ExtractToDirectory(_zipPath, dir.FullName);
#endif

            // Set the last write time to be equal to the write time of the zip file,
            // this way, we can compare this time to the write times of newer zips and
            // detect we need a refresh
            Directory.SetCreationTimeUtc(dir.FullName, File.GetLastWriteTimeUtc(_zipPath));
        }
Exemple #21
0
        static string GetCallstackFromMinidump(string filename, string symPath)
        {
            string tempDir = Environment.ExpandEnvironmentVariables(@"%TEMP%\CrashGatherer");
            string[] files = System.IO.Directory.GetFiles(tempDir, "*.dmp");
            foreach (string fn in files)
            {
                System.IO.File.Delete(fn);
            }

            ICSharpCode.SharpZipLib.Zip.FastZip extractor = new ICSharpCode.SharpZipLib.Zip.FastZip();
            extractor.ExtractZip(filename, tempDir, "dmp");

            files = System.IO.Directory.GetFiles(tempDir, "*.dmp");
            if (files.Length < 1)
            {
                Console.WriteLine("no *.dmp in {0}!", filename);
                return "@@@@==== NO *.DMP FILE ====@@@@";
            }

            if (IsValidMinidumpFile(files[0]) == false)
            {
                Console.WriteLine("invalid *.dmp file: {0}", filename);
                return "@@@@==== INVALID *.DMP FILE ====@@@@";
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("-z {0} -lines -c \".ecxr;kb;q\" -y {1}", files[0], symPath);

            System.Diagnostics.Process cdb = new System.Diagnostics.Process();
            cdb.StartInfo.UseShellExecute = false;
            cdb.StartInfo.FileName = CDBPath;
            cdb.StartInfo.Arguments = sb.ToString();
            cdb.StartInfo.RedirectStandardOutput = true;
            if (cdb.Start() == false)
            {
                Console.WriteLine("Start CDB.EXE failed: {0}", filename);
                return "@@@@==== START CDB.EXE FAILED ====@@@@";
            }

            string output = cdb.StandardOutput.ReadToEnd();
            if (output.EndsWith("quit:\n") == false)
            {
                Console.WriteLine("output log was corrupted: {0}", filename);
                return "@@@@==== OUTPUT LOG WAS CORRUPTED ====@@@@";
            }
            cdb.WaitForExit();

            // 예외 정보가 없는 경우
            if (output.IndexOf("Minidump doesn't have an exception context") != -1)
            {
                return "@@@@==== THREAD HANG (OR EXCEPTION RECORD NOT FOUND) ====@@@@";
            }

            int pos = output.IndexOf("*** Stack trace");
            if (pos == -1)
            {
                // 스택 트레이스 정보가 없는 경우
                return "@@@@==== UNKNOWN *.DMP FORMAT ====@@@@";
            }

            output = output.Substring(pos);

            return output;
        }
		protected void ButtonSenadores_Click(object sender, EventArgs e)
		{
			String atualDir = Server.MapPath("Upload");

			if (FileUpload.FileName != "")
			{
				FileUpload.SaveAs(atualDir + "//" + FileUpload.FileName);

				ICSharpCode.SharpZipLib.Zip.ZipFile file = null;

				try
				{
					file = new ICSharpCode.SharpZipLib.Zip.ZipFile(atualDir + "//" + FileUpload.FileName);

					if (file.TestArchive(true) == false)
					{
						Response.Write("<script>alert('Erro no Zip. Faça o upload novamente.')</script>");
						return;
					}
				}
				finally
				{
					if (file != null)
						file.Close();
				}

				ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
				zip.ExtractZip(atualDir + "//" + FileUpload.FileName, Server.MapPath("Upload"), null);

				File.Delete(atualDir + "//" + FileUpload.FileName);

				CarregarSenadores(atualDir);
			}
			else
			{
				DirectoryInfo dir = new DirectoryInfo(atualDir);

				foreach (FileInfo file in dir.GetFiles("*.zip"))
				{
					ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
					zip.ExtractZip(file.FullName, file.DirectoryName, null);

					File.Delete(file.FullName);

					CarregarSenadores(file.DirectoryName);
				}
			}

			Cache.Remove("menorAnoSenadores");
			Cache.Remove("ultimaAtualizacaoSenadores");
			Cache.Remove("tableSenadores");
			Cache.Remove("tableDespesaSenadores");
			Cache.Remove("tablePartidoSenadores");
		}
Exemple #23
0
		public Boolean CarregaDadosReceitaEleicao(String atualDir, String ano)
		{
			using (Banco banco = new Banco())
			{
				DirectoryInfo dir = new DirectoryInfo(atualDir);

				foreach (FileInfo fileZip in dir.GetFiles("*.zip"))
				{
					ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
					zip.ExtractZip(fileZip.FullName, fileZip.DirectoryName, null);

					File.Delete(fileZip.FullName);

					foreach (FileInfo fileTxt in dir.GetFiles("*.txt", SearchOption.AllDirectories))
					{
						if (ProcessaDadosReceitaEleicao(fileTxt.FullName, banco, ano) == false)
						{
							return false;
						}

						File.Delete(fileTxt.FullName);
					}
				}

				AtualizaFornecedorDoador(banco);
			}

			return true;
		}
        public static bool xmlDB_Libraries_ImportFromZip(this TM_FileStorage tmFileStorage, string zipFileToImport, string unzipPassword)
        {
            UserRole.Admin.demand();

            var result = false;
            try
            {
                var currentLibraryPath = tmFileStorage.Path_XmlLibraries;
                if (currentLibraryPath.isNull())
                    return false;
                if (zipFileToImport.isUri())
                {
                    "[xmlDB_Libraries_ImportFromZip] provided value was an URL so, downloading it: {0}".info(zipFileToImport);
                    zipFileToImport = new Web().downloadBinaryFile(zipFileToImport);
                }
                "[xmlDB_Libraries_ImportFromZip] importing library from: {0}".info(zipFileToImport);
                if (zipFileToImport.fileExists().isFalse())
                    "[xmlDB_Libraries_ImportFromZip] could not find file to import".error(zipFileToImport);
                else
                {
                    // handle the zips we get from GitHub

                    var tempDir = @"..\_".add_RandomLetters(3).tempDir(false).fullPath(); //trying to make the unzip path as small as possible
                    var fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip {Password = unzipPassword ?? ""};

                    fastZip.ExtractZip(zipFileToImport, tempDir, "");

                    Files.copyFolder(tempDir, currentLibraryPath, true, true,"");          // just copy all files into Library path
                    Files.deleteFolder(tempDir,true);                                      // delete tmp folder created
                    result = true;

                }
            }
            catch (Exception ex)
            {
                ex.log("[xmlDB_Libraries_ImportFromZip]");
            }

            if (result)
                tmFileStorage.reloadGuidanceExplorerObjects();

            return result;
        }
        public static bool xmlDB_Libraries_ImportFromZip(this TM_Xml_Database tmDatabase, string zipFileToImport, string unzipPassword)
        {
            try
            {
                 if (zipFileToImport.isUri())
                {
                    "[xmlDB_Libraries_ImportFromZip] provided value was an URL so, downloading it: {0}".info(zipFileToImport);
                    zipFileToImport = new Web().downloadBinaryFile(zipFileToImport);
                    //zipFileToImport =  zipFileToImport.uri().download();
                }
                "[xmlDB_Libraries_ImportFromZip] importing library from: {0}".info(zipFileToImport);
                if (zipFileToImport.fileExists().isFalse())
                    "[xmlDB_Libraries_ImportFromZip] could not find file to import".error(zipFileToImport);
                else
                {
                    var currentLibraryPath = TM_Xml_Database.Path_XmlLibraries;
                    // handle the zips we get from GitHub

                    var tempDir = "_unzip".tempDir();
                    var fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                    fastZip.Password = unzipPassword ?? unzipPassword;
                    fastZip.ExtractZip(zipFileToImport, tempDir, "");

                    var gitZipFolderName = tempDir.folders().first().folderName();				// the first folder should be the one created by gitHub's zip
                    var xmlFile_location1 = tempDir.pathCombine(gitZipFolderName + ".xml");
                    var xmlFile_location2 = tempDir.pathCombine(gitZipFolderName).pathCombine(gitZipFolderName + ".xml");
                    if (xmlFile_location1.fileExists() || xmlFile_location2.fileExists())		// if these exists here, just copy the unziped files directly
                    {
                        Files.copyFolder(tempDir,currentLibraryPath,true,true,".git");
                        if (xmlFile_location1.fileExists())
                            Files.copy(xmlFile_location1, currentLibraryPath.pathCombine(gitZipFolderName));
                        return true;
                    }
                    //if (zipFileToImport.extension() == ".master")
                    else
                    {

                        var gitZipDir = tempDir.pathCombine(gitZipFolderName);
                        foreach (var libraryFolder in gitZipDir.folders())
                        {
                            var libraryName = libraryFolder.folderName();
                            var targetFolder = currentLibraryPath.pathCombine(libraryName);

                            //default behaviour is to override the existing libraries
                            /*if (targetFolder.dirExists())
                            {
                                "[xmlDB_Libraries_ImportFromZip] [from Git zip] could not import library with name {0} since there was already one with that name".error(libraryFolder.folderName());
                                return false;
                            }*/
                            Files.copyFolder(libraryFolder, currentLibraryPath);

                            //handle the case where the xml file is located outside the library folder
                            var libraryXmlFile = gitZipDir.pathCombine("{0}.xml".format(libraryName));
                            if (libraryXmlFile.fileExists())
                                Files.copy(libraryXmlFile, targetFolder);			// put it in the Library folder which is where it really should be
                        }
                        var virtualMappings = gitZipDir.pathCombine("Virtual_Articles.xml");
                        if (virtualMappings.fileExists())
                        {
                            Files.copy(virtualMappings, currentLibraryPath);			// copy virtual mappings if it exists
                            tmDatabase.mapVirtualArticles();
                        }
                        return true;
                    }
                    /*else
                    {
                        //if it is a normal zip, the expectation is that the zip is the library name
                        var libraryName = Path.GetFileNameWithoutExtension(zipFileToImport);
                        var libraryFilePath = tmDatabase.xmlDB_LibraryPath(libraryName);
                        var guidanceItemsPath = tmDatabase.xmlDB_LibraryPath_GuidanceItems(libraryName);

                        //default behaviour is to override the existing libraries

                        //if (libraryFilePath.fileExists() && libraryFilePath.fileInfo().size() == 0 ||
                        //	libraryFilePath.fileExists().isFalse() && guidanceItemsPath.dirExists().isFalse())
                        //{
                            var fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                            fastZip.Password = unzipPassword ?? unzipPassword;
                            fastZip.ExtractZip(zipFileToImport, currentLibraryPath, "");

                            //zipFileToImport.unzip_File(currentLibraryPath);
                            return true;
                        //}
                        //else
                        //	"[xmlDB_Libraries_ImportFromZip] could not import library with name {0} since there was already one with that name".error(libraryName);

                    } */
                }
            }
            catch (Exception ex)
            {
                ex.log("[xmlDB_Libraries_ImportFromZip]");
            }
            return false;
        }
        public bool InstallPlugin(string PluginPackagePath, ref string ErrorText)
        {
            string exePath = Path.GetDirectoryName(Application.ExecutablePath);
            if (Directory.Exists(exePath + "/tempDir/"))
            {
                Directory.Delete(exePath + "/tempDir/", true);
            }

            PluginDescription desc = new PluginDescription();
            string tempfolder = exePath + "/tempDir/";
            string zipFileName = Path.GetFullPath(PluginPackagePath);
            string DescPath = null;

            bool NoError = true;

            ICSharpCode.SharpZipLib.Zip.FastZip fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
            try
            {
                fastZip.ExtractZip(zipFileName, tempfolder, null);
                // find all included plugin descriptions and install the plugins
                List<string> osapdFiles = new List<string>();
                List<string> sqlFiles = new List<string>();

                string[] pluginFile = Directory.GetFiles(tempfolder, "*.osapd", SearchOption.TopDirectoryOnly);
                osapdFiles.AddRange(pluginFile);
                string[] sqlFile = Directory.GetFiles(tempfolder, "*.sql", SearchOption.TopDirectoryOnly);
                sqlFiles.AddRange(sqlFile);

                if (osapdFiles.Count == 0)
                {
                    MessageBox.Show("No plugin description files found.");
                    return false;
                }

                if (osapdFiles.Count > 1)
                {
                    MessageBox.Show("More than one plugin description file found.");
                    return false;
                }
                if (osapdFiles.Count == 1)
                {

                    DescPath = osapdFiles[0];
                }

                if (!string.IsNullOrEmpty(DescPath))
                {
                    desc.Deserialize(DescPath);

                    //NoError = desc.VerifyInstall(ref ErrorText);

                    //uninstall previous plugin and delete the folder
                    if (UninstallPlugin(desc))
                    {

                        // get the plugin folder path
                        string pluginFolder = desc.Path;
                        if (!string.IsNullOrEmpty(pluginFolder))  //only extract valid plugins
                        {
                            string[] files = System.IO.Directory.GetFiles(tempfolder);

                            string ConnectionString = string.Format("Uid={0};Pwd={1};Server={2};Port={3};Database={4};allow user variables=true",
                                Common.DBUsername, Common.DBPassword, Common.DBConnection, Common.DBPort, Common.DBName);
                            MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(ConnectionString);
                            connection.Open();
                            foreach (string s in sqlFile)
                            {
                                try
                                {

                                    MySql.Data.MySqlClient.MySqlScript script = new MySql.Data.MySqlClient.MySqlScript(connection, File.ReadAllText(s));
                                    script.Execute();
                                }
                                catch (Exception ex)
                                {
                                    this.Log.Error("Error running sql script: " + s, ex);
                                }
                            }

                            System.IO.Directory.Move(tempfolder, exePath + "/Plugins/" + pluginFolder);

                            //Check if we are running a x64 bit architecture (This is a silly way to do it since I am not sure if every 64 bit machine has this directory...)
                            bool is64bit = Environment.Is64BitOperatingSystem;

                            //Do a check for any x64 assemblies, and prompt the user to install them if they are running a 64 bit machine
                            if (is64bit && (desc.x64Assemblies.Count > 0))
                            {
                                /* x64 assemblies generally have the same name as their x32 counterparts when referenced by the OSA app
                                 * however they are packaged as "filename.ext.x64" so we will replace the 32bit file which is installed by
                                 * default with the 64bit versioin with the same filename.ext
                                 */

                                if (MessageBox.Show(
                                    "You are running an x64 architecture and this plugin has specific assemblies built for 64bit machines." +
                                    " It is highly recommended that you install the 64bit versions to ensure proper compatibility",
                                    "Install 64bit Assemblies?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    //Install the 64bit assemblies over the 32 bit ones...
                                    string[] x64files = System.IO.Directory.GetFiles(exePath + "/Plugins/" + pluginFolder, "*.x64");

                                    foreach (string str in x64files)
                                    {
                                        string destFile = System.IO.Path.Combine(exePath + "/Plugins/" + pluginFolder + "/", System.IO.Path.GetFileNameWithoutExtension(str));
                                        //Copy it to the new destination overwriting the old file if it exists
                                        System.IO.File.Copy(str, destFile, true);
                                    }
                                }
                            }

                            //Delete all the files with .x64 extensions since they aren't needed anymore
                            string[] delfiles = System.IO.Directory.GetFiles(exePath + "/Plugins/" + pluginFolder, "*.x64");
                            foreach (string str in delfiles)
                                System.IO.File.Delete(str);

                            this.Log.Info("Sending message to service to load plugin.");

                        }
                    }
                    else
                        return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("catch: " + ex.Message);
                return false;
            }
                if (Directory.Exists(exePath + "/tempDir/"))
                {
                    deleteFolder(exePath + "/tempDir/");
                }

                OSAEMethodManager.MethodQueueAdd("SERVICE-" + Common.ComputerName, "RELOAD PLUGINS", "", "", "Plugin Installer");
            return NoError;
        }
Exemple #27
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            try
            {
                string AutoUpdateConfigURL = "" + config.GetValue("AutoUpdate", "AutoUpdateConfigURL");
                string updatePath          = Application.StartupPath;

                AutoUpdateConfig.LoadConfig(AutoUpdateConfigURL, "", "");

                //create web request/response
                string url         = AutoUpdateConfig.AppFileURL;
                string path        = System.Environment.ExpandEnvironmentVariables("%TEMP%") + "\\" + url.Substring(url.LastIndexOf("/") + 1);
                string extract_dir = url.Substring(url.LastIndexOf("/") + 1);
                extract_dir = extract_dir.Substring(0, extract_dir.LastIndexOf(".zip"));

                HttpWebResponse Response;
                HttpWebRequest  Request;


                Request = (HttpWebRequest)HttpWebRequest.Create(url);
                Request.Headers.Add("Translate: f");
                Request.Credentials = CredentialCache.DefaultCredentials;

                Response = (HttpWebResponse)Request.GetResponse();

                Stream respStream = null;
                respStream = Response.GetResponseStream();

                //Do the Download
                byte[] buffer = new byte[4096];
                int    length;

                FileStream fs = File.Open(path, FileMode.Create, FileAccess.ReadWrite);

                length = respStream.Read(buffer, 0, 4096);
                while (length > 0)
                {
                    fs.Write(buffer, 0, length);
                    length = respStream.Read(buffer, 0, 4096);
                }
                fs.Close();

                //updatePath = System.IO.Directory.GetParent(updatePath).ToString();
                ICSharpCode.SharpZipLib.Zip.FastZip FastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                FastZip.ExtractZip(path, updatePath, null);

                CopyDirectory(extract_dir, updatePath);
                System.IO.Directory.Delete(extract_dir, true);

                MessageBox.Show("Live Update finish!", "Live Update");
                timer1.Enabled     = true;
                this.Opacity       = 0;
                this.ShowInTaskbar = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                timer1.Enabled = true;
            }
        }