Example #1
0
        private void DownloadHandler_ConfigurationDownloadRequested(string fileName, DownloadEventArgs args)
        {
            if (settings.AllowConfigurationDownloads)
            {
                logger.Debug($"Forwarding download request for configuration file '{fileName}'.");
                ConfigurationDownloadRequested?.Invoke(fileName, args);

                if (args.AllowDownload)
                {
                    logger.Debug($"Download request for configuration file '{fileName}' was granted. Asking user to confirm the reconfiguration...");

                    var message = TextKey.MessageBox_ReconfigurationQuestion;
                    var title   = TextKey.MessageBox_ReconfigurationQuestionTitle;
                    var result  = messageBox.Show(message, title, MessageBoxAction.YesNo, MessageBoxIcon.Question, window);

                    args.AllowDownload = result == MessageBoxResult.Yes;
                    logger.Info($"The user chose to {(args.AllowDownload ? "start" : "abort")} the reconfiguration.");
                }
                else
                {
                    logger.Debug($"Download request for configuration file '{fileName}' was denied.");
                    messageBox.Show(TextKey.MessageBox_ReconfigurationDenied, TextKey.MessageBox_ReconfigurationDeniedTitle, parent: window);
                }
            }
            else
            {
                logger.Debug($"Discarded download request for configuration file '{fileName}'.");
            }
        }
Example #2
0
        private void Webview_Download(object sender, DownloadEventArgs e)
        {
            try
            {
                var source = Android.Net.Uri.Parse(e.Url);

                var request = new DownloadManager.Request(source);

                request.AllowScanningByMediaScanner();

                request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);

                request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, source.LastPathSegment);

                var manager = (DownloadManager)this.GetSystemService(Context.DownloadService);

                manager.Enqueue(request);

                Toast.MakeText(this, "Downloading Indigent Reports", ToastLength.Short).Show();
            }

            catch (Exception ex)
            {
                Toast.MakeText(this, "Cannot Download the file", ToastLength.Short).Show();
                Console.WriteLine(ex.Message);
            };
        }
Example #3
0
 protected virtual void OnDownloadProgressChanged(DownloadEventArgs e)
 {
     if (DownloadProgressChanged != null)
     {
         DownloadProgressChanged(this, e);
     }
 }
Example #4
0
 static void OnCompleted(DownloadEventArgs args)
 {
     // this is an important thing to do after a download isn't used anymore, otherwise you will run into a memory leak.
     args.Download.DetachAllHandlers();
     Console.WriteLine("Download has finished!");
     finished = true;
 }
 //Prevent stray "Save As" dialogs from popping up
 private void WebCore_Download(object sender, DownloadEventArgs e)
 {
     if ((e.MimeType == "text/html"))
     {
         e.Cancel = true;
     }
 }
        private void IDownloader_DownloadStatusChanged(object sender, DownloadEventArgs e)
        {
            UpdateActiveDownloads();
            if (e.Target.Progress.Status == DownloadStatus.Completed)
            {
                downloads.Remove(e.Target);
                PostProcessors.PostProcessorManager.Instance.Run(e.Target);
            }
            else if (e.Target.Progress.Status == DownloadStatus.Failed)
            {
                Log.WriteLine($"Download failed: {e.Target.DownloadUri}");
                if (File.Exists(e.Target.GetDownloadingPath()))
                {
                    File.Delete(e.Target.GetDownloadingPath());
                }
            }

            if (e.Target.Progress.Status == DownloadStatus.Canceled)
            {
                downloads.Remove(e.Target);
            }

            DownloadStatusChanged?.Invoke(this, e);
            SaveDownloads();
        }
Example #7
0
    public void DoRing()
    {
        int    hh   = DateTime.Now.Hour;
        int    mm   = DateTime.Now.Minute;
        int    ss   = DateTime.Now.Second;
        string h    = Console.ReadLine();
        int    myhh = Int32.Parse(h);
        string m    = Console.ReadLine();
        int    mymm = Int32.Parse(m);
        string s    = Console.ReadLine();
        int    myss = Int32.Parse(s);

        if (myhh == hh && mymm == mm && myss == ss)
        {
            Console.WriteLine("闹钟响了");
        }
        else
        {
            Console.WriteLine("未到时间");
        }

        //发生事件,通知外界
        if (DoIt != null)
        {
            DownloadEventArgs args = new DownloadEventArgs();
            args.Hour   = hh;
            args.Minute = mm;
            args.Second = ss;
            DoIt(this, args);
        }
    }
        private void Browser_ConfigurationDownloadRequested(string fileName, DownloadEventArgs args)
        {
            if (Settings.ConfigurationMode == ConfigurationMode.ConfigureClient)
            {
                logger.Info($"Received download request for configuration file '{fileName}'. Asking user to confirm the reconfiguration...");

                var message     = TextKey.MessageBox_ReconfigurationQuestion;
                var title       = TextKey.MessageBox_ReconfigurationQuestionTitle;
                var result      = messageBox.Show(message, title, MessageBoxAction.YesNo, MessageBoxIcon.Question, args.BrowserWindow);
                var reconfigure = result == MessageBoxResult.Yes;

                logger.Info($"The user chose to {(reconfigure ? "start" : "abort")} the reconfiguration.");

                if (reconfigure)
                {
                    args.AllowDownload = true;
                    args.Callback      = Browser_ConfigurationDownloadFinished;
                    args.DownloadPath  = Path.Combine(appConfig.DownloadDirectory, fileName);
                }
            }
            else
            {
                logger.Info($"Denied download request for configuration file '{fileName}' due to '{Settings.ConfigurationMode}' mode.");
                messageBox.Show(TextKey.MessageBox_ReconfigurationDenied, TextKey.MessageBox_ReconfigurationDeniedTitle, parent: args.BrowserWindow);
            }
        }
 private void OnDownloadCompleted(DownloadEventArgs args)
 {
     lock (this.monitor)
     {
         this.alreadyDownloadedSizes[args.Download] = this.downloadSizes[args.Download];
     }
 }
Example #10
0
 private void OnFileDownloaded(object sender, DownloadEventArgs e)
 {
     if (!e.FileSaved)
     {
         mps.DisplayAlert("UUENDAMINE", "INSTALLIFAILI EI LEITUD!", "OK");
     }
 }
Example #11
0
        private void ClipDownloaded(object sender, DownloadEventArgs e)
        {
            Utils.WriteGreenText($"\n[{DateTime.Now.ToShortDateString()}-{DateTime.Now.ToLongTimeString()}] - [{e.DownloadedClips}/{e.TotalClips}] {e.CourseHeader.Name} - {e.ModuleId}. {e.ModuleTitle}");
            if (e.Succeeded)
            {
                int duration = e.Duration;
                if (duration <= 0)
                {
                    duration = 1000;
                }

                int   seconds  = duration / 1000;
                int   second   = seconds > 60 ? seconds % 60 : seconds;
                int   minute   = seconds / 60;
                float baudrate = (e.TotalSize / 1024) / (duration / 1000);

                Utils.WriteText($"\t\t{e.ClipId}. {e.ClipTitle}  --  downloaded in (HH:mm:ss.ms) {minute}:{second}.{duration}, {e.TotalSize / 1024} KB ({baudrate}/KBps)");
            }
            else
            {
                Utils.WriteRedText($"\t\t{e.ClipId}. {e.ClipTitle} --  Download failed. will retry again.");
                if (e.Error != null)
                {
                    Utils.WriteRedText($"\t\t{e.Error.Message}");
                }
            }
        }
 void DownloaderDone(object sender, DownloadEventArgs args)
 {
     if (Downloaded != null)
     {
         Downloaded(this, args);
     }
 }
