/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> /// <history> /// [erosado] 01/06/2016 Modified. Se agrego async /// [vipacheco] 09/Agosto/2016 Modified -> Se agrego el manejador de eventos. /// </history> protected async override void OnStartup(StartupEventArgs e) { base.OnStartup(e); EventManager.RegisterClassHandler(typeof(DataGrid), UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(dataGrid_MouseLeftButtonUp)); //Creamos el Splash Base! frmSplash frmSplash = new frmSplash(); //Creamos el tipo de login que se necesita! var frmLogin = new frmLogin(frmSplash, EnumLoginType.SalesRoom, changePassword: true, autoSign: true, validatePermission: true, permission: EnumPermission.Host, permissionLevel: EnumPermisionLevel.ReadOnly); await frmLogin.getAllPlaces(); //Mostramos el Splash frmSplash.Show(); //Mandamos llamar el Login frmSplash.ShowLogin(ref frmLogin); if (frmLogin.IsAuthenticated) { Context.User = frmLogin.UserData; frmHost frmMain = new frmHost(); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.ShowDialog(); frmSplash.Close(); } }
/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); frmSplash frmSplash = new frmSplash(); frmLogin frmLogin = new frmLogin(frmSplash, EnumLoginType.Normal, validateRole: true, role: EnumRole.Manager, changePassword: true); frmSplash.Show(); frmSplash.ShowLogin(ref frmLogin); if (frmLogin.IsAuthenticated) { Context.User = frmLogin.UserData; if (Context.User.HasRole(EnumRole.Manager)) { EventManager.RegisterClassHandler(typeof(AccessText), AccessKeyManager.AccessKeyPressedEvent, new RoutedEventHandler(keyManager_keyPressed)); EventManager.RegisterClassHandler(typeof(DataGrid), UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(dataGrid_MouseLeftButtonUp)); EventManager.RegisterClassHandler(typeof(ComboBox), UIElement.KeyDownEvent, new KeyEventHandler(cmb_KeyDown)); frmAdmin frmMain = new frmAdmin(); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.ShowDialog(); frmSplash.Close(); } else { // No tiene permiso para ingresar al modulo UIHelper.ShowMessage("User doesn't have access"); } } }
/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); frmSplash frmSplash = new frmSplash(); frmLogin frmLogin = new frmLogin(frmSplash, EnumLoginType.Normal, validateRole: true, role: EnumRole.Manager, changePassword: true); frmSplash.Show(); frmSplash.ShowLogin(ref frmLogin); if (frmLogin.IsAuthenticated) { Context.User = frmLogin.UserData; if (Context.User.HasRole(EnumRole.Manager)) { frmProcessorOuthouse frmMain = new frmProcessorOuthouse(); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.Show(); frmLogin.Close(); frmSplash.Close(); } else { UIHelper.ShowMessage("User doesn't have access"); } } }
public frmMain() { InitializeComponent(); frmSplash f = new frmSplash(); f.Show(); System.Threading.Thread.Sleep(2000); f.Close(); }
public static async Task <ReturnedSaveFuncInfo> RunAsync(IWin32Window owner, string Script, SqlConnection cn, SqlTransaction transaction = null, short tryCount = 2) { var ret = new ReturnedSaveFuncInfo(); try { if (string.IsNullOrEmpty(Script)) { return(ret); } string[] seperator = { "go\r", "go\r\n", "\ngo\n", "\ngo\r\n", "\tgo\t", " go ", "\rgo\r" }; Script = Script.Replace("GO", "go").Replace("Go", "go").Replace("gO", "go"); var scripts = Script.Split(seperator, StringSplitOptions.RemoveEmptyEntries); var cmd = new SqlCommand("", cn) { CommandTimeout = 60 * 1000 * 2,//2دقیقه CommandType = CommandType.Text }; if (transaction != null) { cmd.Transaction = transaction; } if (cn.State != ConnectionState.Open) { cn.Open(); } var frm = new frmSplash(scripts.ToList().Count); frm.Show(owner); var index = 1; foreach (var item in scripts) { index++; frm.Level = index; ret.AddReturnedValue(await ExecuteAsync(item, cmd)); } frm.Close(); } catch (Exception ex) { WebErrorLog.ErrorInstence.StartErrorLog(ex); ret.AddReturnedValue(ex); } if (ret.HasError && tryCount > 0) { await Task.Delay(1000); return(await RunAsync(owner, Script, cn, transaction, --tryCount)); } return(ret); }
public static void ExportLog(IEnumerable <SmsLogBussines> list, IWin32Window owner) { try { var sfd = new SaveFileDialog() { Filter = "Excel Files|*.xls" }; if (sfd.ShowDialog(owner) != DialogResult.OK) { return; } var excel = new Microsoft.Office.Interop.Excel.Application(); var wb = excel.Workbooks.Add(XlSheetType.xlWorksheet); var ws = (Worksheet)excel.ActiveSheet; excel.Visible = false; var index = 1; var frm = new frmSplash(list.ToList().Count); frm.Show(owner); //Add column ws.Cells[1, 1] = "تاریخ ارسال"; ws.Cells[1, 2] = "کاربر ارسال کننده"; ws.Cells[1, 3] = "هزینه به ریال"; ws.Cells[1, 4] = "وضعیت"; ws.Cells[1, 5] = "متن ارسال شده"; foreach (var item in list) { index++; frm.Level = index; ws.Cells[index, 1] = item.DateSh; ws.Cells[index, 2] = item.UserName; ws.Cells[index, 3] = item.Cost.ToString("N0"); ws.Cells[index, 4] = item.StatusText; ws.Cells[index, 5] = item.Message; } ws.SaveAs(sfd.FileName, XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing); excel.Quit(); frm.Close(); } catch (Exception ex) { WebErrorLog.ErrorInstence.StartErrorLog(ex); } }
private void cmiExport_Click(object sender, EventArgs e) { if (lvDataviews.SelectedItems.Count > 0) { sfdExport.FileName = DateTime.Now.ToString("yyyy_MM_dd_"); if (lvDataviews.SelectedItems.Count == 1) { sfdExport.FileName += lvDataviews.SelectedItems[0].Text; } else { sfdExport.FileName += lvDataviews.SelectedItems.Count; } sfdExport.OverwritePrompt = true; sfdExport.SupportMultiDottedExtensions = true; if (DialogResult.OK == sfdExport.ShowDialog(this)) { var dvs = new List <string>(); var splash = new frmSplash(); foreach (ListViewItem lvi in lvDataviews.SelectedItems) { dvs.Add(lvi.Tag.ToString()); } splash.Show("Exporting " + dvs.Count + " dataview(s)...", false, this); processInBackground( (worker) => { var ds = AdminProxy.ExportDataViewDefinitions(dvs); BinaryFormatter bin = new BinaryFormatter(); using (StreamWriter sw = new StreamWriter(sfdExport.FileName)) { ds.RemotingFormat = SerializationFormat.Binary; bin.Serialize(sw.BaseStream, ds); } }, (worker2, e2) => { splash.ChangeText(getDisplayMember("export{working}", "Still working...")); }, (worker3, e3) => { splash.Close(); MainFormUpdateStatus(getDisplayMember("export{exported}", "Exported {0} dataview(s)", dvs.Count.ToString("###,##0")), true); }); } } }
/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> /// <history> /// [erosado] 21/04/2016 Created /// </history> protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); frmSplash frmSplash = new frmSplash(); var frmLogin = new frmLogin(frmSplash, changePassword: true, validatePermission: true, permission: EnumPermission.MailOutsTexts, permissionLevel: EnumPermisionLevel.ReadOnly); frmSplash.Show(); frmSplash.ShowLogin(ref frmLogin); if (frmLogin.IsAuthenticated) { Context.User = frmLogin.UserData; frmMailOutsTexts frmMain = new frmMailOutsTexts(); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.ShowDialog(); frmSplash.Close(); } }
/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> /// <history> /// [erosado] 01/06/2016 Modified. se agrego async /// </history> protected async override void OnStartup(StartupEventArgs e) { base.OnStartup(e); frmSplash frmSplash = new frmSplash(); frmLogin frmLogin = new frmLogin(frmSplash, EnumLoginType.Location, EnumProgram.Inhouse, changePassword: true, autoSign: true, permission: EnumPermission.Register, permissionLevel: EnumPermisionLevel.Standard); await frmLogin.getAllPlaces(); frmSplash.Show(); frmSplash.ShowLogin(ref frmLogin); if (frmLogin.IsAuthenticated) { Context.User = frmLogin.UserData; frmMailOuts frmMain = new frmMailOuts(); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.ShowDialog(); frmSplash.Close(); } }
/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); frmSplash frmSplash = new frmSplash(); frmLogin frmLogin = new frmLogin(frmSplash, changePassword: true, validatePermission: true, permission: EnumPermission.PRInvitations, permissionLevel: EnumPermisionLevel.Special); frmSplash.Show(); frmSplash.ShowLogin(ref frmLogin); if (frmLogin.IsAuthenticated) { EventManager.RegisterClassHandler(typeof(DataGrid), UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(dataGrid_MouseLeftButtonUp)); Context.User = frmLogin.UserData; frmPRStatistics frmMain = new frmPRStatistics(); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.ShowDialog(); frmSplash.Close(); } }
public static void UninstallExistingMsi(string exeOrMsiFullPath, FileDownloadInfo fdi, Form parentForm, bool silentMode, bool autoLogin, string password, bool useWindowsAuth) { var splash = new frmSplash(); try { var p = new Process(); if (fdi.ProductGuid == Guid.Empty && String.IsNullOrEmpty(fdi.UninstallString)) { // this FileDownloadInfo represents the 'new' installer file, and it was not looked up from the registry. var apps = Utility.ListInstalledApplications(); apps.TryGetValue(fdi.DisplayName, out fdi); // now, fdi represents the currently installed version info, meaning the uninstall info, if any, should be present. } if (fdi.ProductGuid != Guid.Empty) { splash.ChangeText(getDisplayMember("UninstallExistingMsi{start}", "Uninstalling version {0} of {1}, please be patient...", fdi.InstalledVersion, fdi.DisplayName)); //string logFileName = exeOrMsiFullPath + ".uninstall_log"; // "B" format in following line means: // 32 digits separated by hyphens, enclosed in brackets: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} //p.StartInfo = new ProcessStartInfo("msiexec.exe", " " + (silentMode ? " /passive " : "") + (autoLogin ? @" AUTOLOGIN=""TRUE"" " : "") + @" USEWINDOWSAUTH=""" + useWindowsAuth.ToString().ToUpper() + @""" PASSWORD=""" + password + @""" /L*v """ + logFileName + @""" /X" + fdi.ProductGuid.ToString("B")); var encPassword = Utility.EncryptText(password); p.StartInfo = new ProcessStartInfo("msiexec.exe", " " + (silentMode ? " /passive " : "") + (autoLogin ? @" AUTOLOGIN=""TRUE"" " : "") + @" USEWINDOWSAUTH=""" + useWindowsAuth.ToString().ToUpper() + @""" PASSWORD=""" + encPassword + @""" /X" + fdi.ProductGuid.ToString("B")); p.Start(); p.WaitForExit(); waitForMsiToFinish(parentForm, "/X" + fdi.ProductGuid.ToString("B")); // waitForMsiToFinish(parentForm, fdi.FileName ?? fdi.ProductGuid.ToString("B")); } else if (!String.IsNullOrEmpty(fdi.UninstallString)) { splash.ChangeText(getDisplayMember("UninstallExistingMsi{start}", "Uninstalling version {0} of {1}, please be patient...", fdi.InstalledVersion, fdi.DisplayName)); p.StartInfo = new ProcessStartInfo("cmd.exe", " /k " + fdi.UninstallString); p.Start(); p.WaitForExit(); } } finally { splash.Close(); } }
/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> /// <history> /// [aalcocer] 10/03/2016 Created /// </history> protected override async void OnStartup(StartupEventArgs e) { base.OnStartup(e); frmSplash frmSplash = new frmSplash(); Window frmLS = new frmLS(frmSplash); await((frmLS)frmLS).GetLeadSources(); frmSplash.Show(); frmSplash.ShowLogin(ref frmLS); if (((frmLS)frmLS).IsValidated) { LeadSource leadsource = ((frmLS)frmLS).LeadSource; frmGraph frmMain = new frmGraph(leadsource); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.ShowDialog(); frmSplash.Close(); } }
/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> /// [erosado] 23/Mar/2016 Created /// </history> protected async override void OnStartup(StartupEventArgs e) { base.OnStartup(e); frmSplash frmSplash = new frmSplash(); frmLogin frmLogin = new frmLogin(frmSplash, EnumLoginType.SalesRoom, changePassword: true, autoSign: true); await frmLogin.getAllPlaces(); frmSplash.Show(); frmSplash.ShowLogin(ref frmLogin); if (frmLogin.IsAuthenticated) { EventManager.RegisterClassHandler(typeof(DataGrid), UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(dataGrid_MouseLeftButtonUp)); Context.User = frmLogin.UserData; frmSalesCloser frmMain = new frmSalesCloser(); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.ShowDialog(); frmSplash.Close(); } }
/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> /// <history> /// [erosado] 01/06/2016 Modified. se agrego async /// </history> protected override async void OnStartup(StartupEventArgs e) { base.OnStartup(e); frmSplash frmSplash = new frmSplash(); frmLogin frmLogin = new frmLogin(frmSplash, EnumLoginType.Warehouse, validatePermission: true, permission: EnumPermission.GiftsReceipts, permissionLevel: EnumPermisionLevel.Standard, changePassword: true); await frmLogin.getAllPlaces(); frmSplash.Show(); frmSplash.ShowLogin(ref frmLogin); if (!frmLogin.IsAuthenticated) { return; } Context.User = frmLogin.UserData; frmInventoryMovements frmMain = new frmInventoryMovements(); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.ShowDialog(); frmSplash.Close(); }
/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> /// <history> /// [jorcanche] 11/04/2016 created /// [erosado] 01/06/2016 Modified. se agrego async /// </history> protected override async void OnStartup(StartupEventArgs e) { base.OnStartup(e); frmSplash frmSplash = new frmSplash(); frmLogin frmLogin = new frmLogin(frmSplash, EnumLoginType.Location, EnumProgram.Outhouse, true, changePassword: true, autoSign: true, permission: EnumPermission.PRInvitations, permissionLevel: EnumPermisionLevel.ReadOnly); await frmLogin.getAllPlaces(); frmSplash.Show(); frmSplash.ShowLogin(ref frmLogin); if (frmLogin.IsAuthenticated) { EventManager.RegisterClassHandler(typeof(DataGrid), UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(dataGrid_MouseLeftButtonUp)); Context.User = frmLogin.UserData; frmOuthouse frmMain = new frmOuthouse(); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.ShowDialog(); frmSplash.Close(); } }
/// <summary> /// Inicializa el modulo con el Login y el Splash /// </summary> /// <history> /// [jorcanche] 11/04/2016 created /// [erosado] 01/06/2016 Modified. se agrego async /// </history> protected async override void OnStartup(StartupEventArgs e) { base.OnStartup(e); frmSplash frmSplash = new frmSplash(); frmLogin frmLogin = new frmLogin(frmSplash, EnumLoginType.Normal, validatePermission: true, changePassword: true, permission: EnumPermission.HostInvitations, permissionLevel: EnumPermisionLevel.ReadOnly); await frmLogin.getAllPlaces(); frmSplash.Show(); frmSplash.ShowLogin(ref frmLogin); if (frmLogin.IsAuthenticated) { Context.User = frmLogin.UserData; frmInvitConfig frmMain = new frmInvitConfig(); frmMain.Title = $"{Context.Module} - [{Context.Environment}]"; frmMain.ShowDialog(); frmSplash.Close(); } }
private async void btnFinish_Click(object sender, EventArgs e) { try { if (DGrid.RowCount <= 0) { frmNotification.PublicInfo.ShowMessage("هیچ داده ای وجود ندارد"); cmbWithoutGroup.Focus(); return; } btnFinish.Enabled = btnCancel.Enabled = false; var frm = new frmSplash(DGrid.RowCount); frm.Show(this); for (var i = 0; i < DGrid.RowCount; i++) { var x = await GetItemsAsync(i); frm.Level = i; if (x == null) { continue; } await x.SaveAsync(); } DialogResult = DialogResult.OK; frm.Close(); Close(); } catch (Exception ex) { WebErrorLog.ErrorInstence.StartErrorLog(ex); } finally { btnFinish.Enabled = btnCancel.Enabled = true; } }
//Analza un mail recibido public void AnalizaMail(Outlook.MailItem mail) { int pos; string elSubject = mail.Subject.ToString(); string[] elBody; //Sincronización if ((pos = Strings.InStr(mail.Subject.ToString(), "Sincronizar:")) > 0) { //Por ahora no hago nada pues el handler del Evento lo copia para la carpeta MailEprende de todos modos... //Si la sincronización es manual no se necesita hacer nada aquí para sincronizar. 19-09-2013 } //Direcciones erróneas if ((pos = Strings.InStr(mail.Subject.ToString(), "Direcciones Erroneas")) > 0) { try { elBody = mail.Body.ToString().Trim().Split('|'); DateTime fecha = mail.ReceivedTime; correosDataSetTableAdapters.bad_mailTableAdapter taBadMail = new correosDataSetTableAdapters.bad_mailTableAdapter(); correosDataSetTableAdapters.usuariosTableAdapter taUsers = new correosDataSetTableAdapters.usuariosTableAdapter(); correosDataSetTableAdapters.accesoTableAdapter taAccess = new correosDataSetTableAdapters.accesoTableAdapter(); int NumBad = Convert.ToInt32(elBody[0]); int NumBorraBad = 0; string elBodyBad = ""; string elBodyBadAccess = ""; string unaDir = ""; string unaDir1 = ""; string unaDir2 = ""; //Consulto si está activo el borrado automático en los settings... Properties.Settings setting = new Properties.Settings(); //Creo variable para acceder a Settings y leer EmailAdmiin //Declaro borrado y preparo el correo para borrar arriba si está establecido el Check de borrado automático for (int i = 0; i < NumBad; i++) { //Tomo la dirección i-esima unaDir = elBody[i + 1]; //Para chequear los usuarios //La arreglo si está en una tupla de direcciones 01-10-2013 tanto de usuarios como de Accesos 08-05-2014 unaDir1 = (taUsers.GetCorreoLikeUnAddress(unaDir).Count > 0)? taUsers.GetCorreoLikeUnAddress(unaDir)[0].correo.ToString() : ""; unaDir2 = (taAccess.GetAccesoSegunCorreo(unaDir).Count > 0)? taAccess.GetAccesoSegunCorreo(unaDir)[0].correo.ToString():""; if (unaDir1 != "" || unaDir2 != "") //Si encontró una dirección { if ((bool)setting["Borrado_Auto_BadMail"])//Si está seteado borrar automático las dir erroneas { //Preparo para mandar a borrar direcciones y declaro borrado en USUARIO if (unaDir1 != "") //Si encontró una dirección en usuarios { taUsers.UpdateEstadoSegunCorreo("Borrado. Dirección rebotada", unaDir); NumBorraBad++; elBodyBad += unaDir + "|"; } //Preparo para mandar a borrar direcciones y declaro borrado en ACCESOS if (unaDir2 != "") //Si encontró una dirección en usuarios { setting = new Properties.Settings(); //Creo variable para acceder a Settings y leer EmailAdmiin string EmailDir = setting["Email_Admin"].ToString(); string EmailSubject = "eliminar-accesos"; taAccess.UpdateEstadoSegunCorreo("Borrado. Dirección rebotada", unaDir); elBodyBadAccess = taAccess.GetAccesoSegunCorreo(unaDir)[0].id_acceso.ToString() + "|"; Globals.ThisAddIn.SendEmailAddressSubjectBody(EmailDir, EmailSubject, elBodyBadAccess); //Si hay más de un acceso con la misma dir de Email se borra solo uno, el otro será en el próximo rebote } } //Escribo en la tabla bad_mail para que sea aconsultada cuando se quiera //Desde aquí se podrá mandar a borrar si se quiere. 07-04-2014 if (taBadMail.GetByCorreo(unaDir).Count == 0) //Si no está ya el correo { //inserto en la tabla bad_mail si el mail está en la tabla USERS if (taUsers.GetDataByUnCorreo(unaDir1).Count > 0 ) { taBadMail.Insert(unaDir, taUsers.GetDataByUnCorreo(unaDir)[0].nombre.ToString(), taUsers.GetDataByUnCorreo(unaDir)[0].apellido1.ToString(), fecha, 1); } //inserto en la tabla bad_mail si el mail está en la tabla ACCESOS if (taAccess.GetAccesoSegunCorreo(unaDir2).Count > 0) { try { taBadMail.Insert(unaDir, taAccess.GetAccesoSegunCorreo(unaDir)[0].nombre.ToString(), taAccess.GetAccesoSegunCorreo(unaDir)[0].apellido1.ToString(), fecha, 1); } catch { //Se captura la excepción de insersión duplicada de registro //Pero no se hace nada con ello, no es necesario } } } else //Si ya está en la tabla BadMail { taBadMail.UpdateNumRebotesSegunCorreo(Convert.ToInt32(taBadMail.GetByCorreo(unaDir)[0]["numrebotes"]) + 1, unaDir); //Sumo uno al número de rebotes taBadMail.UpdateFechaSegunCorreo(fecha, unaDir); //Actualizo la fecha del último rebote } }//Si consiguio la dirección de tupla o simple OK } //For que recorre los NumBad //El Correo if (NumBorraBad > 0 && (bool)setting["Borrado_Auto_BadMail"]) //Si encontré qué borrar y si está activo el borrado automático { setting = new Properties.Settings(); //Creo variable para acceder a Settings y leer EmailAdmiin string EmailDir = setting["Email_Admin"].ToString(); //Preparo y envío string EmailSubject = "eliminar-usuario"; string BodyBorrar = NumBorraBad.ToString() + "|" + elBodyBad; Globals.ThisAddIn.SendEmailAddressSubjectBody(EmailDir, EmailSubject, BodyBorrar); } /* La actual rutina de borrar accesos es borra uno a uno, así que los Emails se generan arriba if (NumBorraBadAccess > 0 && (bool)setting["Borrado_Auto_BadMail"]) //Si encontré qué borrar y si está activo el borrado automático*/ } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } } //Respuesta de comandos if ((pos = Strings.InStr(mail.Subject.ToString(), "Correcto")) > 0) { elSubject = mail.Subject.ToString().Split(' ')[1].Trim(); switch (elSubject) { //Limpiar el Estado en Accesos y Centros porque fue correcta la reconstrucción case "rehacer-bd": try { //Preparo variables de acceso a los TableAdapters correosDataSetTableAdapters.centroTableAdapter taCentrosCl = new correosDataSetTableAdapters.centroTableAdapter(); correosDataSetTableAdapters.accesoTableAdapter taAccesoCl = new correosDataSetTableAdapters.accesoTableAdapter(); correosDataSetTableAdapters.usuariosTableAdapter taUsuarios = new correosDataSetTableAdapters.usuariosTableAdapter(); correosDataSetTableAdapters.listaTableAdapter taListas = new correosDataSetTableAdapters.listaTableAdapter(); correosDataSetTableAdapters.usuario_listaTableAdapter taUsuarioListas = new correosDataSetTableAdapters.usuario_listaTableAdapter(); int ra = Strings.InStr(taCentrosCl.GetData()[0].estado.ToString(), "Rehacer"); if (ra > 0) //Si esta es la BD que mandó a Reahacer { taAccesoCl.LimpiarEstados(); taCentrosCl.LimpiarEstados(); } else //Si no estoy en la BD que mandó a Rehacer, entonces a serruchar { //Preparo separadores y variables numéricas string[] separators = new string[5]; int NumCentros, NumListas, NumAccesos, NumUsuarios, NumUsuarios_listas; string[] BodyCentros, BodyListas, BodyAccesos, BodyUsuarios, BodyUsuarios_listas; separators[0] = "Centros:"; separators[1] = "Listas:"; separators[2] = "Accesos:"; separators[3] = "Usuarios:"; separators[4] = "Usuarios_listas:"; //Obtengo los trozos del Body del mensaje que tienen los comando de creación elBody = mail.Body.ToString().Split(separators, StringSplitOptions.RemoveEmptyEntries); BodyCentros = elBody[0].Split('|'); BodyListas = elBody[1].Split('|'); BodyAccesos = elBody[2].Split('|'); BodyUsuarios = elBody[3].Split('|'); BodyUsuarios_listas = elBody[4].Split('|'); NumCentros = Convert.ToInt32(BodyCentros[0]); NumListas = Convert.ToInt32(BodyListas[0]); NumAccesos = Convert.ToInt32(BodyAccesos[0]); NumUsuarios = Convert.ToInt32(BodyUsuarios[0]); NumUsuarios_listas = Convert.ToInt32(BodyUsuarios_listas[0]); //Elimino las tablas Usuarios y Centros, con esto limpio todo taAccesoCl.DeleteAll(); taCentrosCl.DeleteAll(); taUsuarios.DeleteAll(); //Muestro el Splash (Nueva Instancia) OutlookAddInEmprende.frmSplash theSplashR = new frmSplash(); theSplashR.pbProgress.Step = 1; theSplashR.pbProgress.Value = 1; theSplashR.pbProgress.Maximum = NumAccesos+NumCentros+NumListas+NumUsuarios+NumUsuarios_listas; theSplashR.etAccion.Text = "Reconstruyendo la Base de Datos Local..."; theSplashR.pbProgress.ForeColor = System.Drawing.Color.Brown; theSplashR.Show(); System.Windows.Forms.Application.DoEvents(); //Ejecuto comandos de creación uno por uno //*************************************************** //Crear Centros: id centro|nombre del centro|correo| for (int i = 0; i < NumCentros; i++) { taCentrosCl.InsertUnCentro(Convert.ToInt32(Strings.Replace(BodyCentros[3 * i + 1], " ", "")), Strings.Replace(BodyCentros[3 * i + 2], " ", ""), Strings.Replace(BodyCentros[3 * i + 3], " ", ""), ""); theSplashR.pbProgress.PerformStep(); System.Windows.Forms.Application.DoEvents(); } //Crear Listas: id lista|nombre de la lista|ID del centro| for (int i = 0; i < NumListas; i++) { taListas.Insert(Convert.ToInt32(Strings.Replace(BodyListas[3 * i + 1], " ", "")), Strings.Replace(BodyListas[3 * i + 2], " ", ""), Convert.ToInt32(Strings.Replace(BodyListas[3 * i + 3], " ", "")), ""); theSplashR.pbProgress.PerformStep(); System.Windows.Forms.Application.DoEvents(); } //Crear Accesos: id acceso|correo|clave|nombre|1er apellido|2do apellido|id de la lista|id de tipo de usuario| for (int i = 0; i < NumAccesos; i++) { taAccesoCl.InsertUnAcceso(Convert.ToInt32(Strings.Replace(BodyAccesos[8 * i + 1], " ", "")), Strings.Replace(BodyAccesos[8 * i + 2], " ", ""), Strings.Replace(BodyAccesos[8 * i + 3], " ", ""), BodyAccesos[8 * i + 4], BodyAccesos[8 * i + 5], BodyAccesos[8 * i + 6], Convert.ToInt32(Strings.Replace(BodyAccesos[8 * i + 7], " ", "")), Convert.ToInt32(Strings.Replace(BodyAccesos[8 * i + 8], " ", "")), ""); theSplashR.pbProgress.PerformStep(); System.Windows.Forms.Application.DoEvents(); } //Crear Usuarios for (int i = 0; i < NumUsuarios; i++) { taUsuarios.InsertUnUsuario(Strings.Replace(BodyUsuarios[4 * i + 1]," ",""), BodyUsuarios[4 * i + 2], BodyUsuarios[4 * i + 3], BodyUsuarios[4 * i + 4], ""); theSplashR.pbProgress.PerformStep(); System.Windows.Forms.Application.DoEvents(); } //Crear Usuario-Lista for (int i = 0; i < NumUsuarios_listas ; i++) { try { taUsuarioListas.InsertUsuario_Lista(Convert.ToInt32(Strings.Replace(BodyUsuarios_listas[2 * i + 2]," ","")), Strings.Replace(BodyUsuarios_listas[2 * i + 1]," ",""), ""); theSplashR.pbProgress.PerformStep(); System.Windows.Forms.Application.DoEvents(); } catch { //Evita que explote por un error de no coinsidencia de clave, no se hace nada //Los usuarios quedarían entonces "sueltos" } } theSplashR.Close(); } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "crear-accesos": case "editar-accesos": //id acceso|correo|clave|nombre|1er apellido|2do apellido|id de la lista|id de tipo de usuario| ** try { elBody = mail.Body.ToString().Trim().Split('|'); correosDataSetTableAdapters.accesoTableAdapter taAcceso = new correosDataSetTableAdapters.accesoTableAdapter(); if (taAcceso.GetAccesoSegunCorreo(elBody[1]).Count > 0) //Si ya está lo actualizo { taAcceso.UpdateUnAcceso(elBody[1],elBody[2],elBody[3],elBody[4],elBody[5],Convert.ToInt32(elBody[6]), Convert.ToInt32(elBody[7]),"",elBody[1]); } else //Si no lo inserto { taAcceso.InsertUnAcceso(Convert.ToInt32(elBody[0]), elBody[1], elBody[2], elBody[3], elBody[4], elBody[5], Convert.ToInt32(elBody[6]), Convert.ToInt32(elBody[7]), ""); } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "eliminar-accesos": //Cuerpo: id acceso| ** try { elBody = mail.Body.ToString().Trim().Split('|'); correosDataSetTableAdapters.accesoTableAdapter taAcceso = new correosDataSetTableAdapters.accesoTableAdapter(); taAcceso.DeleteUnAccesoByID(Convert.ToInt32(elBody[0])); } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "enviar-correo": string[] sep = new string[1]; sep[0] = "ID:"; //Extraigo el ID y si no está lo escribo en la tabla string consec = mail.Subject.ToString().Split( sep ,StringSplitOptions.RemoveEmptyEntries)[1].Trim(); correosDataSetTableAdapters.consecutivoTableAdapter taConsecutivo = new correosDataSetTableAdapters.consecutivoTableAdapter(); if (taConsecutivo.CuantosHay(consec) == 0) { taConsecutivo.InserUnConsecutivo(consec); } break; case "crear-centro": case "editar-centro": //cuerpo: id centro|nombre del centro|correo| ** try { elBody = mail.Body.ToString().Trim().Split('|'); correosDataSetTableAdapters.centroTableAdapter taCentros = new correosDataSetTableAdapters.centroTableAdapter(); if (taCentros.GetCentroBySoloID(Convert.ToInt32(elBody[0])).Count > 0) //si ya está el centro { correosDataSetTableAdapters.centroTableAdapter taCentro = new correosDataSetTableAdapters.centroTableAdapter(); taCentro.SetUnCentro(elBody[1], "", elBody[2], Convert.ToInt32(elBody[0])); } else //si no esta el centro { taCentros.InsertUnCentro(Convert.ToInt32(elBody[0]), elBody[1], elBody[2], ""); } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "eliminar-centro": //cuerpo: ID del centro|** try { elBody = mail.Body.ToString().Trim().Split('|'); correosDataSetTableAdapters.centroTableAdapter taCentro = new correosDataSetTableAdapters.centroTableAdapter(); taCentro.DeleteUnCentro(Convert.ToInt32(elBody[0])); } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "crear-lista": case "editar-lista": //cuerpo: id lista|nombre de la lista|ID del centro| ** try { elBody = mail.Body.ToString().Trim().Split('|'); correosDataSetTableAdapters.listaTableAdapter taLista = new correosDataSetTableAdapters.listaTableAdapter(); if (taLista.GetListaByID(Convert.ToInt32(elBody[0])).Count > 0) //Si está la lista { taLista.UpdateUnaLista(elBody[1], "", Convert.ToInt32(elBody[0])); } else //Si no está la lista { taLista.Insert(Convert.ToInt32(elBody[0]), elBody[1], Convert.ToInt32(elBody[2]),""); } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "eliminar-lista": //Cuerpo: Id lista| ** try { elBody = mail.Body.ToString().Trim().Split('|'); correosDataSetTableAdapters.listaTableAdapter taLista = new correosDataSetTableAdapters.listaTableAdapter(); taLista.DeleteUnaLista(Convert.ToInt32(elBody[0])); } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "crear-usuario": //cant_usuarios|correo|nombre|1er apellido|2do apellido| ** //ejem: 2|[email protected]|mario|gles|mtinez|[email protected]|jose|ramirez|prieto| try { string elCorreo = ""; elBody = mail.Body.ToString().Trim().Split('|'); taUsuarios = new correosDataSetTableAdapters.usuariosTableAdapter(); int Num = Convert.ToInt32(elBody[0]); for (int i = 0; i<Num; i++) { elCorreo = elBody[4*i + 1]; if (taUsuarios.GetDataByUnCorreo(elCorreo).Count > 0) //Si está el correo { taUsuarios.UpdateEstadoSegunCorreo("", elCorreo); //Reseteo su estado } else //Si no está lo inserto { taUsuarios.InsertUnUsuario(elCorreo, elBody[4 * i + 2], elBody[4 * i + 3], elBody[4 * i + 4], ""); } } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "editar-usuario": //correo_old|correo_new|nombre|1er apellido|2do apellido| ** try { elBody = mail.Body.ToString().Trim().Split('|'); taUsuarios = new correosDataSetTableAdapters.usuariosTableAdapter(); if (taUsuarios.GetDataByUnCorreo(elBody[1]).Count > 0) //Si el correo nuevo está { taUsuarios.UpdateUsuarioSegunCorreo(elBody[2],elBody[3],elBody[4],"",elBody[1]); //Actualizo todo menos el correo } //Si el correo viejo es el que está, y no está el nuevo, actualizo cambiando el correo. if (taUsuarios.GetDataByUnCorreo(elBody[0]).Count > 0 && taUsuarios.GetDataByUnCorreo(elBody[1]).Count ==0) { taUsuarios.UpdateUsuarioSegunCorreoIncCorreo(elBody[1],elBody[2], elBody[3], elBody[4], "", elBody[0]); //Actualizo todo } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "editar-usuario-listas": //cuerpo: cant_listas|correo_old|correo_new|nombre|1er apellido|2do apellido|id_lista|id_lista| --** //ejem: 2|[email protected]|[email protected]|Pedro|Pérez|García|7|8| try { elBody = mail.Body.ToString().Trim().Split('|'); taUsuarios = new correosDataSetTableAdapters.usuariosTableAdapter(); correosDataSetTableAdapters.usuario_listaTableAdapter taUsuarioLista = new correosDataSetTableAdapters.usuario_listaTableAdapter(); if(taUsuarios.GetDataByUnCorreo(elBody[1]).Count > 0) //Si el correo_old estaba, lo borro { taUsuarios.DeleteSegunCorreo(elBody[1]); //Borro el correoOld no importa si no está } if (taUsuarios.GetDataByUnCorreo(elBody[2]).Count > 0) //Si ya esta creado el correo_new { taUsuarios.UpdateUsuarioSegunCorreo(elBody[3],elBody[4],elBody[5],"", elBody[2]); //Actualizo los parámetros del usuaro //Ahora actualizo Usuario Lista, actualizando el Estado en este caso int Num = Convert.ToInt32(elBody[0]); //Tomo el número de listas for (int i = 0; i < Num; i++) { if (taUsuarioLista.GetDataByListaYMail(Convert.ToInt32(elBody[i + 6]),elBody[2]).Count > 0 ) //Si el usuario-lista ya está creado { taUsuarioLista.UpdateEstadoSegunIDListaYCorreo("", Convert.ToInt32(elBody[i + 6]), elBody[2]); } else //si el usuario-lista no estaba, lo creo en estado sincronizado { taUsuarioLista.InsertUsuario_Lista(Convert.ToInt32(elBody[i + 6]), elBody[2], ""); } } } else //si no estaba creado el correo_new { taUsuarios.InsertUnUsuario(elBody[2], elBody[3], elBody[4], elBody[5], ""); //Ahora actualizo Usuario Lista, creando en este caso int Num = Convert.ToInt32(elBody[0]); //Tomo el número de listas for (int i = 0; i < Num; i++) { taUsuarioLista.InsertUsuario_Lista(Convert.ToInt32(elBody[i + 6]), elBody[2],""); } } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "eliminar-usuario": //Cuerpo: cant_usuarios|correo| y tantos usuarios como cant_usuarios de forma seguida ** //ejem: 2|[email protected]|[email protected]| try { elBody = mail.Body.ToString().Trim().Split('|'); taUsuarios = new correosDataSetTableAdapters.usuariosTableAdapter(); for(int i = 0; i < Convert.ToInt32(elBody[0]); i++) { taUsuarios.DeleteSegunCorreo(elBody[i+1]); } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "crear-usuario-lista": //Cuerpo: cant_usuarios|correo|id de la lista| y tantos usuarios como cant_usuarios de forma seguida ** //Implica que los usuarios ya están creados en la BD, sólo se asocian con listas //ejem: 2|[email protected]|1|[email protected]|1| try { elBody = mail.Body.ToString().Trim().Split('|'); correosDataSetTableAdapters.usuario_listaTableAdapter taUsuariosLista = new correosDataSetTableAdapters.usuario_listaTableAdapter(); for (int i = 0; i < Convert.ToInt32(elBody[0]); i++) { if (taUsuariosLista.GetDataByListaYMail(Convert.ToInt32(elBody[2 * i + 2]),elBody[2 * i + 1]).Count > 0) //Si está el usuario lista actualizo el estado { taUsuariosLista.UpdateEstadoSegunIDListaYCorreo("", Convert.ToInt32(elBody[2 * i + 2]), elBody[2 * i + 1]); } else //Si no está lo creo { taUsuariosLista.InsertUsuario_Lista(Convert.ToInt32(elBody[2 * i + 2]), elBody[2 * i + 1], ""); } } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "crear-usuario-usuario-lista": //cuerpo: cant_usuarios|correo|nombre|apellido1|apellido2|id lista| y tantos usuarios como cant_usuarios de forma seguida ** //ejem: 2|[email protected]|mario|gles|mtinez|2|[email protected]|jose|ramirez|prieto|1| try { elBody = mail.Body.ToString().Trim().Split('|'); taUsuarios = new correosDataSetTableAdapters.usuariosTableAdapter(); correosDataSetTableAdapters.usuario_listaTableAdapter taUsuariosLista = new correosDataSetTableAdapters.usuario_listaTableAdapter(); for (int i = 0; i < Convert.ToInt32(elBody[0]); i++) { //El usuario if (taUsuarios.GetDataByUnCorreo(elBody[5 * i + 1]).Count > 0) //si está el usuario actualizo el estado { taUsuarios.UpdateEstadoSegunCorreo("", elBody[5 * i + 1]); } else //No está, lo creo { taUsuarios.InsertUnUsuario(elBody[5 * i + 1], elBody[5 * i + 2], elBody[5 * i + 3], elBody[5 * i + 4], ""); } //El usuario-lista if (taUsuariosLista.GetDataByListaYMail(Convert.ToInt32(elBody[5 * i + 5]), elBody[5 * i + 1]).Count > 0) //si está el usuario-lista, actualizo el estado { taUsuariosLista.UpdateEstadoSegunIDListaYCorreo("", Convert.ToInt32(elBody[5 * i + 5]), elBody[5 * i + 1]); } else //Si no está lo creo { taUsuariosLista.InsertUsuario_Lista(Convert.ToInt32(elBody[5 * i + 5]), elBody[5 * i + 1], ""); } } //For que recorre la lista de comandos del body } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "eliminar-usuario-lista": //Cuerpo: cant_usuarios|correo|id de la lista| y tantos usuarios como cant_usuarios de forma seguida ** //ejem: 2|[email protected]|1|[email protected]|1| try { elBody = mail.Body.ToString().Trim().Split('|'); correosDataSetTableAdapters.usuario_listaTableAdapter taUsuariosLista = new correosDataSetTableAdapters.usuario_listaTableAdapter(); for (int i = 0; i < Convert.ToInt32(elBody[0]); i++) { taUsuariosLista.DeleteUnUsuarioLista(Convert.ToInt32(elBody[2 * i + 2]), elBody[2 * i + 1]); } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; case "mover-usuario-lista": //Cuerpo: cant_usuarios|correo|id de la lista vieja|id lista nueva| y tantos usuarios como cant_usuarios de forma seguida //ejem: 2|[email protected]|1|3|[email protected]|1|4| try { elBody = mail.Body.ToString().Trim().Split('|'); correosDataSetTableAdapters.usuario_listaTableAdapter taUsuariosLista = new correosDataSetTableAdapters.usuario_listaTableAdapter(); for (int i = 0; i < Convert.ToInt32(elBody[0]); i++) { if (taUsuariosLista.EstaEnLista(Convert.ToInt32(elBody[3 * i + 3]), elBody[3 * i + 1]) == 0) { taUsuariosLista.MuevePertenenciaALista(Convert.ToInt32(elBody[3 * i + 3]), "", Convert.ToInt32(elBody[3 * i + 2]), elBody[3 * i + 1]); } else { //Si ya estaba en la otra lista reseteo el estado taUsuariosLista.UpdateEstadoSegunIDListaYCorreo("", Convert.ToInt32(elBody[3 * i + 3]), elBody[3 * i + 1]); } } } catch (Exception ex) { if (Strings.InStr(Problemas, "satisfactoria") > 0) Problemas = ""; Problemas += elSubject + ": " + mail.Body.ToString() + ". Registró: " + "\n" + ex.Message.ToString(); } break; }//Switch elSubjec } }
public override void Install(IDictionary stateSaver) { base.Install(stateSaver); var splash = new frmSplash(); try { string targetDir = Utility.GetTargetDirectory(Context, stateSaver, "Web Application"); string gguacPath = Toolkit.ResolveFilePath(targetDir + @"\gguac.exe", false); //MessageBox.Show("config file=" + configFile); splash.ChangeText(getDisplayMember("Install{extracting}", "Extracting bundled files...")); var utility64CabPath = Toolkit.ResolveFilePath(targetDir + @"\utility64.cab", false); var utility64ExePath = Toolkit.ResolveFilePath(targetDir + @"\ggutil64.exe", false); var tempPath = Utility.GetTempDirectory(100); if (!File.Exists(utility64ExePath)) { if (File.Exists(utility64CabPath)) { // wipe out any existing utility64.exe file in the temp folder var extracted = Toolkit.ResolveFilePath(tempPath + @"\ggutil64.exe", false); if (File.Exists(extracted)) { File.Delete(extracted); } // extract it from our cab var cabOutput = Utility.ExtractCabFile(utility64CabPath, tempPath, gguacPath); // move it to the final target path (we can't do this up front because expand.exe tells us "can't expand cab file over itself" for some reason. if (File.Exists(extracted)) { File.Move(extracted, utility64ExePath); } } } // update the config file... string configFile = Toolkit.ResolveFilePath(targetDir + @"\web.config", false); if (File.Exists(configFile)) { splash.ChangeText(getDisplayMember("Install{verifying}", "Verifying database connection...")); string superUserPassword = Utility.GetSuperUserPassword(Context, stateSaver); bool? useWindowsAuth = Utility.GetUseWindowsAuthentication(Context, stateSaver); DatabaseEngineUtil dbEngineUtil = promptForDatabaseConnectionInfo(splash, ref superUserPassword, ref useWindowsAuth); createDatabaseUser(splash, dbEngineUtil, superUserPassword, "gg_user", "PA55w0rd!"); string connectionString = null; if (useWindowsAuth == true) { connectionString = dbEngineUtil.GetDataConnectionSpec("gringlobal", null, null).ConnectionString; } else { connectionString = dbEngineUtil.GetDataConnectionSpec("gringlobal", "gg_user", "PA55w0rd!").ConnectionString; } EventLog.WriteEntry("GRIN-Global Web Application", "Database connection string=" + connectionString, EventLogEntryType.Information); splash.ChangeText(getDisplayMember("Install{writingconfig}", "Writing configuration file...")); string contents = File.ReadAllText(configFile); string appSetting = @"<add providerName=""__ENGINE__"" name=""DataManager"" connectionString=""__CONNECTION_STRING__"" />".Replace("__ENGINE__", dbEngineUtil.EngineName).Replace("__CONNECTION_STRING__", connectionString); contents = contents.Replace("<!-- __CONNECTIONSTRING__ -->", appSetting); contents = contents.Replace("<!-- __COMMENT__ -->", "<!-- TESTING "); contents = contents.Replace("<!-- __ENDCOMMENT__ -->", " -->"); File.WriteAllText(configFile, contents); } // give ASPNET user full control to the ~/uploads folder splash.ChangeText(getDisplayMember("Install{settingperms}", "Setting permissions on uploads folder...")); assignFolderPermissions(Utility.ResolveDirectoryPath(targetDir + @"\uploads", true)); } catch (Exception ex) { MessageBox.Show(getDisplayMember("Install{failed}", "Error: {0}", ex.Message)); throw; } finally { splash.Close(); } }
public Form1(string[] args) { frmSplash splash = new frmSplash(); splash.Show(); System.Windows.Forms.Application.DoEvents(); InitializeComponent(); addWizTuneFilePacks(); // Only have this enabled in debug mode until ready this.barButtonItem29.Visibility = DevExpress.XtraBars.BarItemVisibility.Always; try { RegistryKey TempKeyCM = null; TempKeyCM = Registry.ClassesRoot.CreateSubKey(@"SystemFileAssociations\.bin\shell\Edit in T8 Suite\command"); string StartKey = System.Windows.Forms.Application.ExecutablePath + " \"%1\""; TempKeyCM.SetValue("", StartKey); TempKeyCM.Close(); } catch (Exception E) { logger.Debug(E.Message); } try { RegistryKey TempKeyCM = null; TempKeyCM = Registry.ClassesRoot.CreateSubKey(@"SystemFileAssociations\.bin\shell\Auto detect Trionic file type\command"); string StartKey = System.Windows.Forms.Application.StartupPath + "\\SuiteLauncher.exe" + " \"%1\""; TempKeyCM.SetValue("", StartKey); TempKeyCM.Close(); } catch (Exception E) { logger.Debug(E.Message); } if (args.Length > 0) { if (args[0].ToString().ToUpper().EndsWith(".BIN")) { if (File.Exists(args[0].ToString())) { m_startFromCommandLine = true; m_commandLineFile = args[0].ToString(); } } } try { m_DelegateStartReleaseNotePanel = new DelegateStartReleaseNotePanel(this.StartReleaseNotesViewer); m_DelegateUpdateRealTimeValue = new DelegateUpdateRealTimeValue(this.UpdateRealtimeInformationValue); } catch (Exception E) { logger.Debug(E.Message); } try { sndplayer = new System.Media.SoundPlayer(); t8can.onReadProgress += new ITrionic.ReadProgress(t8can_onReadProgress); t8can.onWriteProgress += new ITrionic.WriteProgress(t8can_onWriteProgress); t8can.onCanInfo += new ITrionic.CanInfo(t8can_onCanInfo); } catch (Exception E) { logger.Debug(E.Message); } splash.Close(); }
public static void Export(IEnumerable <PeoplesBussines> list, IWin32Window owner) { try { var sfd = new SaveFileDialog() { Filter = "Excel Files|*.xls" }; if (sfd.ShowDialog(owner) != DialogResult.OK) { return; } var excel = new Microsoft.Office.Interop.Excel.Application(); var wb = excel.Workbooks.Add(XlSheetType.xlWorksheet); var ws = (Worksheet)excel.ActiveSheet; excel.Visible = false; var index = 1; var frm = new frmSplash(list.ToList().Count); frm.Show(owner); //Add column ws.Cells[1, 1] = "کد شخص"; ws.Cells[1, 2] = "عنوان"; ws.Cells[1, 3] = "کدملی"; ws.Cells[1, 4] = "ش شناسنامه"; ws.Cells[1, 5] = "نام پدر"; ws.Cells[1, 6] = "محل تولد"; ws.Cells[1, 7] = "تاریخ تولد"; ws.Cells[1, 8] = "آدرس"; ws.Cells[1, 9] = "کدپستی"; ws.Cells[1, 10] = "مانده اول دوره"; ws.Cells[1, 11] = "مانده فعلی"; ws.Cells[1, 12] = "وضعیت حساب"; foreach (var item in list) { index++; frm.Level = index; ws.Cells[index, 1] = item.Code; ws.Cells[index, 2] = item.Name; ws.Cells[index, 3] = item.NationalCode; ws.Cells[index, 4] = item.IdCode; ws.Cells[index, 5] = item.FatherName; ws.Cells[index, 6] = item.PlaceBirth; ws.Cells[index, 7] = item.DateBirth; ws.Cells[index, 8] = item.Address; ws.Cells[index, 9] = item.PostalCode; ws.Cells[index, 10] = item.AccountFirst.ToString("N0"); ws.Cells[index, 11] = item.Account_.ToString("N0"); if (item.Account == 0) { ws.Cells[index, 12] = "بی حساب"; } if (item.Account > 0) { ws.Cells[index, 12] = "بدهکار"; } if (item.Account < 0) { ws.Cells[index, 12] = "بستانکار"; } } ws.SaveAs(sfd.FileName, XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing); excel.Quit(); frm.Close(); } catch (Exception ex) { WebErrorLog.ErrorInstence.StartErrorLog(ex); } }
public void main() { //===================================================================== // Procedure Name : Main // Parameters Passed : None // Returns : None // Purpose : Start of the software // Description : // Assumptions : // Dependencies : // Author : Deepak B. // Created : 05.09.06 // Revisions : //===================================================================== //'note: //'this is first starting point of software //'this is a function which called first. //'do some software initialisation step here. //'like checking for user, checking for dependencies etc. frmSplash objfrmSplashScreen = new frmSplash(); frmAASInitialisation objfrmAASInitialisation; bool blnResetCmd = false; string strPath; clsTimer objTimeDelay = new clsTimer(null, 5000); bool blnIsUpgradeSessionID; try { //---Initialize error handler subErrorHandlerInitialization(gobjErrorHandler); //'Added by pankaj on 29 Jan 08 INI_SETTINGS_PATH = Application.StartupPath + "\\AAS.ini"; //---Initialize database settings if (funcInitializeAppDatabaseSettings() == true) { //---read configuration settings if (!gobjHardwareLock.gfuncGetConfigurationSetting()) { //display msg -error in configuration settings initialization gobjMessageAdapter.ShowMessage(constConfigurationError); Application.DoEvents(); //'allow application to perfrom its panding work. System.Environment.Exit(0); } } else { //---display msg -error in database initialization gobjMessageAdapter.ShowMessage("AAS ini Error", "Error", MessageHandler.clsMessageHandler.enumMessageType.ErrorMessage); Application.DoEvents(); System.Environment.Exit(0); } //'--------- //---Display Splash screen objfrmSplashScreen.Show(); //'put a delay of 3000 for splash screen. //Call objTimeDelay.subTime_Delay(2000) Application.DoEvents(); //'now allow application to perfrom its panding work ////----- Added by Sachin Dokhale //objTimeDelay = Nothing ////----- //'--- Check for the previous instance of the application if (PrevInstance()) { //'this function will find that ,is there any other instance of software is running //'or not.If running then prompt a message. gobjMessageAdapter.ShowMessage("Application Busy", "One instance of the application is already running" + vbCrLf + "Please close the previous instance", EnumMessageType.Information); System.Environment.Exit(0); } objTimeDelay.subTime_Delay(2000); objTimeDelay = null; Application.DoEvents(); //--------------- //INI_SETTINGS_PATH = Application.StartupPath & "\AAS.ini" //'---Initialize database settings //If funcInitializeAppDatabaseSettings() = True Then // '---read configuration settings // If Not gobjHardwareLock.gfuncGetConfigurationSetting() Then // 'display msg -error in configuration settings initialization // Call gobjMessageAdapter.ShowMessage(constConfigurationError) // Call Application.DoEvents() // ''allow application to perfrom its panding work. // End // End If //Else // '---display msg -error in database initialization // Call gobjMessageAdapter.ShowMessage("AAS ini Error", "Error", MessageHandler.clsMessageHandler.enumMessageType.ErrorMessage) // Call Application.DoEvents() // End //End If //--------- //--path of AAS.ini file //INI_SETTINGS_PATH = Application.StartupPath & "\AAS.ini" //---Initialize database settings //If funcInitializeAppDatabaseSettings() = True Then // '---read configuration settings // If Not gobjHardwareLock.gfuncGetConfigurationSetting() Then // 'display msg -error in configuration settings initialization // Call gobjMessageAdapter.ShowMessage(constConfigurationError) // Call Application.DoEvents() // ''allow application to perfrom its panding work. // End // End If //Else // '---display msg -error in database initialization // Call gobjMessageAdapter.ShowMessage("AAS ini Error", "Error", MessageHandler.clsMessageHandler.enumMessageType.ErrorMessage) // Call Application.DoEvents() // End //End If //---read hardware lock settings if (gobjHardwareLock.gfuncReadHardwareLockSetting() == false) { if (!IsNothing(objfrmSplashScreen)) { objfrmSplashScreen.Close(); objfrmSplashScreen.Dispose(); objfrmSplashScreen = null; } gobjMessageAdapter.ShowMessage("Hardware Lock Error", "Error", MessageHandler.clsMessageHandler.enumMessageType.ErrorMessage); //'prompt a error message if hardware lock failed. System.Environment.Exit(0); } //==========*********Modified by Saurabh**********========= if (gstructSettings.AppMode == EnumAppMode.DemoMode) { //--- To Get A New session ID and write it back to INI file. funcGetSessionID(); //--- To Create Service LogBook Database Connection. gfuncCreateLogBookConnection(); //--- To Create Userinfo Database Connection. gfuncCreateUserInfoConnection(); //---Insert new row with new sessionsID and //---insert current Date , time and day funcInsertLogData(gstructUserDetails.SessionID); } else { //--- To Get A New session ID and write it back to INI file. funcGetSessionID(); gfuncCreateLogBookConnection(); gfuncCreateUserInfoConnection(); gSetInstrumentStartTime = System.DateTime.Now; gSetWStartTime = System.DateTime.Now; gSetD2StartTime = System.DateTime.Now; } //========================================================= //--close and dispose splash screen if (!IsNothing(objfrmSplashScreen)) { objfrmSplashScreen.Close(); Application.DoEvents(); objfrmSplashScreen.Dispose(); objfrmSplashScreen = null; } //Saurabh 31.07.07 to Check for Hydride Mode //---if application is already in hydride mode then display message box. if (gstructSettings.HydrideMode == 1) { gobjMessageAdapter.ShowMessage("HYDRIDE MODE", "CONFIGURATION", MessageHandler.clsMessageHandler.enumMessageType.InformativeMessage); Application.DoEvents(); } //Saurabh 31.07.07 to Check for Hydride Mode if (gstructSettings.Enable21CFR == true) { //'check for 21 CFR frmLogin objfrmLogin = new frmLogin(); if (objfrmLogin.ShowDialog() == DialogResult.OK) { Application.DoEvents(); //If objfrmLogin.DialogResult = DialogResult.OK Then if (!objfrmLogin.LoginSuccessfull) { return; } } else { System.Environment.Exit(0); } Application.DoEvents(); } //'get a application path string strConfigPath; strConfigPath = Application.ExecutablePath; strConfigPath = Right(strConfigPath, Len("AAS_Service.exe")); //---check which executable file to run if (UCase(strConfigPath) == UCase("AAS_Service.exe")) { //'for normal application gstructSettings.EnableServiceUtility = true; gstructSettings.ExeToRun = EnumApplicationMode.ServiceUtility; } else { //'for service utility gstructSettings.EnableServiceUtility = false; gstructSettings.ExeToRun = EnumApplicationMode.AAS; } //---Initialize all global Variable here gobjCommProtocol = new clsCommProtocolFunctions(); gobjfrmStatus = new frmStatus(); //--- Get the global variables from AAS.ini file gFuncLoadGlobals(); //---Initialize gobjinst object if (funcInitInstrumentSettings() == true) { if (gstructSettings.AppMode == EnumAppMode.DemoMode | gstructSettings.AppMode == EnumAppMode.DemoMode_201 | gstructSettings.AppMode == EnumAppMode.DemoMode_203D) { //---if demo mode then load gobjinst object from serialized file funcLoadInstStatus(); } } string strAANameVersion; bool blnFlag; if (gstructSettings.ExeToRun == EnumApplicationMode.ServiceUtility) { //blnFlag = gobjCommProtocol.funcInitInstrument() blnFlag = true; } else { if (gstructSettings.AppMode == EnumAppMode.FullVersion_203 | gstructSettings.AppMode == EnumAppMode.FullVersion_203D | gstructSettings.AppMode == EnumAppMode.FullVersion_201) { //'check for the real mode of application //If Not gstructSettings.EnableServiceUtility Then 'ToChange objfrmAASInitialisation = new frmAASInitialisation(); //'show the initialization form and start the initialization here objfrmAASInitialisation.Show(); if (objfrmAASInitialisation.funcInstrumentInitialization()) { //'start the initialization //objfrmAASInitialisation.Close() //objfrmAASInitialisation.Dispose() } else { objfrmAASInitialisation.Close(); objfrmAASInitialisation.Dispose(); System.Environment.Exit(0); return; } //Else //End If } } Application.DoEvents(); //---Load the Methods from serialized file. if (!funcLoadMethods()) { //---display Msg -error in loading methods //---commented on 10.04.09 for ver 4.85 //Call gobjMessageAdapter.ShowMessage("Error in loading method settings file.", "Error", MessageHandler.clsMessageHandler.enumMessageType.ErrorMessage) //Call Application.DoEvents() //---------------- //End } //---commented on 19.06.07 //'check for the demo mode of application. if (gstructSettings.AppMode == EnumAppMode.DemoMode) { gintInstrumentBeamType = AAS203Library.Instrument.enumInstrumentBeamType.SingleBeam; } else if (gstructSettings.AppMode == EnumAppMode.DemoMode_203D) { gintInstrumentBeamType = AAS203Library.Instrument.enumInstrumentBeamType.DoubleBeam; } else if (gstructSettings.AppMode == EnumAppMode.DemoMode_201) { } //Saurabh 28.07.07 To set Instrument title //'set the instrument title as par application mode. //--4.85 14.04.09 if (gstructSettings.NewModelName == false) { if (gstructSettings.AppMode == EnumAppMode.FullVersion_203) { gstrTitleInstrumentType = CONST_AA203_FullVersion; } else if (gstructSettings.AppMode == EnumAppMode.FullVersion_203D) { gstrTitleInstrumentType = CONST_AA203D_FullVersion; } else if (gstructSettings.AppMode == EnumAppMode.FullVersion_201) { gstrTitleInstrumentType = CONST_AA201_FullVersion; } else if (gstructSettings.AppMode == EnumAppMode.DemoMode) { gstrTitleInstrumentType = CONST_AA203_DemoVersion; } else if (gstructSettings.AppMode == EnumAppMode.DemoMode_203D) { gstrTitleInstrumentType = CONST_AA203D_DemoVersion; } else if (gstructSettings.AppMode == EnumAppMode.DemoMode_201) { gstrTitleInstrumentType = CONST_AA201_DemoVersion; } else { gstrTitleInstrumentType = CONST_AA203; } } else { if (gstructSettings.AppMode == EnumAppMode.FullVersion_203) { gstrTitleInstrumentType = CONST_AA303_FullVersion; } else if (gstructSettings.AppMode == EnumAppMode.FullVersion_203D) { gstrTitleInstrumentType = CONST_AA303D_FullVersion; } else if (gstructSettings.AppMode == EnumAppMode.FullVersion_201) { gstrTitleInstrumentType = CONST_AA301_FullVersion; } else if (gstructSettings.AppMode == EnumAppMode.DemoMode) { gstrTitleInstrumentType = CONST_AA303_DemoVersion; } else if (gstructSettings.AppMode == EnumAppMode.DemoMode_203D) { gstrTitleInstrumentType = CONST_AA303D_DemoVersion; } else if (gstructSettings.AppMode == EnumAppMode.DemoMode_201) { gstrTitleInstrumentType = CONST_AA301_DemoVersion; } else { gstrTitleInstrumentType = CONST_AA303_FullVersion; } } //--4.85 14.04.09 //Saurabh 28.07.07 To set Instrument title if (gstructSettings.EnableServiceUtility) { //'this will check which EXE to be run. either main exe or service exe. gobjMainService = new frmMDIMainService(); Application.Run(gobjMainService); } else { gobjMain = new frmMDIMain(); if (!objfrmAASInitialisation == null) { objfrmAASInitialisation.Close(); objfrmAASInitialisation.Dispose(); } Application.DoEvents(); Application.Run(gobjMain); } funcExitApplicationSettings(); //'fir deinitialise the application setting //'It Exit Application parameters gIntMethodID = 0; //---added by deepak on 19.07.07 to reset the instrument ////----- Modified by Sachin Dokhale if (gobjCommProtocol.mobjCommdll.gFuncIsPortOpen()) { ////----- gobjCommProtocol.funcResetInstrument(); //'serial communication function to Reset the Instrument } System.Environment.Exit(0); } catch (Exception ex) { //--------------------------------------------------------- //Error Handling and logging gobjErrorHandler.ErrorDescription = ex.Message; gobjErrorHandler.ErrorMessage = ex.Message; gobjErrorHandler.WriteErrorLog(ex); //--------------------------------------------------------- } finally { //--------------------------------------------------------- //Writing Execution log if (CONST_CREATE_EXECUTION_LOG == 1) { gobjErrorHandler.WriteExecutionLog(); } Application.DoEvents(); //--------------------------------------------------------- } }
private void customInstall(IDictionary state) { string targetDir = Utility.GetTargetDirectory(this.Context, state, "Search Engine"); string targetDataDir = Toolkit.ResolveDirectoryPath(@"*COMMONAPPLICATIONDATA*\GRIN-Global\GRIN-Global Search Engine", true); int installerWindowHandle = 0; var splash = new frmSplash(); try { string gguacPath = Toolkit.ResolveFilePath(targetDir + @"\gguac.exe", false); splash.ChangeText(getDisplayMember("customInstall{extracting}", "Extracting bundled files...")); var utility64CabPath = Toolkit.ResolveFilePath(targetDir + @"\utility64.cab", false); var utility64ExePath = Toolkit.ResolveFilePath(targetDir + @"\ggutil64.exe", false); var tempPath = Utility.GetTempDirectory(15); if (!File.Exists(utility64ExePath)) { if (File.Exists(utility64CabPath)) { // wipe out any existing utility64.exe file in the temp folder var extracted = Toolkit.ResolveFilePath(tempPath + @"\ggutil64.exe", false); if (File.Exists(extracted)) { File.Delete(extracted); } // extract it from our cab var cabOutput = Utility.ExtractCabFile(utility64CabPath, tempPath, gguacPath); // move it to the final target path (we can't do this up front because expand.exe tells us "can't expand cab file over itself" for some reason. if (File.Exists(extracted)) { File.Move(extracted, utility64ExePath); } } } // delete any existing index file(s) string indexDir = (targetDataDir + @"\indexes").Replace(@"\\", @"\"); if (Directory.Exists(targetDataDir)) { Directory.Delete(targetDataDir, true); } string helperPath = (Utility.GetTargetDirectory(this.Context, state, "Search Engine") + @"\gguac.exe").Replace(@"\\", @"\"); // prompt user to tell us what to do -- download files or begin recreating locally... var f = new frmInstallIndexes(); f.HelperPath = helperPath; installerWindowHandle = Toolkit.GetWindowHandle("GRIN-Global Search Engine"); //// HACK: try to give MSI form a moment to focus before we show our dialog... //Thread.Sleep(500); //Application.DoEvents(); //Thread.Sleep(500); // we no longer allow user to download indexes. always issue a recreate. File.WriteAllText(Toolkit.ResolveFilePath(indexDir + @"\recreate.init", true), ""); //DialogResult result = DialogResult.Cancel; //var autoIncludeOptionalData = Utility.GetParameter("optionaldata", null, this.Context, null); //if (("" + autoIncludeOptionalData).ToUpper() == "TRUE" || ("" + autoIncludeOptionalData).ToUpper() == "1") { // f.DownloadAllFiles(); // result = DialogResult.OK; //} else if (("" + autoIncludeOptionalData).ToUpper() == "FALSE" || ("" + autoIncludeOptionalData).ToUpper() == "0"){ // result = DialogResult.OK; //} else { // result = f.ShowDialog(installerWindowHandle); //} //if (result == DialogResult.OK) { // if (f.rdoCreateLocally.Checked) { // // need to create locally // File.WriteAllText(Toolkit.ResolveFilePath(indexDir + @"\recreate.init", true), ""); // // EventLog.WriteEntry("GRIN-Global Search Engine", "Should recreate indexes locally...", EventLogEntryType.Information); // } else { // if (f.IndexFiles != null && f.IndexFiles.Count > 0) { // // downloaded files. // splash.Show("Inspecting index files (" + f.IndexFiles.Count + ")...", false, null); // for (var i = 0; i < f.IndexFiles.Count; i++) { // var s = f.IndexFiles[i]; // splash.ChangeText("Extracting index files (" + (i + 1) + " of " + f.IndexFiles.Count + ")..."); // Utility.ExtractCabFile(s, indexDir, helperPath); // // we expanded the cab file, now delete it since we don't need it anymore (and want the next install to re-request data from the server and ignore the cache) // try { // var moveTo = s.Replace(@"\downloaded\", @"\installed\"); // if (File.Exists(moveTo)) { // File.Delete(moveTo); // } // File.Move(s, moveTo); // } catch { // try { // // move failed, try to delete it // File.Delete(s); // } catch { // // ultimately ignore all file movement errors // } // } // } // } else { // EventLog.WriteEntry("GRIN-Global Search Engine", "User chose to download indexes, but selected 0 indexes to download. Empty indexes will be created.", EventLogEntryType.Information); // } // } //} else { // // user cancelled out. // //Context.LogMessage("User cancelled out of choosing to generate indexes locally or download from server"); // EventLog.WriteEntry("GRIN-Global Search Engine", "User cancelled out of choosing to generate indexes locally or download from server"); // // this.Rollback(state); // throw new InvalidOperationException("User cancelled out of choosing to generate indexes locally or download from server."); //} } catch (Exception ex) { splash.Close(); //this.Context.LogMessage("Setup failed to extract the index files: " + ex.Message); EventLog.WriteEntry("GRIN-Global Search Engine", "Setup failed to extract the index files: " + ex.Message); // this.Rollback(state); throw; } // // first unzip the data (note we need to run this is athe currently logged-in user for it to work) // Utility.ExtractCabFile((targetDir + @"\search.cab").Replace(@"\\", @"\"), indexDir, helperPath); //// Utility.Unzip((Utility.DataDirectory + @"\gringlobal_search_small.zip").Replace(@"\\", @"\"), indexDir); string configFile = Toolkit.ResolveFilePath(targetDir + @"\GrinGlobal.Search.Engine.Service.exe.config", false); try { // update the config file... if (File.Exists(configFile)) { splash.ChangeText(getDisplayMember("customInstall{verifying}", "Verifying database connection...")); string superUserPassword = Utility.GetSuperUserPassword(Context, state); bool? useWindowsAuthentication = Utility.GetUseWindowsAuthentication(Context, state); //MessageBox.Show("pw=" + superUserPassword + ", windowsAuth=" + useWindowsAuthentication); DatabaseEngineUtil dbEngineUtil = promptForDatabaseConnectionInfo(splash, ref superUserPassword, ref useWindowsAuthentication); createDatabaseUser(splash, dbEngineUtil, superUserPassword, "gg_search", "gg_search_PA55w0rd!"); string connectionString = null; if (useWindowsAuthentication == true) { connectionString = dbEngineUtil.GetDataConnectionSpec("gringlobal", null, null).ConnectionString; } else { connectionString = dbEngineUtil.GetDataConnectionSpec("gringlobal", "gg_search", "gg_search_PA55w0rd!").ConnectionString; } EventLog.WriteEntry("GRIN-Global Search Engine", "Database connection string=" + connectionString, EventLogEntryType.Information); splash.ChangeText(getDisplayMember("customInstall{writingconfig}", "Writing configuration file...")); string contents = File.ReadAllText(configFile); string appSetting = @"<add providerName=""__ENGINE__"" name=""DataManager"" connectionString=""__CONNECTION_STRING__"" />".Replace("__ENGINE__", dbEngineUtil.EngineName).Replace("__CONNECTION_STRING__", connectionString); contents = contents.Replace("<!-- __CONNECTIONSTRING__ -->", appSetting); contents = contents.Replace("<!-- __COMMENT__ -->", "<!-- TESTING "); contents = contents.Replace("<!-- __ENDCOMMENT__ -->", " -->"); File.WriteAllText(configFile, contents); } } catch (Exception ex) { splash.Close(); //this.Context.LogMessage("Setup failed to update the configuration file (" + configFile + "): " + ex.Message); EventLog.WriteEntry("GRIN-Global Search Engine", "Setup failed to update the configuration file (" + configFile + "): " + ex.Message); // this.Rollback(state); throw; } finally { splash.Close(); if (installerWindowHandle > 0) { Toolkit.RestoreWindow(installerWindowHandle); } } }
public void BuscaMailsDeComandos(int dias) { try { Cursor MyCursor = Cursors.WaitCursor; FindComand = false; Outlook.MailItem mail; //Ahí pongo cada Mail Outlook.NameSpace outlookNameSpace = this.Application.GetNamespace("MAPI"); Outlook.MAPIFolder inbox = outlookNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); Outlook.Items items = inbox.Items.Restrict("[Unread]=true"); DateTime hacedias = DateTime.Today - new TimeSpan(dias, 0, 0, 0); //Fecha de hace "dias" días //Muestro el splash OutlookAddInEmprende.frmSplash theSplash = new frmSplash(); theSplash.Show(); theSplash.pbProgress.Step = 1; theSplash.pbProgress.Value = 1; theSplash.pbProgress.Maximum = items.Count; System.Windows.Forms.Application.DoEvents(); //Obtengo la dirección de Email del buzón de comandos Properties.Settings setting = new Properties.Settings(); //Creo variable para acceder a Settings y leer EmailAdmiin string EmailDir = setting["Email_Admin"].ToString(); ////Reviso los Unread de la carpeta MailEmprende, y los analizo foreach (Object m in items) { theSplash.pbProgress.PerformStep(); if ((mail = m as Outlook.MailItem) != null) //si el item es un mail { if (mail.MessageClass == "IPM.Note" && mail.SenderEmailAddress.ToUpper().Contains(EmailDir.ToUpper()) && mail.ReceivedTime > hacedias) { FindComand = true; AnalizaMail(mail); mail.UnRead = false; mail.Move(inbox.Folders["MailEmprende"]); } } } if (FindComand) //Si encontré algo { /* Fue comentada porque ya no tiene sentido al hacerse más robusta la rutina precedente * //09-04-2014 //Muevo los mails encontrados repito la rutina para que no quede nada foreach (Object m in items) { if ((mail = m as Outlook.MailItem) != null) //si el item es un mail { if (mail.MessageClass == "IPM.Note" && mail.SenderEmailAddress.ToUpper().Contains(EmailDir.ToUpper()) && mail.ReceivedTime > hacedias) { mail.Move(inbox.Folders["MailEmprende"]); } } }*/ //Pongo cartel de resultados MessageBox.Show(Problemas, "¡Resultados!", MessageBoxButtons.OK); Problemas = "Ejecución satisfactoria " + "\n" + "de comandos MailEmprende " + "\n" + "recibidos de la Web."; //Limpio la varible que guardaba los mensajes de error. } MyCursor = Cursors.Default; theSplash.Close(); //Cierro el splash } catch (Exception ex) { Cursor MyCursor = Cursors.Default; MessageBox.Show(ex.Message + " Se intentaba revisar los mensajes recibidos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void frmProgress_Activated(object sender, EventArgs e) { if (_activatedBefore) { return; } _activatedBefore = true; this.DialogResult = DialogResult.Cancel; Application.DoEvents(); _cancel = false; var files = _files; string downloadCache = FileDownloadInfo.DownloadedCacheFolder(_componentType); string installCache = FileDownloadInfo.InstalledCacheFolder(_componentType); // determine how many files we have, how many bytes we have to downloaded int totalCount = 0; long totalBytes = 0; string url = null; foreach (var key in files.Keys) { totalCount += files[key].Count; foreach (var di in files[key]) { totalBytes += di.SizeInBytes; if (url == null) { url = di.AbsoluteUrl.Replace(di.AppRelativeUrl.Replace("~", ""), ""); } } } int currentCount = 1; long totalBytesRead = 0; lblStatus.Text = "Initializing..."; lblOverallDownload.Text = "Initializing..."; lblOverallInstall.Text = "Initializing..."; lblURL.Text = url; pbOverallDownload.Maximum = (int)totalBytes / 1024; Application.DoEvents(); // for each row in the datagrid foreach (var key in files.Keys) { var filesToDownload = files[key]; string filePath = (downloadCache + @"\" + key).Replace("~", "").Replace("//", @"\").Replace(@"\\", @"\") + @"\"; // If the .msi is marked as needing downloading, the associated setup.exe will // also be marked as needing downloading. // If there is no setup.exe with the .msi, we still want to download the msi. // for each file associated with each row in the datagrid foreach (var downloadInfo in filesToDownload) { downloadInfo.FullFilePath = filePath + downloadInfo.FileName; Utility.ResolveFilePath(downloadInfo.FullFilePath, true); lblStatus.Text = "Downloading " + downloadInfo.FileName + " (" + currentCount + " of " + totalCount + ")..."; if (downloadInfo.NeedToDownload) { if (Utility.IsWindowsFilePath(downloadInfo.AbsoluteUrl)) { // simply copy file from source path to destination path if (File.Exists(downloadInfo.FullFilePath)) { File.Delete(downloadInfo.FullFilePath); } File.Copy(downloadInfo.AbsoluteUrl, downloadInfo.FullFilePath); // and the flag file so if they connect to a web server later we know which version the cached one is File.WriteAllText(downloadInfo.FullFilePath + ".version", downloadInfo.LatestVersion); totalBytesRead += downloadInfo.SizeInBytes; } else { downloadFileFromWebServer(downloadInfo, ref totalBytesRead, ref totalBytes); } } else { totalBytesRead += downloadInfo.SizeInBytes; } // add to the progress bar the bytes for this file (in case download was skipped) decimal percentTotalDone = ((decimal)totalBytesRead / (decimal)totalBytes) * 100.0M; //50.0M; lblOverallDownload.Text = percentTotalDone.ToString("##0.00") + "% of all files downloaded"; int overallVal = (int)(totalBytesRead / 1024); pbOverallDownload.Value = (overallVal > pbOverallDownload.Maximum ? pbOverallDownload.Maximum : overallVal); currentCount++; Application.DoEvents(); if (_cancel) { break; } } } bool installFailed = false; string failedInstallName = ""; if (!_cancel) { lblCurrentAction.Text = "100% downloaded"; pbFile.Value = pbFile.Maximum; lblOverallDownload.Text = "100% of all files downloaded"; pbOverallDownload.Value = pbOverallDownload.Maximum; this.WindowState = FormWindowState.Minimized; Application.DoEvents(); if (_performInstallation) { btnCancel.Enabled = false; Text = "Installing..."; if (this.Owner != null) { this.Owner.WindowState = FormWindowState.Minimized; } Utility.ActivateApplication(this.Handle); Application.DoEvents(); int totalInstallCount = 0; int installCount = 0; foreach (var key in files.Keys) { foreach (var di in files[key]) { if (di.NeedToInstall) { totalInstallCount++; } } } pbOverallInstall.Maximum = totalInstallCount; // for each row in the datagrid foreach (var key in files.Keys) { var filesToDownload = files[key]; string filePath = (downloadCache + @"\" + key).Replace("~", "").Replace("//", @"\").Replace(@"\\", @"\") + @"\"; // If the .msi is marked as needing downloading, the associated setup.exe will // also be marked as needing downloading. // If there is no setup.exe with the .msi, we still want to download the msi. var installed = new List <string>(); var installedInfo = new List <FileDownloadInfo>(); // for each file associated with the current row in the datagrid foreach (var downloadInfo in filesToDownload) { if (downloadInfo.NeedToInstall) { lblStatus.Text = "Installing " + downloadInfo.FileName; lblCurrentAction.Text = "Installing " + downloadInfo.FileName; this.Text = lblCurrentAction.Text; lblOverallInstall.Text = "Installing..."; string logFileName = null; Application.DoEvents(); if (downloadInfo.FileName.ToLower().EndsWith(".exe")) { // install it!!! if (_installingNewUpdater) { // an exe locks files when it's running -- meaning if we try to update the updater while it's running, // we're guaranteed it will fail. copyForMirrorIfNeeded(filePath, downloadInfo); var batFilePath = createBatchFileToUpdateUpdater(downloadInfo, null); runBatchFile(batFilePath); this.DialogResult = DialogResult.OK; this.Close(); return; } else { string msiName = installViaSetupExe(filePath + downloadInfo.FileName, downloadInfo, out logFileName); } installed.Add(downloadInfo.FileName.ToLower().Replace(".exe", "")); } else if (downloadInfo.FileName.ToLower().EndsWith(".msi")) { string file = downloadInfo.FileName.ToLower().Replace(".msi", ""); if (!installed.Contains(file)) { // this is a free msi -- no .exe is associated with it. if (_installingNewUpdater) { // an exe locks files when it's running -- meaning if we try to update the updater while it's running, // we're guaranteed it will fail. copyForMirrorIfNeeded(filePath, downloadInfo); var batFilePath = createBatchFileToUpdateUpdater(null, downloadInfo); runBatchFile(batFilePath); this.DialogResult = DialogResult.OK; this.Close(); return; } else { // 'normal' msi install installViaMsiExec(filePath + downloadInfo.FileName, downloadInfo, out logFileName); } // installedInfo.Add(downloadInfo); } else { // the exe installed it, just skip this msi } } else if (downloadInfo.FileName.ToLower().EndsWith(".zip")) { // this is a .zip file, just open it in explorer // TODO: auto-unzip? distribute a .cab instead??? Process.Start("explorer.exe", @"/select,""" + downloadInfo.FullFilePath + @""""); } else if (downloadInfo.FileName.ToLower().EndsWith(".cab")) { // auto-extract to a temp folder or prompt them to extract it somewhere? var fCab = new frmExpand(); fCab.txtExpandTo.Text = Utility.GetTempDirectory(1500) + @"\" + downloadInfo.DisplayName; fCab.ShowDialog(this); var splash = new frmSplash(); try { if (fCab.rdoExpand.Checked) { // expand cab file, launch var dest = Utility.ResolveDirectoryPath(fCab.txtExpandTo.Text, true); if (fCab.chkEmptyDirectory.Checked) { splash.ChangeText(getDisplayMember("activated{emptying}", "Emptying directory {0} ...", dest)); Utility.EmptyDirectory(dest); } splash.ChangeText(getDisplayMember("activated{extracting}", "Extracting {0}...", downloadInfo.FileName)); Utility.ExtractCabFile(downloadInfo.FullFilePath, dest, null); if (fCab.chkLaunchSetup.Checked) { var setupBat = Utility.ResolveFilePath(dest + @"\Setup.bat", false); if (File.Exists(setupBat)) { // launch setup.bat... Process.Start(dest + @"\Setup.bat"); } else { Process.Start("explorer.exe", @"""" + dest + @""""); } } else { Process.Start("explorer.exe", @"""" + dest + @""""); } } else { Process.Start("explorer.exe", @"/select,""" + downloadInfo.FullFilePath + @""""); } } finally { splash.Close(); } } else { // we don't know what this is, just display it in explorer Process.Start("explorer.exe", @"/select,""" + filePath + @""""); } if (downloadInfo.NeedToInstall && downloadInfo.TriedToInstall) { if (!File.Exists(logFileName)) { failedInstallName = downloadInfo.DisplayName; installFailed = true; break; } else { string logText = File.ReadAllText(logFileName); if (logText.Contains("-- Installation failed.")) { installFailed = true; failedInstallName = downloadInfo.DisplayName; break; } } } installCount++; pbOverallInstall.Value = installCount / totalInstallCount; lblOverallInstall.Text = (((decimal)installCount / (decimal)totalInstallCount) * 100.0M).ToString("##0.00") + "% installed"; Application.DoEvents(); if (_cancel) { break; } } } if (!installFailed) { foreach (var di in filesToDownload) { if (di.TriedToInstall) { // move from downloadcache to installercache string curFilePath = filePath + di.FileName; string newFilePath = curFilePath.Replace(downloadCache, installCache); if (File.Exists(newFilePath)) { File.Delete(newFilePath); } Utility.ResolveDirectoryPath(Directory.GetParent(newFilePath).FullName, true); File.Move(curFilePath, newFilePath); try { if (File.Exists(curFilePath + ".version")) { File.Delete(curFilePath + ".version"); } } catch { // ignore all errors, it will be overwritten as needed later anyway } if (_cancel) { break; } } } } if (_cancel || installFailed) { break; } } if (this.Owner != null) { this.Owner.WindowState = FormWindowState.Normal; } this.WindowState = FormWindowState.Normal; Application.DoEvents(); Utility.ActivateApplication(this.Handle); if (installFailed) { MessageBox.Show(getDisplayMember("activated", "Install of {0} failed.\n\nAny remaining installs have been cancelled.", failedInstallName)); } } else { // no installing done, just downloading. // if this is a mirror server, be sure to copy to the mirror temp dir if (_isMirrorServer) { foreach (var key in files.Keys) { string filePath = (downloadCache + @"\" + key).Replace("~", "").Replace("//", @"\").Replace(@"\\", @"\") + @"\"; var filesToDownload = files[key]; foreach (var fdi in filesToDownload) { copyForMirrorIfNeeded(filePath, fdi); } } } } } this.DialogResult = (_cancel ? DialogResult.Cancel : DialogResult.OK); }