Example #13
0
        private void OnFileDownloaded(object sender, DownloadEventArgs e)
        {
            if (e.FileSaved)
            {
                Log.Warning("Download", "File have been downloaded with success");
                _NbFileDownloaded++;

                ProgressBar.ProgressTo(ProgressBar.Progress + 0.3, SIZE_PROGRESS_LONG, Easing.Linear);
                if (_NbFileDownloaded == 2)
                {
                    Preferences.Set(Constants.DATE_DOWNLAOD, DateTime.Now.ToString());
                    Preferences.Set(Constants.SHARED_DATABASE_PATH, Path.Combine(_DownloadDirectoryPath, Constants.DATABASE_FILE_NAME));

                    DataManager.GetInstance(ConfigInstance.GetInstance().IsDev, Preferences.Get(Constants.SHARED_DATABASE_PATH, ""));
                    string pathZipFile = Path.Combine(_DownloadDirectoryPath, Constants.IMG_FILE_NAME);
                    ZipManager.Unzip(pathZipFile, _ImgDirectoryPath);

                    //delete temporary file after get values
                    File.Delete(Path.Combine(_DownloadDirectoryPath, Constants.IMG_FILE_NAME));
                    ProgressBar.ProgressTo(0.99, SIZE_PROGRESS_LONG, Easing.Linear);
                    _App.ChangePage(new MainPage());
                }
            }
            else
            {
                Log.Warning("Download", "Error while saving the file");
            }
        }
        private void RequestConfigurationFileDownload(DownloadItem downloadItem, IBeforeDownloadCallback callback)
        {
            var args = new DownloadEventArgs();

            logger.Debug($"Handling download of configuration file '{downloadItem.SuggestedFileName}'.");
            ConfigurationDownloadRequested?.Invoke(downloadItem.SuggestedFileName, args);

            if (args.AllowDownload)
            {
                if (args.Callback != null)
                {
                    callbacks[downloadItem.Id] = args.Callback;
                }

                logger.Debug($"Starting download of configuration file '{downloadItem.SuggestedFileName}'...");

                using (callback)
                {
                    callback.Continue(args.DownloadPath, false);
                }
            }
            else
            {
                logger.Debug($"Download of configuration file '{downloadItem.SuggestedFileName}' was cancelled.");
            }
        }
 private void _webView_Download(object sender, DownloadEventArgs e)
 {
     _broadcastReceiver.SendDownloadUrl(new DownloadUrlInfo()
     {
         Url = e.Url, MimeType = e.Mimetype
     });
 }
Example #16
0
        public void Reconfiguration_MustCorrectlyHandleFailedRequest()
        {
            var downloadPath = @"C:\Folder\Does\Not\Exist\filepath.seb";
            var filename     = "filepath.seb";
            var args         = new DownloadEventArgs();

            appConfig.DownloadDirectory = @"C:\Folder\Does\Not\Exist";
            settings.ConfigurationMode  = ConfigurationMode.ConfigureClient;
            messageBox.Setup(m => m.Show(
                                 It.IsAny <TextKey>(),
                                 It.IsAny <TextKey>(),
                                 It.IsAny <MessageBoxAction>(),
                                 It.IsAny <MessageBoxIcon>(),
                                 It.IsAny <IWindow>())).Returns(MessageBoxResult.Yes);
            runtimeProxy.Setup(r => r.RequestReconfiguration(It.Is <string>(p => p == downloadPath))).Returns(new CommunicationResult(false));

            sut.TryStart();
            browserController.Raise(b => b.ConfigurationDownloadRequested += null, filename, args);
            args.Callback(true, downloadPath);

            runtimeProxy.Verify(r => r.RequestReconfiguration(It.IsAny <string>()), Times.Once);
            messageBox.Verify(m => m.Show(
                                  It.IsAny <TextKey>(),
                                  It.IsAny <TextKey>(),
                                  It.IsAny <MessageBoxAction>(),
                                  It.Is <MessageBoxIcon>(i => i == MessageBoxIcon.Error),
                                  It.IsAny <IWindow>()), Times.Once);
        }
        private static void OnDownloadTaskStoppedHandler(object sender,
                                                         DownloadEventArgs args)
        {
            DownloadInfo dif = args.DownloadInfo;

            DownloadTaskStartedOrStopped(dif, false);
        }
Example #18
0
 protected virtual void OnDownloadStopped(DownloadEventArgs args)
 {
     if (this.DownloadStopped != null)
     {
         this.DownloadStopped(args);
     }
 }
        public void Reconfiguration_MustCorrectlyHandleDownload()
        {
            var downloadPath = @"C:\Folder\Does\Not\Exist\filepath.seb";
            var filename     = "filepath.seb";
            var args         = new DownloadEventArgs();

            appConfig.TemporaryDirectory           = @"C:\Folder\Does\Not\Exist";
            settings.Security.AllowReconfiguration = true;
            messageBox.Setup(m => m.Show(
                                 It.IsAny <TextKey>(),
                                 It.IsAny <TextKey>(),
                                 It.IsAny <MessageBoxAction>(),
                                 It.IsAny <MessageBoxIcon>(),
                                 It.IsAny <IWindow>())).Returns(MessageBoxResult.Yes);
            runtimeProxy.Setup(r => r.RequestReconfiguration(It.Is <string>(p => p == downloadPath))).Returns(new CommunicationResult(true));

            sut.TryStart();
            browser.Raise(b => b.ConfigurationDownloadRequested += null, filename, args);
            args.Callback(true, downloadPath);

            runtimeProxy.Verify(r => r.RequestReconfiguration(It.Is <string>(p => p == downloadPath)), Times.Once);

            Assert.AreEqual(downloadPath, args.DownloadPath);
            Assert.IsTrue(args.AllowDownload);
        }
        private static void DownloadEventAction(DownloadEventArgs args,
                                                DownloadAction action)
        {
            if (args.DownloadInfo != null)
            {
                lock (downloads.SyncRoot)
                {
                    action(args.DownloadInfo);
                }
            }
            else if (args.Downloads != null)
            {
                lock (downloads.SyncRoot)
                {
                    foreach (DownloadInfo dif in args.Downloads)
                    {
                        if (dif != null)
                        {
                            action(dif);
                        }
                    }
                }
            }

            source.Update();
        }
Example #21
0
        private void OnFileDownloaded(object sender, DownloadEventArgs e)
        {
            if (e.FileSaved)
            {
                Log.Debug("Download", "File have been downloaded with success");
                _NbFileDownloaded++;
                if (_NbFileDownloaded == 2)
                {
                    SharedPreferenceManager.SaveString(ApplicationContext, Constants.DATE_DOWNLAOD, DateTime.Now.ToString());
                    SharedPreferenceManager.SaveString(ApplicationContext, Constants.SHARED_DATABASE_PATH, System.IO.Path.Combine(_DownloadDirectoryPath, Constants.DATABASE_FILE_NAME));

                    if (Controller.Permission.CheckPermission.PermissionGranted(ApplicationContext, Manifest.Permission.ReadExternalStorage))
                    {
                        DataManager.GetInstance(ConfigInstance.GetInstance().IsDev, SharedPreferenceManager.GetString(ApplicationContext, Constants.SHARED_DATABASE_PATH, ""));
                        string pathZipFile = System.IO.Path.Combine(_DownloadDirectoryPath, Constants.IMG_FILE_NAME);
                        ZipManager.Unzip(pathZipFile, _ImgDirectoryPath);
                    }
                    else
                    {
                        Toast.MakeText(ApplicationContext, "Permission non accordée pour la lecture du fichier, aller dans les paramètres de l'application pour modifier cette valeur.", ToastLength.Long).Show();
                    }

                    //delete temporary file after get values
                    File.Delete(System.IO.Path.Combine(_DownloadDirectoryPath, Constants.IMG_FILE_NAME));
                    HideProgressBar();
                    StartActivity(typeof(HomeActivity));
                    Finish();
                }
            }
            else
            {
                Log.Error("Download", "Error while saving the file");
            }
        }
        private void CurrentBrowser_DownloadCompleted(object sender, EventArgs e)
        {
            DownloadEventArgs dl = (DownloadEventArgs)e;

            Invoke((MethodInvoker) delegate
            {
                uiActionLoggedToolStripStatusLabel.Visible = false;
                uiDownloadProgressBar.Visible = false;
                MessageBox.Show("Download Completed", "Download Complete", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            });

            string dlPath   = dl.DownloadItems.FullPath;
            string savePath = Path.Combine(Constants.ContainerLocation, Constants.Directories.GetSpecifiedCaseDirectory(Actions.Download), Path.GetFileName(dl.DownloadItems.FullPath));

            if (File.Exists(savePath))
            {
                string extension = Path.GetExtension(savePath);
                string name      = Path.GetFileNameWithoutExtension(savePath) + "_" + (DateTime.Now.ToString("yyyy-MM-dd_hh_mm_ss") + extension);
                savePath = Path.Combine(Constants.ContainerLocation, Constants.Directories.GetSpecifiedCaseDirectory(Actions.Download), name);
            }


            File.Copy(dlPath, savePath);
            Logger.Log(new WebpageActionsLog(dl.DownloadItems.Url, Actions.Download, OsirtHelper.GetFileHash(dlPath), Path.GetFileName(savePath), ""));
        }
Example #23
0
        public void Reconfiguration_MustCorrectlyHandleFailedRequest()
        {
            var downloadPath = @"C:\Folder\Does\Not\Exist\filepath.seb";
            var downloadUrl  = @"https://www.host.abc/someresource.seb";
            var filename     = "filepath.seb";
            var args         = new DownloadEventArgs();

            appConfig.TemporaryDirectory           = @"C:\Folder\Does\Not\Exist";
            settings.Security.AllowReconfiguration = true;
            messageBox.Setup(m => m.Show(
                                 It.IsAny <TextKey>(),
                                 It.IsAny <TextKey>(),
                                 It.IsAny <MessageBoxAction>(),
                                 It.IsAny <MessageBoxIcon>(),
                                 It.IsAny <IWindow>())).Returns(MessageBoxResult.Yes);
            runtimeProxy.Setup(r => r.RequestReconfiguration(
                                   It.Is <string>(p => p == downloadPath),
                                   It.Is <string>(u => u == downloadUrl))).Returns(new CommunicationResult(false));

            sut.TryStart();
            browser.Raise(b => b.ConfigurationDownloadRequested += null, filename, args);
            args.Callback(true, downloadUrl, downloadPath);

            runtimeProxy.Verify(r => r.RequestReconfiguration(It.IsAny <string>(), It.IsAny <string>()), Times.Once);
            messageBox.Verify(m => m.Show(
                                  It.IsAny <TextKey>(),
                                  It.IsAny <TextKey>(),
                                  It.IsAny <MessageBoxAction>(),
                                  It.Is <MessageBoxIcon>(i => i == MessageBoxIcon.Error),
                                  It.IsAny <IWindow>()), Times.Once);
        }
Example #24
0
 private void downloadStopped(DownloadEventArgs args)
 {
     lock (this.monitor)
     {
         this.CloseFile();
     }
 }
Example #25
0
 private void OnDonwloadEnd(object sender, DownloadEventArgs ev)
 {
     Task.Run(() => {
         Dispatcher.Invoke(() => {
             Shutdown();
         });
     });
 }
 public void DownloadModified(object sender, DownloadEventArgs e)
 {
     if (this._cancellationPending)
     {
         ((FileDownloader) sender).Cancel();
     }
     this.asyncOperation.Post(this.progressReporter, new DeploymentProgressChangedEventArgs(e.Progress, this.userState, e.BytesCompleted, e.BytesTotal, DeploymentProgressState.DownloadingApplicationFiles, this.groupName));
 }
Example #27
0
 private void downloader_ProgressChanged(object sender, DownloadEventArgs e)
 {
     // (In WorkerThread space)
     if (downloadStarted)
     {
         BeginInvoke(callbackUpdateProgressBar, e.PercentDone);
     }
 }
Example #28
0
 private void Downloader_FinishedDownload(object sender, DownloadEventArgs e)
 {
     MessageBox.Show("Download Finished!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
     progressBar.Value = 0;
     progressLbl.Text  = "0 %";
     TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress, Handle);
     TaskbarManager.Instance.SetProgressValue(0, 100, Handle);
 }
Example #29
0
 public DownLoad PublishedTemplate(object sender, DownloadEventArgs e)
 {
     return(new DownLoad
     {
         FileName = "导入模版.xls",
         FilePath = HttpContext.Current.Server.MapPath("/Resource/Template/ImportPublish.xls")
     });
 }
Example #30
0
 public DownLoad Chrome(object sender, DownloadEventArgs e)
 {
     return(new DownLoad()
     {
         FileName = "Chrome_chs.exe",
         FilePath = @"\\192.168.0.4\Minicut\软件\办公软件\Chrome_chs.exe"
     });
 }
Example #31
0
        protected virtual void OnTthAssigned(DownloadEventArgs e)
        {
            var handler = TthAssigned;

            if (handler != null)
            {
                handler(this, e);
            }
        }
Example #32
0
	public static void RaiseDownloadFinishedEvent (DownloadEventArgs e) {
		if (string.IsNullOrEmpty(e.result.error)) {
			Debug.Log("Download finished");
		} else {
			Debug.Log("Problem with download");
		}
		if (Events.DownloadFinished != null) {
			Events.DownloadFinished(null, e);
		}
	}
Example #33
0
 private void DownloadEndedHandler(object sender, DownloadEventArgs e)
 {
     if (InvokeRequired)
     {
         Invoke((EventHandler<DownloadEventArgs>)DownloadEndedHandler, sender, e);
         return;
     }
     if (e.Task.Success)
     {
         Controls.Remove(downloadControls[e.Task]);
         downloadControls.Remove(e.Task);
         UpdateLayout();
     }
     else
     {
         downloadControls[e.Task].ErrorMessage = e.Task.ErrorMessage;
     }
 }
 public void DownloadModified(object sender, DownloadEventArgs e)
 {
     if (this._userCancelling)
     {
         ((FileDownloader) sender).Cancel();
     }
     else
     {
         this._downloadData = e;
         if (((this._info.iconFilePath != null) && (this._appIconBitmap == null)) && ((e.Cookie != null) && File.Exists(this._info.iconFilePath)))
         {
             using (Icon icon = Icon.ExtractAssociatedIcon(this._info.iconFilePath))
             {
                 this._appIconBitmap = this.TryGet32x32Bitmap(icon);
             }
         }
         base.BeginInvoke(this.updateUIMethodInvoker);
     }
 }
		private void OnLinkOpenWebViewDownloadCompleted(Object sender, DownloadEventArgs e)
		{
			if (_extensionsManager.LinkOpenExtension.LinkData == null) return;
			AppManager.Instance.ShowFloater(() =>
			{

				switch (_extensionsManager.LinkOpenExtension.LinkData?.Type)
				{

					case LinkType.PowerPoint:
					case LinkType.Word:
					case LinkType.Excel:
					case LinkType.Pdf:
					case LinkType.Image:
						OpenFileLink(new[] { e.Item.FullPath });
						break;
				}
				_extensionsManager.LinkOpenExtension.ReleaseData();
			}, null);
		}
		private void OnDownloadProgressChanged(object sender, DownloadEventArgs e)
		{
		}
 //Prevent stray "Save As" dialogs from popping up
 private void WebCore_Download(object sender, DownloadEventArgs e)
 {
     if ((e.MimeType == "text/html"))
     {
         e.Cancel = true;
     }
 }
Example #38
0
        private void WebView_DownloadCompleted(object sender, DownloadEventArgs e)
        {
            try
            {
                if (this.Cancelar)
                {
                    this.Cursor = System.Windows.Forms.Cursors.Arrow;
                    this.webControl1.Cursor = System.Windows.Forms.Cursors.Arrow;
                //    Mensaje.MostrarMensaje(Constantes.TipoMensaje.Detenido, "Descarga", "Proceso cancelado por el usuario");
                }
                else
                {
                    DownloadItem archivoXML = e.Item;

                    String full = archivoXML.FullPath;
                    if (new FileInfo(full).Length == 0)
                    {
                        // empty
                        System.Windows.Forms.Clipboard.SetText("archivo vacio");

                        this.cuantosNoSeInsertaron++;

                    }
                    else
                    {
                        String[] fullArray = full.Split('\\');
                        String nombreDelArchivo = fullArray.Last();

                        XmlDocument doc = new XmlDocument();
                        doc.Load(full);
                        XmlNodeList titles = doc.GetElementsByTagName("tfd:TimbreFiscalDigital");
                        XmlNode obj = titles.Item(0);

                        String noCertificadoSAT = "";
                        bool isNoCertificado = obj.Attributes["noCertificadoSAT"] != null;
                        if (isNoCertificado)
                        {
                            noCertificadoSAT = obj.Attributes["noCertificadoSAT"].InnerText;
                        }

                        String selloCFD = "";
                        bool isselloCFD = obj.Attributes["selloCFD"] != null;
                        if (isselloCFD)
                        {
                            selloCFD = obj.Attributes["selloCFD"].InnerText;
                        }

                        String selloSAT = "";
                        bool isselloSAT = obj.Attributes["selloSAT"] != null;
                        if (isselloSAT)
                        {
                            selloSAT = obj.Attributes["selloSAT"].InnerText;
                        }

                        String folio_fiscal = obj.Attributes["UUID"].InnerText;
                        folio_fiscal = folio_fiscal.ToUpper();

                        XmlNodeList titlesx = doc.GetElementsByTagName("cfdi:Receptor");
                        if (titlesx.Count == 0)
                        {
                            titlesx = doc.GetElementsByTagName("Receptor");
                        }

                        XmlNode objx = titlesx.Item(0);
                        String rfcReceptor = "";
                        String nombreReceptor = "";
                        bool isRFCrfcReceptor = objx.Attributes["rfc"] != null;
                        if (isRFCrfcReceptor)
                        {
                            rfcReceptor = objx.Attributes["rfc"].InnerText.Trim();
                        }
                        bool isRFCNombreReceptor = objx.Attributes["nombre"] != null;
                        if (isRFCNombreReceptor)
                        {
                            nombreReceptor = objx.Attributes["nombre"].InnerText;
                        }

                        XmlNodeList titles1 = doc.GetElementsByTagName("cfdi:Emisor");
                        if (titles1.Count == 0)
                        {
                            titles1 = doc.GetElementsByTagName("Emisor");
                        }

                        XmlNode obj1 = titles1.Item(0);
                        String rfc = "";
                        bool isRFC = obj1.Attributes["rfc"] != null;
                        if (isRFC)
                        {
                            rfc = obj1.Attributes["rfc"].InnerText.Trim();
                        }
                        //revisar que el RFC coincida , por lo menos uno de los 2
                        if (!rfc.Equals(Properties.Settings.Default.RFC))
                        {
                            if (!rfcReceptor.Equals(Properties.Settings.Default.RFC))
                            {
                                return;//naranjas
                            }
                        }

                        String razon = "";
                        bool isRazon = obj1.Attributes["nombre"] != null;
                        if (isRazon)
                        {
                            razon = obj1.Attributes["nombre"].InnerText;
                            razon = razon.Replace('\'', ' ');
                        }

                        XmlNodeList titles2 = doc.GetElementsByTagName("cfdi:Comprobante");
                        if (titles2.Count == 0)
                        {
                            titles2 = doc.GetElementsByTagName("Comprobante");
                        }

                        XmlNode obj2 = titles2.Item(0);

                        XmlNodeList titlesY = doc.GetElementsByTagName("cfdi:DomicilioFiscal");
                        if (titlesY.Count == 0)
                        {
                            titlesY = doc.GetElementsByTagName("DomicilioFiscal");
                        }
                        String calle = "";
                        String noExterior = "";
                        String colonia = "";
                        String municipio = "";
                        String estado = "";

                        if (titlesY.Count > 0)
                        {
                            XmlNode objY = titlesY.Item(0);
                            bool isCalle = objY.Attributes["calle"] != null;
                            if (isCalle)
                            {
                                calle = objY.Attributes["calle"].InnerText;
                            }

                            bool isnoExterior = objY.Attributes["noExterior"] != null;
                            if (isnoExterior)
                            {
                                noExterior = objY.Attributes["noExterior"].InnerText;
                            }

                            bool iscolonia = objY.Attributes["colonia"] != null;
                            if (iscolonia)
                            {
                                colonia = objY.Attributes["colonia"].InnerText;
                            }

                            bool ismunicipio = objY.Attributes["municipio"] != null;
                            if (ismunicipio)
                            {
                                municipio = objY.Attributes["municipio"].InnerText;
                            }

                            bool isestado = objY.Attributes["estado"] != null;
                            if (isestado)
                            {
                                estado = objY.Attributes["estado"].InnerText;
                            }
                        }

                        XmlNodeList titles4 = doc.GetElementsByTagName("cfdi:Impuestos");
                        if (titles4.Count == 0)
                        {
                            titles4 = doc.GetElementsByTagName("Impuestos");
                        }

                        XmlNode obj4 = titles4.Item(0);

                        String iva = "0";
                        bool isIva = obj4.Attributes["totalImpuestosTrasladados"] != null;
                        if (isIva)
                        {
                            iva = obj4.Attributes["totalImpuestosTrasladados"].InnerText;
                        }
                        else
                        {
                            XmlNodeList traslados = doc.GetElementsByTagName("cfdi:Traslado");
                            if (traslados.Count == 0)
                            {
                                traslados = doc.GetElementsByTagName("Traslado");
                            }
                            int i;
                            for (i = 0; i < traslados.Count; i++)
                            {
                                XmlNode objn = traslados.Item(i);
                                String cantidad = "0";
                                bool isCantidad = objn.Attributes["importe"] != null;
                                if (isCantidad)
                                {
                                    cantidad = objn.Attributes["importe"].InnerText;
                                }
                                iva = Convert.ToString(float.Parse(iva) + float.Parse(cantidad));
                            }
                        }

                        String subTotal = "";
                        bool isSubTotal = obj2.Attributes["subTotal"] != null;
                        if (isSubTotal)
                        {
                            subTotal = obj2.Attributes["subTotal"].InnerText;
                        }

                        String tipoDeComprobante = "INGRESO";
                        bool istipoDeComprobante = obj2.Attributes["tipoDeComprobante"] != null;
                        if (istipoDeComprobante)
                        {
                            tipoDeComprobante = obj2.Attributes["tipoDeComprobante"].InnerText.Trim().ToUpper();
                        }

                        String total = "";
                        bool isTotal = obj2.Attributes["total"] != null;
                        if (isTotal)
                        {
                            total = obj2.Attributes["total"].InnerText;
                        }

                        bool isFecha = obj2.Attributes["fecha"] != null;
                        String fecha = "";
                        if (isFecha)
                        {
                            fecha = obj2.Attributes["fecha"].InnerText;
                        }
                        bool isFolio = obj2.Attributes["folio"] != null;
                        String folio = "";
                        if (isFolio)
                        {
                            folio = obj2.Attributes["folio"].InnerText;
                        }
                        if (estoyEnCancelados)
                        {
                            String query1 = "UPDATE [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] set STATUS = '0' WHERE folioFiscal = '" + folio_fiscal + "'";
                            totalDeCancelados++;
                            try
                            {
                                using (SqlConnection connection = new SqlConnection(connString))
                                {
                                    connection.Open();
                                    SqlCommand cmd = new SqlCommand(query1, connection);
                                    cmd.ExecuteNonQuery();

                                    String queryCheck1 = "SELECT BUNIT, JRNAL_NO, JRNAL_LINE, CONCEPTO, FUNCION, PROJECT, descripcionLI, AMOUNT, Consecutivo, FOLIO_FISCAL FROM [" + Properties.Settings.Default.Database + "].[dbo].[FISCAL_xml] WHERE folioFiscal = '" + folio_fiscal + "'";
                                    SqlCommand cmdCheck = new SqlCommand(queryCheck1, connection);
                                    SqlDataReader reader = cmdCheck.ExecuteReader();

                                    if (reader.HasRows)
                                    {
                                        String BUNIT = "";
                                        String JRNAL_NO = "";
                                        String JRNAL_LINE = "";
                                        String CONCEPTO = "";
                                        String FUNCION = "";
                                        String PROJECT = "";
                                        String descripcionLI = "";
                                        String AMOUNT = "";
                                        String Consecutivo = "";
                                        String FOLIO_FISCAL = "";
                                        mensajeParaElCorreo.Append(this.Enters + "Los cancelados estan ligados a los siguientes movimientos: ");
                                        while (reader.Read())
                                        {
                                            BUNIT = reader.GetString(0).Trim();
                                            JRNAL_NO = Convert.ToString(reader.GetInt32(1));
                                            JRNAL_LINE = Convert.ToString(reader.GetInt32(2));
                                            CONCEPTO = reader.GetString(3).Trim();
                                            FUNCION = reader.GetString(4).Trim();
                                            PROJECT = reader.GetString(5).Trim();
                                            descripcionLI = reader.GetString(6).Trim();
                                            AMOUNT = Convert.ToString(reader.GetDecimal(7));
                                            Consecutivo = reader.GetString(8).Trim();
                                            FOLIO_FISCAL = reader.GetString(9).Trim();

                                            mensajeParaElCorreo.Append(this.Enters + BUNIT + " " + JRNAL_NO + " " + JRNAL_LINE + " " + CONCEPTO + " " + FUNCION + " " + PROJECT + " " + descripcionLI + " " + AMOUNT + " " + FOLIO_FISCAL + " " + Consecutivo);

                                        }
                                    }
                                }
                            }
                            catch (Exception ex1)
                            {
                                System.Windows.Forms.MessageBox.Show(ex1.ToString(), "Error Message1", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }

                        }
                        else
                        {

                            String query = "";
                            int STATUS = -1;
                            if (this.AnoSel.IndexOf("Emitidos") != -1)
                            {
                                if (tipoDeComprobante.Equals("INGRESO"))
                                {
                                    STATUS = 2;
                                    query = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] (folioFiscal,nombreArchivoXML,ruta,rfc,razonSocial,total,folio,fechaExpedicion,nombreArchivoPDF,STATUS,ocultaEnLigar,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + nombreDelArchivo + "', '" + carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual + "', '" + rfcReceptor + "', '" + nombreReceptor + "', " + total + ", '" + folio + "' , '" + fecha + "', '" + folio_fiscal + ".pdf','2',0,'" + Properties.Settings.Default.RFC + "')";
                                }
                                else
                                {
                                    STATUS = 1;
                                    query = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] (folioFiscal,nombreArchivoXML,ruta,rfc,razonSocial,total,folio,fechaExpedicion,nombreArchivoPDF,STATUS,ocultaEnLigar,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + nombreDelArchivo + "', '" + carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual + "', '" + rfcReceptor + "', '" + nombreReceptor + "', " + total + ", '" + folio + "' , '" + fecha + "', '" + folio_fiscal + ".pdf','1',0,'" + Properties.Settings.Default.RFC + "')";
                                }
                                insertaProveedor(rfcReceptor, nombreReceptor);
                                sincroniza(fecha, rfcReceptor, nombreReceptor, STATUS, total, folio, folio_fiscal, Properties.Settings.Default.RFC, "");
                            }
                            else
                            {
                                if (tipoDeComprobante.Equals("INGRESO"))
                                {
                                    STATUS = 1;
                                    query = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] (folioFiscal,nombreArchivoXML,ruta,rfc,razonSocial,total,folio,fechaExpedicion,nombreArchivoPDF,STATUS,ocultaEnLigar,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + nombreDelArchivo + "', '" + carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual + "', '" + rfc + "', '" + razon + "', " + total + ", '" + folio + "' , '" + fecha + "', '" + folio_fiscal + ".pdf','1',0,'" + Properties.Settings.Default.RFC + "')";
                                }
                                else
                                {
                                    STATUS = 2;
                                    query = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] (folioFiscal,nombreArchivoXML,ruta,rfc,razonSocial,total,folio,fechaExpedicion,nombreArchivoPDF,STATUS,ocultaEnLigar,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + nombreDelArchivo + "', '" + carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual + "', '" + rfc + "', '" + razon + "', " + total + ", '" + folio + "' , '" + fecha + "', '" + folio_fiscal + ".pdf','2',0,'" + Properties.Settings.Default.RFC + "')";
                                }
                                //query = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] (folioFiscal,nombreArchivoXML,ruta,rfc,razonSocial,total,folio,fechaExpedicion,nombreArchivoPDF,STATUS,ocultaEnLigar) VALUES ('" + folio_fiscal + "', '" + nombreDelArchivo + "', '" + carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual + "', '" + rfc + "', '" + razon + "', " + total + ", '" + folio + "' , '" + fecha + "', '" + folio_fiscal + ".pdf','1',0)";
                                insertaProveedor(rfc, razon);
                                sincroniza(fecha, rfc,  razon,  STATUS,  total,  folio,  folio_fiscal, Properties.Settings.Default.RFC, "");
                            }
                            String queryCheck = "SELECT * FROM [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] WHERE folioFiscal = '" + folio_fiscal + "'";

                            try
                            {
                                using (SqlConnection connection = new SqlConnection(connString))
                                {
                                    connection.Open();
                                    SqlCommand cmdCheck = new SqlCommand(queryCheck, connection);
                                    SqlDataReader reader = cmdCheck.ExecuteReader();
                                    if (!reader.Read())
                                    {
                                        reader.Close();
                                        connection.Close();
                                        connection.Open();
                                        SqlCommand cmd = new SqlCommand(query, connection);
                                        cmd.ExecuteNonQuery();
                                        PdfContents Contents = null;
                                        PdfPage Page = null;
                                        const Double Width = 5.15;
                                        const Double Height = 10.65;
                                        const Double FontSize = 9.0;
                                        PdfFileWriter.TextBox Box = null;
                                        if (cadaCuantasHorasGlobal == 0 || 1 == 1)//no estoy en modo de horas
                                        {
                                            String FileName = carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual.ToString() + (object)Path.DirectorySeparatorChar + folio_fiscal + ".pdf";
                                            Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, FileName);
                                            DefineFontResources();
                                            DefineTilingPatternResource();
                                            Page = new PdfPage(Document);
                                            Contents = new PdfContents(Page);
                                            Contents.SaveGraphicsState();
                                            Contents.Translate(0.1, 0.1);
                                            Box = new PdfFileWriter.TextBox(Width, 0.25);
                                        }
                                        XmlNodeList conceptos = doc.GetElementsByTagName("cfdi:Concepto");
                                        if (conceptos.Count == 0)
                                        {
                                            conceptos = doc.GetElementsByTagName("Concepto");
                                        }

                                        int i;
                                        String conceptosString = "";
                                        for (i = 0; i < conceptos.Count; i++)
                                        {
                                            XmlNode objy = conceptos.Item(i);
                                            String cantidadc = "";
                                            bool isCantidadc = objy.Attributes["cantidad"] != null;
                                            if (isCantidadc)
                                            {
                                                cantidadc = objy.Attributes["cantidad"].InnerText;
                                            }
                                            String unidadc = "";
                                            bool isUnidadc = objy.Attributes["unidad"] != null;
                                            if (isUnidadc)
                                            {
                                                unidadc = objy.Attributes["unidad"].InnerText;
                                            }
                                            String descripcionc = "";
                                            bool isdescripcionc = objy.Attributes["descripcion"] != null;
                                            if (isdescripcionc)
                                            {
                                                descripcionc = objy.Attributes["descripcion"].InnerText;
                                            }
                                            String importec = "";
                                            bool isimportec = objy.Attributes["importe"] != null;
                                            if (isimportec)
                                            {
                                                importec = objy.Attributes["importe"].InnerText;
                                            }
                                            conceptosString = conceptosString + "\n" + cantidadc + " " + descripcionc + " $" + importec;
                                        }
                                        String impuestosString = "";
                                        double totalDeRetenciones = 0;
                                        XmlNodeList retencionesLocales = doc.GetElementsByTagName("implocal:RetencionesLocales");
                                        if (retencionesLocales.Count == 0)
                                        {
                                            retencionesLocales = doc.GetElementsByTagName("RetencionesLocales");
                                        }
                                        for (i = 0; i < retencionesLocales.Count; i++)
                                        {
                                            XmlNode objn = retencionesLocales.Item(i);
                                            String cantidad = "0";
                                            String impuesto = "";
                                            float tasa = 0;
                                            bool isCantidad = objn.Attributes["Importe"] != null;
                                            if (isCantidad)
                                            {
                                                totalDeRetenciones += Convert.ToDouble(objn.Attributes["Importe"].InnerText);
                                                cantidad = objn.Attributes["Importe"].InnerText;
                                                impuesto = objn.Attributes["ImpLocRetenido"].InnerText;
                                                tasa = float.Parse(objn.Attributes["TasadeRetencion"].InnerText);
                                                float importe = float.Parse(cantidad);
                                                String queryCheckImpuesto = "SELECT * FROM [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] WHERE folioFiscal = '" + folio_fiscal + "' and impuesto = '" + impuesto + "' and tasa = " + tasa + " and importe = " + importe;
                                                SqlCommand cmdCheckImpuesto = new SqlCommand(queryCheckImpuesto, connection);
                                                SqlDataReader readerImpuesto = cmdCheckImpuesto.ExecuteReader();
                                                impuestosString = impuestosString + "\nImpuesto: " + impuesto + "\nTasa: " + tasa + "\nImporte: " + importe;
                                                if (!readerImpuesto.HasRows)
                                                {
                                                    readerImpuesto.Close();
                                                    String queryImpuesto = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] (folioFiscal,impuesto,tasa,importe,tipo,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + impuesto + "', " + tasa + ", " + importe + ",2,'" + Properties.Settings.Default.RFC + "')";
                                                    SqlCommand cmdImpuesto = new SqlCommand(queryImpuesto, connection);
                                                    cmdImpuesto.ExecuteNonQuery();
                                                }
                                                else
                                                {
                                                    readerImpuesto.Close();
                                                }
                                            }
                                            iva = Convert.ToString(float.Parse(iva) + float.Parse(cantidad));
                                        }

                                        XmlNodeList retenciones = doc.GetElementsByTagName("cfdi:Retencion");
                                        if (retenciones.Count == 0)
                                        {
                                            retenciones = doc.GetElementsByTagName("Retencion");
                                        }

                                        for (i = 0; i < retenciones.Count; i++)
                                        {
                                            XmlNode objn = retenciones.Item(i);
                                            String cantidad = "0";
                                            String impuesto = "";
                                            float tasa = 0;
                                            bool isCantidad = objn.Attributes["importe"] != null;
                                            if (isCantidad)
                                            {
                                                totalDeRetenciones += Convert.ToDouble(objn.Attributes["importe"].InnerText);
                                                cantidad = objn.Attributes["importe"].InnerText;
                                                impuesto = objn.Attributes["impuesto"].InnerText;
                                                tasa = 0;
                                                float importe = float.Parse(cantidad);
                                                String queryCheckImpuesto = "SELECT * FROM [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] WHERE folioFiscal = '" + folio_fiscal + "' and impuesto = '" + impuesto + "' and tasa = " + tasa + " and importe = " + importe;
                                                SqlCommand cmdCheckImpuesto = new SqlCommand(queryCheckImpuesto, connection);
                                                SqlDataReader readerImpuesto = cmdCheckImpuesto.ExecuteReader();
                                                impuestosString = impuestosString + "\nImpuesto: " + impuesto + "\nImporte: " + importe;
                                                if (!readerImpuesto.HasRows)
                                                {
                                                    readerImpuesto.Close();
                                                    String queryImpuesto = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] (folioFiscal,impuesto,tasa,importe,tipo,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + impuesto + "', " + tasa + ", " + importe + ",2,'" + Properties.Settings.Default.RFC + "')";
                                                    SqlCommand cmdImpuesto = new SqlCommand(queryImpuesto, connection);
                                                    cmdImpuesto.ExecuteNonQuery();
                                                }
                                                else
                                                {
                                                    readerImpuesto.Close();
                                                }
                                            }
                                            iva = Convert.ToString(float.Parse(iva) + float.Parse(cantidad));
                                        }

                                        if (totalDeRetenciones > 0.0)
                                        {
                                            double nuevoTotal = Math.Round(totalDeRetenciones + Convert.ToDouble(total), 2);
                                            String query2 = "UPDATE [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] set total = " + nuevoTotal + "  WHERE folioFiscal = '" + folio_fiscal + "'";
                                            try
                                            {
                                                using (SqlCommand cmdx = new SqlCommand(query2, connection))
                                                {
                                                    cmd.ExecuteNonQuery();
                                                }
                                            }
                                            catch (Exception ex3)
                                            {
                                                ex3.ToString();
                                            }
                                        }

                                        XmlNodeList trasladosLocales = doc.GetElementsByTagName("implocal:TrasladosLocales");
                                        if (trasladosLocales.Count == 0)
                                        {
                                            trasladosLocales = doc.GetElementsByTagName("TrasladosLocales");
                                        }
                                        for (i = 0; i < trasladosLocales.Count; i++)
                                        {
                                            XmlNode objn = trasladosLocales.Item(i);
                                            String cantidad = "0";
                                            String impuesto = "";
                                            float tasa = 0;
                                            bool isCantidad = objn.Attributes["Importe"] != null;
                                            if (isCantidad)
                                            {
                                                cantidad = objn.Attributes["Importe"].InnerText;
                                                impuesto = objn.Attributes["ImpLocTrasladado"].InnerText;
                                                tasa = float.Parse(objn.Attributes["TasadeTraslado"].InnerText);
                                                float importe = float.Parse(cantidad);
                                                String queryCheckImpuesto = "SELECT * FROM [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] WHERE folioFiscal = '" + folio_fiscal + "' and impuesto = '" + impuesto + "' and tasa = " + tasa + " and importe = " + importe;
                                                SqlCommand cmdCheckImpuesto = new SqlCommand(queryCheckImpuesto, connection);
                                                SqlDataReader readerImpuesto = cmdCheckImpuesto.ExecuteReader();
                                                impuestosString = impuestosString + "\nImpuesto: " + impuesto + "\nTasa: " + tasa + "\nImporte: " + importe;
                                                if (!readerImpuesto.HasRows)
                                                {
                                                    readerImpuesto.Close();
                                                    String queryImpuesto = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] (folioFiscal,impuesto,tasa,importe,tipo,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + impuesto + "', " + tasa + ", " + importe + ",1,'" + Properties.Settings.Default.RFC + "')";
                                                    SqlCommand cmdImpuesto = new SqlCommand(queryImpuesto, connection);
                                                    cmdImpuesto.ExecuteNonQuery();
                                                }
                                                else
                                                {
                                                    readerImpuesto.Close();
                                                }
                                            }
                                            iva = Convert.ToString(float.Parse(iva) + float.Parse(cantidad));
                                        }

                                        XmlNodeList traslados = doc.GetElementsByTagName("cfdi:Traslado");
                                        if (traslados.Count == 0)
                                        {
                                            traslados = doc.GetElementsByTagName("Traslado");
                                        }
                                        for (i = 0; i < traslados.Count; i++)
                                        {
                                            XmlNode objn = traslados.Item(i);
                                            String cantidad = "0";
                                            String impuesto = "";
                                            float tasa = 0;
                                            bool isCantidad = objn.Attributes["importe"] != null;
                                            if (isCantidad)
                                            {
                                                cantidad = objn.Attributes["importe"].InnerText;
                                                impuesto = objn.Attributes["impuesto"].InnerText;
                                                tasa = float.Parse(objn.Attributes["tasa"].InnerText);
                                                float importe = float.Parse(cantidad);
                                                String queryCheckImpuesto = "SELECT * FROM [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] WHERE folioFiscal = '" + folio_fiscal + "' and impuesto = '" + impuesto + "' and tasa = " + tasa + " and importe = " + importe;
                                                SqlCommand cmdCheckImpuesto = new SqlCommand(queryCheckImpuesto, connection);
                                                SqlDataReader readerImpuesto = cmdCheckImpuesto.ExecuteReader();
                                                impuestosString = impuestosString + "\nImpuesto: " + impuesto + "\nTasa: " + tasa + "\nImporte: " + importe;
                                                if (!readerImpuesto.HasRows)
                                                {
                                                    readerImpuesto.Close();
                                                    String queryImpuesto = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] (folioFiscal,impuesto,tasa,importe,tipo,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + impuesto + "', " + tasa + ", " + importe + ",1,'" + Properties.Settings.Default.RFC + "')";
                                                    SqlCommand cmdImpuesto = new SqlCommand(queryImpuesto, connection);
                                                    cmdImpuesto.ExecuteNonQuery();
                                                }
                                                else
                                                {
                                                    readerImpuesto.Close();
                                                }
                                            }
                                            iva = Convert.ToString(float.Parse(iva) + float.Parse(cantidad));
                                        }
                                        if (cadaCuantasHorasGlobal == 0 || 1 == 1)//no estoy en modo de horas
                                        {
                                            Box.AddText(ArialNormal, FontSize,
                                           "Cliente: " + nombreReceptor + "\n" +
                                           "RFC: " + rfcReceptor + "\n" +
                                           "Emisor: " + razon + "\n" +
                                           "RFC: " + rfc + "\n" +
                                           "Domicilio Fiscal: " + calle + " " + noExterior + " " + colonia + " " + municipio + " " + estado + "\n" +
                                           "Folio: " + folio + "\nFolio Fiscal: " + folio_fiscal + "\nTotal: $" + total + "\nFecha de Expedicion: " + fecha + conceptosString + impuestosString + "\nNo de Serie del Certificado del SAT: " + noCertificadoSAT + "\nSello digital del CFDI:\n" + selloCFD + "\n\nSello del SAT:\n" + selloSAT + "\n\n\nEste documento es una representación impresa de un CFDI");
                                            Box.AddText(ArialNormal, FontSize, "\n");
                                            Double PosY = Height;
                                            Contents.DrawText(0.0, ref PosY, 0.0, 0, 0.015, 0.05, TextBoxJustify.FitToWidth, Box);
                                            Contents.RestoreGraphicsState();
                                            Contents.SaveGraphicsState();
                                            String DataString = "?re=" + rfc + "&rr=" + rfcReceptor + "&tt=" + total + "&id=" + folio_fiscal;
                                            PdfQRCode QRCode = new PdfQRCode(Document, DataString, ErrorCorrection.M);
                                            Contents.DrawQRCode(QRCode, 6.0, 6.8, 1.2);
                                            Contents.RestoreGraphicsState();
                                            Document.CreateFile();
                                        }
                                        totalDeDescargados++;
                                    }
                                    else
                                    {
                                        this.cuantosYaExistian++;
                                        totalDeYaExistian++;
                                    }

                                }
                            }
                            catch (Exception ex1)
                            {
                                ex1.ToString();
                                System.Windows.Forms.Clipboard.SetText(query);

                                this.cuantosNoSeInsertaron++;
                                //   System.Windows.Forms.MessageBox.Show("Error Message", ex1.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                        }//else if estoyEnCancelados
                    }//else de empty

                    ++this.posicion;
                    if (this.posicion < this.ligas.Count)
                    {
                        if (!this.Cancelar)
                        {
                            this.Descargados.Add(e.Item);
                            this.proceso.Text = string.Format("Descargando {0} de {1}, Ya existian: {2}, Con errores: {3} ", (object)(this.posicion + 1), (object)this.ligas.Count.ToString() , (object)this.cuantosYaExistian, (object)this.cuantosNoSeInsertaron);
                            this.Descarga();
                        }
                        else
                        {
                            this.Cursor = System.Windows.Forms.Cursors.Arrow;
                            this.webControl1.Cursor = System.Windows.Forms.Cursors.Arrow;
                 //           Mensaje.MostrarMensaje(Constantes.TipoMensaje.Detenido, "Descarga", "Proceso cancelado por el usuario");
                        }
                    }
                    else
                    {

                        //                  enQueHoraVoyGlobal
                        //                    cadaCuantasHorasGlobal

                        int horaQueSigue = enQueHoraVoyGlobal + cadaCuantasHorasGlobal;
                        if(horaQueSigue<24 && cadaCuantasHorasGlobal!=0)//sigue con las horas
                        {
                            enQueHoraVoyGlobal = enQueHoraVoyGlobal + cadaCuantasHorasGlobal;
                            if(estoyEnEmitidos)
                            {
                                tmrDecimoCuarto.Start();
                            }
                            else
                            {
                                tmrQuintoPrimo.Start();
                            }
                        }
                        else
                        {//cambia el dia
                            enQueHoraVoyGlobal = 0;
                            //cambia un dia
                            if (modoGlobal == 2 && estoyEnEmitidos)
                            {
                                DateTime now = DateTime.Now;
                                int year = now.Year - anoAnterior;
                                int month = now.Month;
                                if (modoGlobal == 2)//ultrapesado
                                {
                                    month = mesActual + 1;
                                }

                                int diaFinal = 28;
                                if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
                                {
                                    diaFinal = 31;
                                }
                                else
                                {
                                    if (month == 4 || month == 6 || month == 9 || month == 11)
                                    {
                                        diaFinal = 30;
                                    }
                                    else
                                    {
                                        if (year % 4 == 0)//ano bisiesto
                                        {
                                            diaFinal = 29;
                                        }
                                    }
                                }

                                if (diaActual < diaFinal)
                                {
                                    diaActual++;
                                    tmrDecimoCuarto.Start();
                                    return;
                                }
                                else
                                {
                                    diaActual = 1;
                                    if (mesActual < 11)
                                    {
                                        mesActual++;
                                        tmrDecimoCuarto.Start();
                                        return;
                                    }
                                    else
                                    {
                                        tmrDecimoSexto.Start();
                                        return;
                                    }
                                }

                            }
                            if (modoGlobal == 1)
                            {
                                if (estoyEnEmitidos)
                                {
                                    mandaCorreo();
                                }
                                else
                                {
                                    empiezaConLosEmitidos();
                                }
                            }
                            else
                            {
                                this.proceso.Text = string.Format("Descargando {0} de {1}, Ya existian: {2}, Con errores: {3}", (object)this.posicion, (object)this.ligas.Count.ToString(), (object)this.cuantosYaExistian, (object)this.cuantosNoSeInsertaron);
                                this.Descargados.Add(e.Item);
                                this.Cursor = System.Windows.Forms.Cursors.Arrow;
                                this.webControl1.Cursor = System.Windows.Forms.Cursors.Arrow;
                                this.proceso.Text = string.Format("Descarga Finalizada {0} de {1}, Ya existian: {2}, Con errores: {3}", (object)this.posicion, (object)this.ligas.Count.ToString(), (object)this.cuantosYaExistian, (object)this.cuantosNoSeInsertaron);
                                if (estoyEnCancelados)
                                {
                                    //ya termine
                                    mensajeParaElCorreo.Append(totalDeCancelados);
                                    return;
                                }
                                if (!estoyEnCancelados && estoyEnEmitidos)
                                {
                                    //agregar para debuguear emitidos
                                    mensajeParaElCorreo.Append(Enters + Enters + "Facturas Emitidas totales: " + (object)this.ligas.Count.ToString() + " Ya existian: " + (object)this.cuantosYaExistian);
                                    tmrDecimoSexto.Start();
                                    return;
                                }
                                DateTime now = DateTime.Now;
                                int year = now.Year - anoAnterior;
                                int month = now.Month;
                                if (modoGlobal == 2)//ultrapesado
                                {
                                    month = mesActual + 1;
                                }

                                int diaFinal = 28;
                                if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
                                {
                                    diaFinal = 31;
                                }
                                else
                                {
                                    if (month == 4 || month == 6 || month == 9 || month == 11)
                                    {
                                        diaFinal = 30;
                                    }
                                    else
                                    {
                                        if (year % 4 == 0)//ano bisiesto
                                        {
                                            diaFinal = 29;
                                        }
                                    }
                                }

                                if (diaActual < diaFinal)
                                {
                                    diaActual++;
                                    if (estoyEnElMesAnterior)
                                    {
                                        tmrDecimo.Start();
                                    }
                                    else
                                    {
                                        if(cadaCuantasHorasGlobal==0)//sin horas
                                        {
                                            tmrQuinto.Start();
                                        }
                                        else
                                        {
                                            tmrQuintoPrimo.Start();
                                        }

                                    }
                                }
                                else
                                {
                                    if (estoyEnElMesAnterior)
                                    {
                                        estoyEnElMesAnterior = false;
                                        diaActual = 1;
                                        empiezaConLosCancelados();
                                    }
                                    else
                                    {
                                        if (modoGlobal == 2)//ultrapesado
                                        {
                                            if (mesActual < 11)
                                            {
                                                mesActual++;
                                                diaActual = 1;
                                                tmrDecimo.Start();
                                            }
                                            else
                                            {
                                                estoyEnElMesAnterior = false;
                                                diaActual = 1;
                                                mesActual = 0;
                                                empiezaConLosCancelados();
                                            }
                                        }
                                        else//modo pesado
                                        {
                                            empiezaConElMesAnterior();
                                        }
                                    }
                                }
                            }
                        }//if cambia un dia
                    }
                }
            }
            catch (Exception ex)
            {
               System.Windows.Forms.MessageBox.Show( ex.ToString(), "Error Title2", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

               //  Logs.Escribir("Error en download complete : " + ex.ToString());
            }
        }
Example #39
0
		private void OnWebViewDownloadCanceled(object sender, DownloadEventArgs e)
		{
			FormMain.Instance.ResumePages();
			FormDownloadProgress.CloseProgress();
		}
Example #40
0
		private void OnWebViewDownloadCompleted(object sender, DownloadEventArgs e)
		{
			FormMain.Instance.ResumePages();
			FormDownloadProgress.CloseProgress();
			if (".MP4".Equals(Path.GetExtension(e.Item.FullPath), StringComparison.OrdinalIgnoreCase))
			{
				if (HandleVideoDownloaded(e.Item.FullPath))
					return;
			}
			using (var formComplete = new FormFileDownloadComplete(e.Item.FullPath))
			{
				formComplete.ShowDialog(FormMain.Instance);
			}
		}
 void IDownloadNotification.DownloadModified(object sender, DownloadEventArgs e)
 {
     if (this._cancellationPending)
     {
         ((FileDownloader) sender).Cancel();
     }
     this.asyncOperation.Post(this.progressReporter, new DeploymentProgressChangedEventArgs(e.Progress, null, e.BytesCompleted, e.BytesTotal, this._state, null));
 }
 void IDownloadNotification.DownloadCompleted(object sender, DownloadEventArgs e)
 {
     this._downloadedAppSize = e.BytesCompleted;
 }
Example #43
0
		private void OnWebViewDownloadCanceled(Object sender, DownloadEventArgs e)
		{
			TabControl.Enabled = true;
			FormProgress.CloseProgress();
		}
 public void DownloadCompleted(object sender, DownloadEventArgs e)
 {
     base.BeginInvoke(this.disableMethodInvoker);
 }
Example #45
0
 private void DownloadStartedHandler(object sender, DownloadEventArgs e)
 {
     if (InvokeRequired)
     {
         Invoke((EventHandler<DownloadEventArgs>)DownloadStartedHandler, sender, e);
         return;
     }
     var control = new DownloadControl();
     control.Visible = false;
     control.Left = ClientRectangle.Left;
     control.Width = ClientSize.Width;
     control.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
     control.FileName = Path.GetFileName(e.Task.TargetFile);
     downloadControls.Add(e.Task, control);
     Controls.Add(control);
     UpdateLayout();
 }
Example #46
0
		private void OnWebViewDownloadUpdated(Object sender, DownloadEventArgs e)
		{
			FormProgress.SetDetails(String.Format("{0} - {1}%", Path.GetFileName(e.Item.FullPath), e.Item.PercentageComplete));
			Application.DoEvents();
		}
 private static void ProcessDownloadedFile(object sender, DownloadEventArgs e)
 {
     if (e.Cookie != null)
     {
         string fileName = Path.GetFileName(e.FileLocalPath);
         FileDownloader downloader = (FileDownloader) sender;
         if ((e.FileResponseUri != null) && !e.FileResponseUri.Equals(e.FileSourceUri))
         {
             throw new InvalidDeploymentException(ExceptionTypes.AppFileLocationValidation, string.Format(CultureInfo.CurrentUICulture, Resources.GetString("Ex_DownloadAppFileAsmRedirected"), new object[] { fileName }));
         }
         DependencyDownloadCookie cookie = (DependencyDownloadCookie) e.Cookie;
         if (cookie.ManifestElement is DependentAssembly)
         {
             DependentAssembly manifestElement = (DependentAssembly) cookie.ManifestElement;
             AssemblyManifest deployManifest = cookie.DeployManifest;
             AssemblyManifest appManifest = cookie.AppManifest;
             AssemblyManifest assemblyManifest = new AssemblyManifest(e.FileLocalPath);
             if (!assemblyManifest.Identity.Matches(manifestElement.Identity, true))
             {
                 throw new InvalidDeploymentException(ExceptionTypes.RefDefValidation, string.Format(CultureInfo.CurrentUICulture, Resources.GetString("Ex_DownloadRefDefMismatch"), new object[] { fileName }));
             }
             if (assemblyManifest.Identity.Equals(deployManifest.Identity) || assemblyManifest.Identity.Equals(appManifest.Identity))
             {
                 throw new InvalidDeploymentException(ExceptionTypes.ManifestSemanticValidation, string.Format(CultureInfo.CurrentUICulture, Resources.GetString("Ex_AppPrivAsmIdSameAsDeployOrApp"), new object[] { assemblyManifest.Identity.ToString() }));
             }
             System.Deployment.Application.Manifest.File[] files = assemblyManifest.Files;
             for (int i = 0; i < files.Length; i++)
             {
                 Uri fileSourceUri = MapFileSourceUri(deployManifest, e.FileSourceUri, files[i].Name);
                 if (!fileSourceUri.AbsoluteUri.Equals(e.FileSourceUri.AbsoluteUri, StringComparison.OrdinalIgnoreCase))
                 {
                     string directoryName = Path.GetDirectoryName(e.FileLocalPath);
                     AddFileToDownloader(downloader, deployManifest, appManifest, files[i], fileSourceUri, directoryName, files[i].NameFS, files[i].HashCollection);
                 }
             }
             downloader.ComponentVerifier.AddFileForVerification(e.FileLocalPath, manifestElement.HashCollection);
             if (assemblyManifest.Identity.PublicKeyToken == null)
             {
                 downloader.ComponentVerifier.AddSimplyNamedAssemblyForVerification(e.FileLocalPath, assemblyManifest);
             }
             else
             {
                 downloader.ComponentVerifier.AddStrongNameAssemblyForVerification(e.FileLocalPath, assemblyManifest);
             }
         }
         else if (cookie.ManifestElement is System.Deployment.Application.Manifest.File)
         {
             System.Deployment.Application.Manifest.File file = (System.Deployment.Application.Manifest.File) cookie.ManifestElement;
             downloader.ComponentVerifier.AddFileForVerification(e.FileLocalPath, file.HashCollection);
         }
     }
 }
		private void OnExtensionsWebViewDownloadCompleted(Object sender, DownloadEventArgs e)
		{
			FormMain.Instance.ResumePages();
			FormDownloadProgress.CloseProgress();
		}
Example #49
0
 private void OnFileDownload(object sender, DownloadEventArgs e)
 {
     var request = new DownloadManager.Request(Uri.Parse(e.Url));
     // TODO: this should be fixed on the server!
     request.AllowScanningByMediaScanner();
     request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
     // TODO: set proper file name
     request.SetDestinationInExternalPublicDir(Environment.DirectoryDownloads, "report.docx");
     var dm = this.Activity.GetSystemService(Context.DownloadService).JavaCast<DownloadManager>();
     dm.Enqueue(request);
     this.GoBack();
     Toast.MakeText(this.Activity, "Свалям файла...", ToastLength.Long).Show();
 }
Example #50
0
 private void WebView_Download(object sender, DownloadEventArgs downloadEventArgs)
 {
     //TODO: Do we need to handle this somehow?
 }
		private void OnSlideContentWebViewDownloadCompleted(object sender, DownloadEventArgs e)
		{
			if (!_extensionsManager.LinkViewContentExtension.ContentEnabled) return;
			switch (_afterDownloadAction)
			{
				case AfterDownloadAction.Print:
					ExtensionsManager.PrintFile(
						e.Item.FullPath,
						(_extensionsManager.LinkViewContentExtension.CurrentPrintableContent.CurrentPage + 1) ?? 1);
					break;
				default:
					AppManager.Instance.ShowFloater(() =>
					{
						if (_extensionsManager.LinkViewContentExtension.CurrentLinkViewContent?.ContentType == LinkContentType.Video)
						{
							FormProgress.ShowProgress();
							FormProgress.SetTitle("Chill-Out for a few seconds...\nGenerating slides so your presentation can look AWESOME!");
							PowerPointSingleton.Instance.InsertVideoIntoActivePresentation(e.Item.FullPath);
							FormProgress.CloseProgress();
						}
						else if (_extensionsManager.LinkViewContentExtension.CurrentLinkViewContent?.ContentType == LinkContentType.PowerPoint)
						{
							FormProgress.ShowProgress();
							FormProgress.SetTitle("Chill-Out for a few seconds...\nGenerating slides so your presentation can look AWESOME!");
							PowerPointSingleton.Instance.AppendSlidesFromFile(e.Item.FullPath);
							FormProgress.CloseProgress();
						}
					}, null);
					break;
			}
		}
Example #52
0
		private void OnWebViewDownloadCompleted(Object sender, DownloadEventArgs e)
		{
			TabControl.Enabled = true;
			FormProgress.CloseProgress();
			using (var formComplete = new FormFileDownloadComplete(e.Item.FullPath))
			{
				formComplete.StartPosition=FormStartPosition.CenterScreen;
				formComplete.ShowDialog();
			}
		}
Example #53
0
 static void downloader_ProgressChanged(object sender, DownloadEventArgs e)
 {
     Console.WriteLine("Progress " + e.PercentDone);
 }
 public void DownloadCompleted(object sender, DownloadEventArgs e)
 {
 }
Example #55
0
 void OnDownloadUpdated(object sender, DownloadEventArgs e)
 {
     Log("DownloadUpdated: " + e.downloads[0].downloadState + ", " + e.downloads[0].progress);
 }