public static void SetIeCompatibility()
        {
            WebBrowser webBrowserInstance = new WebBrowser();
            int iEnumber = webBrowserInstance.Version.Major; //reference: http://support.microsoft.com/kb/969393/en-us
            int compatibilityCode = iEnumber * 1000;//Reference:http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation
            webBrowserInstance.Dispose();
            Trace.TraceInformation("Using Internet Explorer {0}", iEnumber);

            var fileName = Path.GetFileName(Application.ExecutablePath);
            try
            {
                //Note: write to HKCU (HKEY_CURRENT_USER) instead of HKLM (HKEY_LOCAL_MACHINE) because HKLM need admin privilege while HKCU do not. Ref:http://stackoverflow.com/questions/4612255/regarding-ie9-webbrowser-control
                Registry.SetValue(@"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION",
                                  fileName,
                                  compatibilityCode);
            }
            catch (Exception ex)
            {
                Trace.TraceError(String.Format("Error setting IE compatibility: {0}", ex));
            }
            try //for 32 bit IE on 64 bit windows
            {
                Registry.SetValue(
                    @"HKEY_CURRENT_USER\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION",
                    fileName,
                    compatibilityCode);
            }
            catch (Exception ex)
            {
                Trace.TraceError(String.Format("Error setting IE compatibility: {0}", ex));
            }
        }
Exemple #2
0
    /// <summary>
    /// This method creates a new form with a webbrowser of correct size on it,
    /// to make a fullsize website screenhot.
    /// </summary>
    /// <param name="navigatingArgs">The <see cref="WebBrowserNavigatingEventArgs"/> instance containing the event data,
    /// especially the url.</param>
    /// <param name="filename">The filename to save the screenshot to.</param>
    public static void DoScreenshot(WebBrowserNavigatingEventArgs navigatingArgs, string filename)
    {
      newTargetUrl = navigatingArgs.Url;
      newScreenshotFilename = filename;

      var tempBrowser = new WebBrowser();
      var dummyForm = new Form { ClientSize = new Size(1, 1), FormBorderStyle = FormBorderStyle.None };
      dummyForm.ShowInTaskbar = false;
      dummyForm.Controls.Add(tempBrowser);
      dummyForm.Show();
      tempBrowser.ScrollBarsEnabled = true;
      tempBrowser.ScriptErrorsSuppressed = true;
      tempBrowser.DocumentCompleted += WebBrowserDocumentCompleted;

      if (navigatingArgs.TargetFrameName != string.Empty)
      {
        tempBrowser.Navigate(navigatingArgs.Url, navigatingArgs.TargetFrameName);
      }
      else
      {
        tempBrowser.Navigate(newTargetUrl);
      }

      while (tempBrowser.ReadyState != WebBrowserReadyState.Complete)
      {
        Application.DoEvents();
      }

      tempBrowser.Dispose();
    }
Exemple #3
0
        public Bitmap GenerateScreenshot(string url, int width, int height)
        {
            WebBrowser wb = new WebBrowser();
            wb.NewWindow += wb_NewWindow;
            wb.ScrollBarsEnabled = false;
            wb.ScriptErrorsSuppressed = true;
            wb.Navigate(url);
            while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }

            Thread.Sleep(int.Parse(ConfigurationSettings.AppSettings["WaitForLoadWebSite"].ToString().Trim()));

            wb.Width = width;
            wb.Height = height;

            if (width == -1)
            {

                wb.Width = wb.Document.Body.ScrollRectangle.Width;
            }

            if (height == -1)
            {

                wb.Height = wb.Document.Body.ScrollRectangle.Height;
            }

            Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
            wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
            wb.Dispose();
            return bitmap;
        }
        /// <summary>
        /// Returns a SharePoint on-premises / SharePoint Online ClientContext object. Requires claims based authentication with FedAuth cookie.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="icon">Optional icon to use for the popup form</param>
        /// <returns>ClientContext to be used by CSOM code</returns>
        public ClientContext GetWebLoginClientContext(string siteUrl, System.Drawing.Icon icon = null)
        {
            var cookies = new CookieContainer();
            var siteUri = new Uri(siteUrl);

            var thread = new Thread(() =>
            {
                var form = new System.Windows.Forms.Form();
                if (icon != null)
                {
                    form.Icon = icon;
                }
                var browser = new System.Windows.Forms.WebBrowser
                {
                    ScriptErrorsSuppressed = true,
                    Dock = DockStyle.Fill
                };


                form.SuspendLayout();
                form.Width  = 900;
                form.Height = 500;
                form.Text   = string.Format("Log in to {0}", siteUrl);
                form.Controls.Add(browser);
                form.ResumeLayout(false);

                browser.Navigate(siteUri);

                browser.Navigated += (sender, args) =>
                {
                    if (siteUri.Host.Equals(args.Url.Host))
                    {
                        var cookieString = CookieReader.GetCookie(siteUrl).Replace("; ", ",").Replace(";", ",");
                        if (Regex.IsMatch(cookieString, "FedAuth", RegexOptions.IgnoreCase))
                        {
                            var _cookies = cookieString.Split(',').Where(c => c.StartsWith("FedAuth", StringComparison.InvariantCultureIgnoreCase) || c.StartsWith("rtFa", StringComparison.InvariantCultureIgnoreCase));
                            cookies.SetCookies(siteUri, string.Join(",", _cookies));
                            form.Close();
                        }
                    }
                };

                form.Focus();
                form.ShowDialog();
                browser.Dispose();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            if (cookies.Count > 0)
            {
                var ctx = new ClientContext(siteUrl);
                ctx.ExecutingWebRequest += (sender, e) => e.WebRequestExecutor.WebRequest.CookieContainer = cookies;
                return(ctx);
            }

            return(null);
        }
Exemple #5
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Create your own web history images.");
            System.Console.WriteLine("Type the URL (with http://...");
            string url = System.Console.ReadLine();
            System.Console.WriteLine(@"Save to location (e.g. C:\Images\)");
            string path = System.Console.ReadLine();
            IArchiveService service = new WebArchiveService();
            Website result = service.Load(url);
            System.Console.WriteLine("WebArchive Sites found: " + result.ArchiveWebsites.Count);
            WebBrowser wb = new WebBrowser();  
            int i = 0;
            foreach (ArchiveWebsite site in result.ArchiveWebsites)
            {
             i++;
             System.Console.WriteLine("Save image (Date " + site.Date.ToShortDateString() + ") number: " + i.ToString());
             wb.ScrollBarsEnabled = false;  
             wb.ScriptErrorsSuppressed = true;
             wb.Navigate(site.ArchiveUrl);  
             while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }     
             wb.Width = wb.Document.Body.ScrollRectangle.Width;  
             wb.Height = wb.Document.Body.ScrollRectangle.Height;  
  
             Bitmap bitmap = new Bitmap(wb.Width, wb.Height);  
             wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));  
             bitmap.Save(path + site.Date.Year.ToString() + "_" + site.Date.Month.ToString() + "_" + site.Date.Day.ToString() + ".bmp");  
            }
            wb.Dispose();

            System.Console.WriteLine(result.Url);
        }
Exemple #6
0
        //////////////////////////////////////////////////////////////////////////
        // Web Document 操作 処理関数
        /// <summary>
        /// id = fileurl の filePathを取得する
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static String GetPathByID(String url)
        {
            // create a hidden web browser, which will navigate to the page
            System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
            web.ScrollBarsEnabled      = false; // we don't want scrollbars on our image
            web.ScriptErrorsSuppressed = true;  // don't let any errors shine through
            web.Navigate(url);                  // let's load up that page!

            // wait until the page is fully loaded
            while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
            {
                System.Windows.Forms.Application.DoEvents();
            }
            //System.Threading.Thread.Sleep(1500); // allow time for page scripts to update
            // the appearance of the page

            HtmlWindow currentWindow = web.Document.Window;
            String     fileurl       = "";

            if (web.Document.GetElementById("fileurl") != null)
            {
                fileurl = web.Document.GetElementById("fileurl").InnerText;
                fileurl = Url2Path(fileurl);
            }
            web.Dispose();
            return(fileurl);
        }
Exemple #7
0
        public void BitmapThreadWorker(object url)
        {
            try
            {
                DateTime started = DateTime.Now;
                WebBrowser browser = new WebBrowser();
                browser.ScrollBarsEnabled = false;
                browser.ClientSize = new Size(800, 600);
                browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
                browser.Navigate((string)url);

                while (bmp == null)
                {
                    Thread.Sleep(1000);
                    Application.DoEvents();
                    TimeSpan elapsed = DateTime.Now.Subtract(started);
                    if (elapsed.TotalMilliseconds > s_RequestTimeout / 2)
                    {
                        browser.Dispose();
                        mre.Set();
                        break;
                    }
                }
            }
            catch
            {
                mre.Set();
            }
        }
Exemple #8
0
 public void Dispose()
 {
     if (!web.IsDisposed)
     {
         web.Dispose();
     }
 }
Exemple #9
0
        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            m_IsMonTime = false;

            m_CloseForm = true;

            btnCancel.IsEnabled = btnGoBack.IsEnabled = btnIndex.IsEnabled = false;
            web.Dispose();
        }
Exemple #10
0
 private void DisposeWebBrowser()
 {
     if (_webBrowser != null)
     {
         ((Session)HostNode.Session).UnregisterControlHelp(_webBrowser);
         _webBrowser.Dispose();
         _webBrowser = null;
     }
 }
 private void GenerateWebSiteImageInternal()
 {
     WebBrowser WebBrowser = new WebBrowser();
     WebBrowser.ScrollBarsEnabled = false;
     WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
     WebBrowser.Navigate(Url);
     while (WebBrowser.ReadyState != WebBrowserReadyState.Complete)
         Application.DoEvents();
     WebBrowser.Dispose();
 }
 private void _GenerateWebSiteThumbnailImage()
 {
     WebBrowser m_WebBrowser = new WebBrowser();
     m_WebBrowser.ScrollBarsEnabled = false;
     m_WebBrowser.Navigate(m_Url);
     m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
     while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
         Application.DoEvents();
     m_WebBrowser.Dispose();
 }
        private void _Generate()
        {
            var browser = new WebBrowser { ScrollBarsEnabled = false };
            browser.Navigate(m_Url);
            browser.DocumentCompleted += WebBrowser_DocumentCompleted;

            while (browser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }

            browser.Dispose();
        }
        public void CaptureWebPage()
        {
            // create a hidden web browser, which will navigate to the page
            System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
            web.Width  = 1089;
            web.Height = 10;
            // we don't want scrollbars on our image
            web.ScrollBarsEnabled = false;
            // don't let any errors shine through
            web.ScriptErrorsSuppressed = true;
            // let's load up that page!
            if (this.Method == ThumbnailMethod.Url)
            {
                web.Navigate(this.Url);
                // web.Show();
            }
            else
            {
                web.DocumentText = this.Html;
            }
            web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (web.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            // web.Dispose();

            // wait until the page is fully loaded
            //     while (web.ReadyState != WebBrowserReadyState.Complete)
            //       System.Windows.Forms.Application.DoEvents();
            //  System.Threading.Thread.Sleep(1500); // allow time for page scripts to update
            // the appearance of the page

            // set the size of our web browser to be the same size as the page
            //int width = web.Document.Body.ScrollRectangle.Width;
            //int height = web.Document.Body.ScrollRectangle.Height;
            //web.Width = width;
            //web.Height = height;
            // a bitmap that we will draw to
            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height);
            // draw the web browser to the bitmap
            //web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, width, height));
            //Bitmap bitmap = new Bitmap(CaptureWebPage("http://46.183.10.241/Quotewerks/demo-certificate1.html"));
            //Response.ContentType = "image/jpeg";
            ///bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
            //bitmap.Dispose();
            //bitmap.Dispose();
            //Response.End();
            //return bmp; // return the bitmap for processing
            web.Dispose();
        }
        internal static void OpenConsentFlow(string url, Action <string> messageAction)
        {
            var thread = new Thread(() =>
            {
                var maxRetry   = 5;
                var retryCount = 0;
                var form       = new System.Windows.Forms.Form();
                var browser    = new System.Windows.Forms.WebBrowser
                {
                    ScriptErrorsSuppressed = true,
                    Dock = DockStyle.Fill
                };

                form.SuspendLayout();
                form.Width  = 1024;
                form.Height = 800;
                form.Text   = $"Consent";
                form.Controls.Add(browser);
                form.ResumeLayout(false);

                browser.Navigate(url);

                browser.Navigated += (sender, args) =>
                {
                    if (args.Url.Query.Contains("admin_consent=True"))
                    {
                        form.Close();
                    }
                    if (args.Url.Query.Contains("error="))
                    {
                        var query = HttpUtility.ParseQueryString(args.Url.Query);
                        messageAction?.Invoke(query.Get("error"));
                        retryCount++;

                        if (retryCount < maxRetry)
                        {
                            browser.Navigate(url);
                        }
                    }
                };

                form.Focus();
                form.ShowDialog();
                browser.Dispose();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
        }
Exemple #16
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (webBrowser != null)
            {
                webBrowser.Dispose();
            }
            if (kitBrowser != null)
            {
                kitBrowser.Dispose();
            }

            GC.Collect();
            this.Close();
        }
Exemple #17
0
 static void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
 {
     try
     {
         System.Threading.Thread.Sleep(500);
         if (_browserControl != null)
         {
             _browserControl.Stop();
             _browserControl.Dispose();
         }
     }
     catch (Exception ex)
     {
         MuteFm.SmartVolManagerPackage.SoundEventLogger.LogException(ex);
     }
 }
        private void _Generate()
        {
            _browser = new WebBrowser
                       {
                           ScrollBarsEnabled = false
                       };

            _browser.Navigate(_mUrl);

            _browser.DocumentCompleted += WebBrowser_DocumentCompleted;

            while (_browser.ReadyState != WebBrowserReadyState.Complete)
            {
            }

            _browser.Dispose();
        }
        public AddForm()
        {
            InitializeComponent();

            button_save.Enabled = false;
            if (!string.IsNullOrEmpty(config.TfsDefaultProject))
            {
                textbox_tfsUrl.Text = config.TfsServerUrl;
                textbox_defaultProject.Text = config.TfsDefaultProject;
                button_save.Enabled = true;
            }

            this.BindScreen();

            // genereate system info
            StringBuilder systemInfo = new StringBuilder();

            OperatingSystem os = Environment.OSVersion;
            systemInfo.AppendFormat("OS Version : {0}{1}", os.VersionString.ToString(), Environment.NewLine);
            systemInfo.AppendFormat("Computer name : {0}{1}", SystemInformation.ComputerName, Environment.NewLine);
            systemInfo.AppendFormat("Monitor count : {0}{1}", SystemInformation.MonitorCount, Environment.NewLine);
            systemInfo.AppendFormat("Monitors same display format : {0}{1}", SystemInformation.MonitorsSameDisplayFormat, Environment.NewLine);
            systemInfo.AppendFormat("Primary monitor size : {0} x {1} {2}", SystemInformation.PrimaryMonitorSize.Height.ToString(), SystemInformation.PrimaryMonitorSize.Width.ToString(), Environment.NewLine);
            systemInfo.AppendFormat("Terminal server session : {0}{1}", SystemInformation.TerminalServerSession, Environment.NewLine);
            systemInfo.AppendFormat("Working Area : {0} X {1} {2}", SystemInformation.WorkingArea.Height.ToString(), SystemInformation.WorkingArea.Width.ToString(), Environment.NewLine);

            WebBrowser browser = new WebBrowser();
            systemInfo.AppendFormat("Internet explorer version : {0}{1}", browser.Version, SystemInformation.WorkingArea.Width.ToString(), Environment.NewLine);
            browser.Dispose();

            //version firefox
            var regKeyFirefox = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Mozilla\Mozilla Firefox", false);
            if (regKeyFirefox != null)
            {
                systemInfo.AppendFormat("{0}Firefox version :{1}",Environment.NewLine, regKeyFirefox.GetValue("CurrentVersion"));
            }

            //version chrome
            var regKeyChrome = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome", false);
            if (regKeyChrome != null)
            {
                systemInfo.AppendFormat("{0}Chrome version : {1}",Environment.NewLine, regKeyChrome.GetValue("Version"));
            }

            textbox_SystemInfo.Text = systemInfo.ToString();
        }
Exemple #20
0
        static void Main(string[] args)
        {
            WebBrowser wb = new WebBrowser();
            wb.ScrollBarsEnabled = false;
            wb.ScriptErrorsSuppressed = true;
            wb.Navigate("http://code-inside.de");
            while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }

            wb.Width = wb.Document.Body.ScrollRectangle.Width;
            wb.Height = wb.Document.Body.ScrollRectangle.Height;

            Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
            wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
            wb.Dispose();

            bitmap.Save("C://screenshot.bmp");

        }
Exemple #21
0
        public static void OpenBrowser(string url, Action <bool> success, System.Drawing.Icon icon = null)
        {
            var thread = new Thread(() =>
            {
                var form = new System.Windows.Forms.Form();
                if (icon != null)
                {
                    form.Icon = icon;
                }
                var browser = new System.Windows.Forms.WebBrowser
                {
                    ScriptErrorsSuppressed = true,
                    Dock = DockStyle.Fill
                };

                form.SuspendLayout();
                form.Width  = 568;
                form.Height = 1012;
                form.Text   = $"Authenticate";
                form.Controls.Add(browser);
                form.ResumeLayout(false);
                form.FormClosed += (sender, args) =>
                {
                    success(false);
                };
                browser.Navigated += (sender, args) =>
                {
                    if (browser.DocumentText.Contains("You have signed in to the PnP Office 365 Management Shell application on your device. You may now close this window."))
                    {
                        form.Close();
                        success(true);
                    }
                };
                browser.Navigate(url);

                form.Focus();
                form.ShowDialog();
                browser.Dispose();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
        }
        public static void LaunchBrowser(string url, Action <bool> success, System.Drawing.Icon icon = null)
        {
            var thread = new Thread(() =>
            {
                var form = new System.Windows.Forms.Form();
                if (icon != null)
                {
                    form.Icon = icon;
                }
                var browser = new System.Windows.Forms.WebBrowser
                {
                    ScriptErrorsSuppressed = true,
                    Dock = DockStyle.Fill
                };

                form.SuspendLayout();
                form.Width  = 568;
                form.Height = 1012;
                form.Text   = $"Authenticate";
                form.Controls.Add(browser);
                form.ResumeLayout(false);
                form.FormClosed += (sender, args) =>
                {
                    success(false);
                };
                browser.Navigated += (sender, args) =>
                {
                    if (browser.Url.AbsoluteUri.Equals("https://login.microsoftonline.com/common/login", StringComparison.InvariantCultureIgnoreCase) || browser.Url.AbsoluteUri.StartsWith("https://login.microsoftonline.com/common/reprocess", StringComparison.InvariantCultureIgnoreCase))
                    {
                        form.Close();
                        success(true);
                    }
                };
                browser.Navigate(url);

                form.Focus();
                form.ShowDialog();
                browser.Dispose();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
        }
        protected void GetWebPageWorker()
        {
            using (var browser = new WebBrowser())
            {
                browser.ScrollBarsEnabled = false;
                browser.ScriptErrorsSuppressed = true;
                browser.Navigate(_url);

                // Wait for control to load page
                while (browser.ReadyState != WebBrowserReadyState.Complete)
                    Application.DoEvents();
                browser.ClientSize = new Size(1280, 1024);
                Thread.Sleep(1000);

                bitmap = new Bitmap(1280, 1024);
                browser.DrawToBitmap(bitmap, new Rectangle(0, 0, browser.Width, browser.Height));
                browser.Dispose();
            }
        }
Exemple #24
0
        // Protected implementation of Dispose pattern.
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                wb.Dispose();
                wb = null;
                socket.Dispose();
                socket = null;
            }

            // Free any unmanaged objects here.
            //
            disposed = true;
        }
        /// <summary>
        /// Convert url to bitmap byte array
        /// </summary>
        /// <param name="url">Url to browse</param>
        /// <param name="width">width of page (if page contains frame, you need to pass this params)</param>
        /// <param name="height">heigth of page (if page contains frame, you need to pass this params)</param>
        /// <param name="htmlToManipulate">function to manipulate dom</param>
        /// <param name="timeout">in milliseconds, how long can you wait for page response?</param>
        /// <returns>bitmap byte[]</returns>
        /// <example>
        /// byte[] img = new Uri("http://www.uol.com.br").ToImage();
        /// </example>
        public static byte[] ToImage(this Uri url, int? width = null, int? height = null, Action<HtmlDocument> htmlToManipulate = null, int timeout = -1)
        {
            byte[] toReturn = null;

            Task tsk = Task.Factory.StartNew(() =>
            {
                WebBrowser browser = new WebBrowser() { ScrollBarsEnabled = false };
                browser.Navigate(url);

                browser.DocumentCompleted += (s, e) =>
                {
                    var browserSender = (WebBrowser)s;

                    if (browserSender.ReadyState == WebBrowserReadyState.Complete)
                    {
                        if (htmlToManipulate != null) htmlToManipulate(browserSender.Document);

                        browserSender.ClientSize = new Size(width ?? browser.Document.Body.ScrollRectangle.Width, height ?? browser.Document.Body.ScrollRectangle.Bottom);
                        browserSender.ScrollBarsEnabled = false;
                        browserSender.BringToFront();

                        using (Bitmap bmp = new Bitmap(browserSender.Document.Body.ScrollRectangle.Width, browserSender.Document.Body.ScrollRectangle.Bottom))
                        {
                            browserSender.DrawToBitmap(bmp, browserSender.Bounds);
                            toReturn = (byte[])new ImageConverter().ConvertTo(bmp, typeof(byte[]));
                        }
                    }

                };

                while (browser.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }

                browser.Dispose();

            }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

            tsk.Wait(timeout);

            return toReturn;
        }
 public static String GetHtmlByWebBrowser(String url, DependencyObject dispatcher)
 {
     ManualResetEvent mre = new ManualResetEvent(false);
     StreamReader stream = null;
     dispatcher.Dispatcher.Invoke(new Action(() =>
     {
         WebBrowser wb = new WebBrowser();
         wb.Navigate(url);
         wb.Navigated +=new WebBrowserNavigatedEventHandler((Object sender,WebBrowserNavigatedEventArgs e)=>
         {
             wb.Stop();
             Encoding encoding = Encoding.GetEncoding(wb.Document.Encoding);
             stream = new StreamReader(wb.DocumentStream, encoding);
             wb.Dispose();
             mre.Set();
         });
     }));
     mre.WaitOne();
     return stream.ReadToEnd();
 }
Exemple #27
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			StreamReader sr = new StreamReader(sInput, Encoding.Unicode, true);
			string strData = sr.ReadToEnd();
			sr.Close();

			strData = strData.Replace(@"<WBR>", string.Empty);
			strData = strData.Replace(@"&shy;", string.Empty);

			WebBrowser wb = new WebBrowser();
			try
			{
				wb.Visible = false;
				wb.ScriptErrorsSuppressed = true;

				UIUtil.SetWebBrowserDocument(wb, strData);
				ImportPriv(pwStorage, wb.Document.Body);
			}
			finally { wb.Dispose(); }
		}
Exemple #28
0
        public void DoCapture(String url, int width = 1024, int height = 768)
        {
            try
            {
               
                WebBrowser browser = new WebBrowser();
                browser.ScrollBarsEnabled = false;
                browser.ScriptErrorsSuppressed = true;
                browser.Navigate(url);
                while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }

                // Set the size of the WebBrowser control
                browser.Width = width;
                browser.Height = height;

                if (width == -1)
                {
                    // get image with full width
                    browser.Width = browser.Document.Body.ScrollRectangle.Width;
                }

                if (height == -1)
                {
                    //get image with full height
                    browser.Height = browser.Document.Body.ScrollRectangle.Height;
                }

               
                Bitmap bitmap = new Bitmap(browser.Width, browser.Height);
                browser.DrawToBitmap(bitmap, new Rectangle(0, 0, browser.Width, browser.Height));
                browser.Dispose();
                result= bitmap;
            }
            catch (Exception ex)
            {
                result= null;

            }
          
        }
        public void GenerateBitmapMobile(string url, string name)
        {
            System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
            wb.ScrollBarsEnabled      = false;
            wb.ScriptErrorsSuppressed = true;
            wb.Width  = wb.Document.Body.ScrollRectangle.Width;
            wb.Height = wb.Document.Body.ScrollRectangle.Height;

            wb.Navigate(url);
            while (wb.ReadyState != WebBrowserReadyState.Complete)
            {
                System.Windows.Forms.Application.DoEvents();
            }

            Bitmap bitmap = new Bitmap(wb.Width, wb.Height);

            wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
            wb.Dispose();
            var savePath = screenshotFolder + @"\" + name + "-mobile.jpg";

            bitmap.Save(savePath, ImageFormat.Jpeg);
        }
        void webBrowser1_Navigating(object sender, System.Windows.Forms.WebBrowserNavigatingEventArgs e)
        {
            if (e.Url.PathAndQuery.ToLower().Contains("/citrix/metaframe/site/launcher.aspx?"))
            {
                e.Cancel = true;
                string icaFileName = e.Url.AbsoluteUri.Replace("launcher.aspx?", "launch.ica?");
                webBrowser1.Visible = false;

                ICAClient.Visible = true;
                ICAClient.Width   = base.Width;
                ICAClient.Height  = base.Height;
                ICAClient.LoadIcaFile(icaFileName);
                VCClientComm.Start();
                // AutoAppResize makes the app full screen even though
                // the control is smaller.  It also removes the scrollbars
                // and clips the display.  Citrix is was working on a fix a while back (case #60065812)
                ICAClient.AutoAppResize = false;
                ICAClient.Connect();

                webBrowser1.Dispose();
                webBrowser1 = null;
            }
        }
Exemple #31
0
 public Bitmap GenerateScreenshot(string url, int width, int height) { 
     // Load the webpage into a WebBrowser control 
     WebBrowser wb = new WebBrowser(); 
     wb.ScrollBarsEnabled = false; 
     wb.ScriptErrorsSuppressed = true; wb.Navigate(url);  
     while (wb.ReadyState != WebBrowserReadyState.Complete) 
     { 
         System.Windows.Forms.Application.DoEvents();                
     }
     // Set the size of the 
     wb.Width = width; wb.Height = height;   
     if (width == -1) { 
         // Take Screenshot of the web pages full width 
         wb.Width = wb.Document.Body.ScrollRectangle.Width; 
     }   
     if (height == -1) 
     { 
             // Take Screenshot of the web pages full height 
             wb.Height = wb.Document.Body.ScrollRectangle.Height; 
     }   
     // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control 
     Bitmap bitmap = new Bitmap(wb.Width, wb.Height); wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height)); wb.Dispose();  
     return bitmap; 
 }
        private void repIn_Click(object sender, EventArgs e)
        {
            DataRow row = layoutView1.GetDataRow(layoutView1.FocusedRowHandle);
            PrintDocument thePrint = new PrintDocument();
            PrintDialog print = new PrintDialog();
            print.Document = thePrint;
            thePrint.PrintPage += new PrintPageEventHandler(thePrint_PrintPage);
            Path_new = FrameworkParams.TEMP_FOLDER + @"\" + row["TEN_FILE"].ToString();

            byte[] a = row["NOI_DUNG"] as byte[];
            if (a == null || a.Length == 0) return;
            HelpByte.BytesToFile(a, Path_new);
            try
            {
                pic = Image.FromFile(Path_new);
            }
            catch
            { pic = null; }
            read = new System.IO.StreamReader(Path_new, System.Text.Encoding.Default, true);
            #region print word file
            if (Path.GetExtension(Path_new).ToLower().Equals(".doc")
                || Path.GetExtension(Path_new).ToLower().Equals(".docx"))
            {
                Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                object fileName = Path_new;
                object nullobj = Missing.Value;
                wordApp.Visible = true;
                Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(
                    ref fileName, ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj);

                doc.PrintPreview();
            }
            #endregion

            #region print excel file
            else if (Path.GetExtension(Path_new).ToLower().Equals(".xls")
                || Path.GetExtension(Path_new).ToLower().Equals(".xlsx"))
            {
                Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
                ExcelApp.Visible = true;
                ExcelApp.DisplayAlerts = false;
                Microsoft.Office.Interop.Excel.Workbook WBook = ExcelApp.Workbooks.Open(Path_new, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                object obj = true;
                WBook.PrintPreview(obj);
                WBook.Close(false, Missing.Value, Missing.Value);
                ExcelApp.Quit();
            }
            #endregion

            #region print .pdf file
            else if (Path.GetExtension(Path_new).ToLower().Equals(".pdf"))
            {
                System.Diagnostics.Process objProcess = new System.Diagnostics.Process();
                objProcess.StartInfo.FileName = Path_new; //file to print
                objProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                objProcess.StartInfo.UseShellExecute = true;
                objProcess.StartInfo.CreateNoWindow = false;
                objProcess.StartInfo.ErrorDialog = false;
                objProcess.StartInfo.Verb = "print";
                objProcess.Start();
            }
            #endregion

            #region print html file
            else if (Path.GetExtension(Path_new).ToLower().Equals(".htm")
                || Path.GetExtension(Path_new).ToLower().Equals(".html"))
            {
                WebBrowser browser = new WebBrowser();
                browser.DocumentText = read.ReadToEnd();
                while (browser.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }
                browser.Parent = this;
                browser.ShowPrintPreviewDialog();
                browser.Dispose();
            }
            #endregion

            else if (print.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppd = new PrintPreviewDialog();
                ppd.Document = thePrint;
                ((Form)ppd).WindowState = FormWindowState.Maximized;
                ppd.ShowDialog();
                //thePrint.Print();
            }
        }
Exemple #33
0
        void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                App.Status.IsError = false;
                switch (step)
                {
                case "step1":
                    HtmlElement  elem;
                    HtmlDocument doc = webBrowser.Document;
                    if (doc.Body.InnerText.Contains("Logout"))
                    {
                        App.Status.Status = "Already Logged in";
                        step = "step2";
                        return;
                    }
                    App.Status.Status = "Logging...";
                    HtmlElement loginForm = doc.Forms[1];
                    elem = loginForm.GetElementsByTagName("INPUT")[0];
                    elem.SetAttribute("value", Username);
                    elem = loginForm.GetElementsByTagName("INPUT")[1];
                    elem.SetAttribute("value", Password);
                    loginForm.InvokeMember("submit");
                    step = "step2";
                    break;

                case "step2":
                    if (webBrowser.Document.Url.AbsolutePath.Contains("buy_credit"))
                    {
                        App.Status.Status = "Logged on.";
                        webBrowser.Navigate("https://www.rynga.com/reseller_options/generate_vouchers");
                        step = "step3";
                    }
                    else
                    {
                        step = "step1";
                    }
                    break;

                case "step3":
                    if (webBrowser.Document.Url.AbsolutePath.Contains("generate_vouchers"))
                    {
                        step = "step4";
                        goto step4;
                    }
                    else if (webBrowser.Document.Url.AbsolutePath.Contains("validate"))
                    {
                        App.Status.Status = "Generating Vouchers...";
                        HtmlElement pincodeElem;
                        pincodeElem = webBrowser.Document.GetElementById("pincode");
                        pincodeElem.SetAttribute("value", Pincode);
                        webBrowser.Document.Forms[0].InvokeMember("submit");
                        step = "step4";
                    }
                    break;

                case "step4":
step4:
                    if (webBrowser.Document.Url.AbsolutePath.Contains("generate_vouchers"))
                    {
                        HtmlElement formVoucher = webBrowser.Document.Forms[voucherCredit];
                        HtmlElement elemVoucher = formVoucher.GetElementsByTagName("INPUT")[0];
                        elemVoucher.SetAttribute("value", vouchersQuantity.ToString());
                        step = "step5";
                        formVoucher.InvokeMember("submit");
                    }
                    break;

                case "step5":
                    if (webBrowser.Document.Url.AbsolutePath.Contains("voucher_details"))
                    {
                        HtmlElement           divVouchers     = webBrowser.Document.GetElementById("page-local-agents-agent-details");
                        HtmlElementCollection voucherElements = divVouchers.GetElementsByTagName("DIV")[1].GetElementsByTagName("H3");
                        for (int i = 0; i < vouchersQuantity; i++)
                        {
                            VoucherRecord vouch = new VoucherRecord(DateTime.Now, voucherElements[i].InnerText, "", "Not Sent");
                            App.VoucherRecords.Insert(0, vouch);
                            VoucherRecord.SaveToXml(vouch);
                        }
                        App.Status.Status = "Vouchers Generated";
                        webBrowser.Dispose();
                        EventWaitHandle.OpenExisting("vouchersResetEvent").Set();
                    }
                    break;

                default:
                    break;
                }
            }
            catch
            {
                App.Status.RiseError("Error generating vouchers!");
                webBrowser.Dispose();
                EventWaitHandle.OpenExisting("vouchersResetEvent").Set();
            }
        }
 /// <summary>
 /// Creates the browser
 /// </summary>
 private void CreateBrowser()
 {
     WebBrowser Browser = new WebBrowser();
     try
     {
         Browser.ScrollBarsEnabled = false;
         DateTime TimeoutStart = DateTime.Now;
         TimeSpan Timeout = new TimeSpan(0, 0, 10);
         Browser.Navigate(Url);
         Browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Browser_DocumentCompleted);
         while (Browser.ReadyState != WebBrowserReadyState.Complete)
         {
             if (DateTime.Now - TimeoutStart > Timeout)
                 break;
             Application.DoEvents();
         }
     }
     catch { }
     finally
     {
         Browser.Dispose();
     }
 }
Exemple #35
0
        /// <summary>
        /// Returns a SharePoint on-premises / SharePoint Online ClientContext object. Requires claims based authentication with FedAuth cookie.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="icon">Optional icon to use for the popup form</param>
        /// <returns>ClientContext to be used by CSOM code</returns>
        public ClientContext GetWebLoginClientContext(string siteUrl, System.Drawing.Icon icon = null)
        {
            var authCookiesContainer = new CookieContainer();
            var siteUri = new Uri(siteUrl);

            var thread = new Thread(() =>
            {
                var form = new System.Windows.Forms.Form();
                if (icon != null)
                {
                    form.Icon = icon;
                }
                var browser = new System.Windows.Forms.WebBrowser
                {
                    ScriptErrorsSuppressed = true,
                    Dock = DockStyle.Fill
                };

                form.SuspendLayout();
                form.Width  = 900;
                form.Height = 500;
                form.Text   = $"Log in to {siteUrl}";
                form.Controls.Add(browser);
                form.ResumeLayout(false);

                browser.Navigate(siteUri);

                browser.Navigated += (sender, args) =>
                {
                    if (siteUri.Host.Equals(args.Url.Host))
                    {
                        var cookieString = CookieReader.GetCookie(siteUrl).Replace("; ", ",").Replace(";", ",");

                        // Get FedAuth and rtFa cookies issued by ADFS when accessing claims aware applications.
                        // - or get the EdgeAccessCookie issued by the Web Application Proxy (WAP) when accessing non-claims aware applications (Kerberos).
                        IEnumerable <string> authCookies = null;
                        if (Regex.IsMatch(cookieString, "FedAuth", RegexOptions.IgnoreCase))
                        {
                            authCookies = cookieString.Split(',').Where(c => c.StartsWith("FedAuth", StringComparison.InvariantCultureIgnoreCase) || c.StartsWith("rtFa", StringComparison.InvariantCultureIgnoreCase));
                        }
                        else if (Regex.IsMatch(cookieString, "EdgeAccessCookie", RegexOptions.IgnoreCase))
                        {
                            authCookies = cookieString.Split(',').Where(c => c.StartsWith("EdgeAccessCookie", StringComparison.InvariantCultureIgnoreCase));
                        }
                        if (authCookies != null)
                        {
                            authCookiesContainer.SetCookies(siteUri, string.Join(",", authCookies));
                            form.Close();
                        }
                    }
                };

                form.Focus();
                form.ShowDialog();
                browser.Dispose();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            if (authCookiesContainer.Count > 0)
            {
                var ctx = new ClientContext(siteUrl);
                ctx.ExecutingWebRequest += (sender, e) => e.WebRequestExecutor.WebRequest.CookieContainer = authCookiesContainer;
                return(ctx);
            }

            return(null);
        }
Exemple #36
0
        public static string TransformUsingJS(string inputText, bool SafeMode, bool ExtraMode, bool MarkdownInHtml, bool AutoHeadingIDs)
        {
            // Find test page
            var url = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
            url = System.IO.Path.GetDirectoryName(url);
            url = url.Replace("file:\\", "file:\\\\");
            url = url.Replace("\\", "/");
            url = url + "/JSTestResources/JSHost.html";

            // Create browser, navigate and wait
            WebBrowser b = new WebBrowser();
            b.Navigate(url);
            b.ScriptErrorsSuppressed = true;

            while (b.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }

            var o = b.Document.InvokeScript("transform", new object[] { inputText, SafeMode, ExtraMode, MarkdownInHtml, AutoHeadingIDs} );

            string result = o as string;

            // Clean up
            b.Dispose();

            return result;
        }
Exemple #37
0
        public Route Load(PointD[] RoutePoints)
        {
            using (WebBrowser webBrowser = new WebBrowser())
            {
                ScriptManager scriptManager = new ScriptManager();

                webBrowser.ScriptErrorsSuppressed = true;
                webBrowser.ObjectForScripting = scriptManager;
                webBrowser.WebBrowserShortcutsEnabled = false;

                scriptManager.GetState = ScriptManager.State.Running;

                string jsCode = GetJSCode(RoutePoints);
                webBrowser.DocumentText = String.Format(htmlTemplate, jsCode);

                bool IsCheck = true;
                DateTime starTime = DateTime.Now;

                while (IsCheck)
                {
                    switch (scriptManager.GetState)
                    {
                        case ScriptManager.State.Ok:
                            Route route = new Route();
                            route.RouteId = Guid.NewGuid().ToString();
                            route.RouteLength = scriptManager.routeLength;
                            route.RouteJamsTime = scriptManager.routeJamsTime;
                            route.RouteTime = scriptManager.routeTime;
                            route.RouteHumanLength = scriptManager.routeHumanLength;
                            route.RouteHumanJamsTime = scriptManager.routeHumanJamsTime;
                            route.RouteHumanTime = scriptManager.routeHumanTime;
                            IsCheck = false;
                            return route;

                        case ScriptManager.State.Error:
                            IsCheck = false;
                            break;
                    }

                    // Выходим по TimeOut
                    TimeSpan ts = DateTime.Now - starTime;
                    if (ts.Seconds > requestTimeout)
                    {
                        IsCheck = false;
                    }
                    Thread.Sleep(100);
                    Application.DoEvents();
                }

                webBrowser.Dispose();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }

            return null;
        }
Exemple #38
0
 private static void browser_PrintTemplateTeardown(object pDisp)
 {
     browser.Dispose();
     Application.Exit();
 }
        private static void Main()
        {
            int width = -1;
            int height = -1;

            var wb = new WebBrowser { AllowNavigation = true, ScrollBarsEnabled = false, ScriptErrorsSuppressed = true };
            wb.Navigate("http://tillidsoft.com");
            while (wb.ReadyState != WebBrowserReadyState.Complete)
            { }
            // Set the size of the WebBrowser control
            wb.Width = width;
            wb.Height = height;
            if (wb.Document != null && wb.Document.Body != null)
            {
                if (width == -1)
                {
                    // Take Screenshot of the web pages full width
                    wb.Width = wb.Document.Body.ScrollRectangle.Width;
                }
                if (height == -1)
                {
                    // Take Screenshot of the web pages full height
                    wb.Height = wb.Document.Body.ScrollRectangle.Height;
                }

                // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
                var bitmap = new Bitmap(wb.Width, wb.Height);
                wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
                wb.Dispose();

                bitmap.Save(@"C:\Users\santhosh\Desktop\TaskScheduler\1.png", System.Drawing.Imaging.ImageFormat.Png);
            }
            return;

            //// Get the service on the local machine
            //using (var ts = new TaskService())
            //{
            //    if (ts.RootFolder.GetTasks().Any(task => task.Name == "BethedaContentSync"))
            //    {
            //        ts.RootFolder.DeleteTask("BethedaContentSync");
            //    }

            //    // Create a new task definition and assign properties
            //    TaskDefinition td = ts.NewTask();
            //    td.RegistrationInfo.Description = "Bethesda Employee, Patient and Physician import task.";

            //    // Create a trigger that will fire the task at this time every day
            //    //td.Triggers.Add(new DailyTrigger { StartBoundary = DateTime.Now.AddHours(-DateTime.Now.Hour), DaysInterval = 1, Enabled = true });
            //    td.Triggers.Add(new DailyTrigger { StartBoundary = DateTime.Now.AddSeconds(5), DaysInterval = 1, Enabled = true });

            //    string path = @"C:\Program Files\Internet Explorer\iexplore.exe";

            //    // Create an action that will launch Notepad whenever the trigger fires
            //    td.Actions.Add(new ExecAction(path, "", null));

            //    // Register the task in the root folder
            //    ts.RootFolder.RegisterTaskDefinition(@"BethedaContentSync", td);
            //}

            return;
            var consentFormSvcClient = new ConsentFormSvcClient();
            consentFormSvcClient.CreateLog("Sanhtosh", LogType.E, "Test", "Some desc");

            return;
            const string localConStr = "server=192.168.1.158;database=bethesdaCollege;uid=sa;pwd=sa@123";
            const string bethesdaConStr = "server=192.168.1.93;database=Soarian_Clin_Tst_1;uid=sa;pwd=sa@123";

            using (var sqlConnectionLocal = new SqlConnection(localConStr))
            {
                sqlConnectionLocal.Open();

                using (var sqlConnectionBethesda = new SqlConnection(bethesdaConStr))
                {
                    sqlConnectionBethesda.Open();

                    # region Import Physician

                    // ---------------starts physician import process------------------

                    //                    // starts synchronizing
                    //                    var command = new SqlCommand(string.Empty, sqlConnectionBethesda)
                    //                    {
                    //                        //CommandText = "select user_oid,GroupName,UserDescription from [soariandbtest].[dbo].[Physician]"
                    //                        CommandText = "BMH_Consent_GetPhysicianList",
                    //                        CommandType = CommandType.StoredProcedure
                    //                    };

                    //                    var daPhysician = new SqlDataAdapter(command);

                    //                    var physiciansDs = new DataSet();
                    //                    daPhysician.Fill(physiciansDs);

                    //                    int syncId = Convert.ToInt32(DateTime.Now.Ticks % 65323);

                    //                    foreach (DataTable dataTable in physiciansDs.Tables)
                    //                    {
                    //                        foreach (DataRow dataRow in dataTable.Rows)
                    //                        {
                    //                            command = new SqlCommand("select * from Physician where Fname='" + dataRow["UserDescription"] + "'", sqlConnectionLocal);

                    //                            daPhysician = new SqlDataAdapter(command);

                    //                            var physiciansCheck = new DataSet();
                    //                            daPhysician.Fill(physiciansCheck);

                    //                            if (physiciansCheck.Tables.Count == 0 || physiciansCheck.Tables[0].Rows.Count == 0)
                    //                            {
                    //                                string physicianName = dataRow["UserDescription"].ToString();
                    //                                string userId = dataRow["user_oid"].ToString();
                    //                                string groupName = dataRow["GroupName"].ToString();

                    //                                command = new SqlCommand(@"insert into Physician
                    //                                                                                values('False','True',8,'" + physicianName + "','" + userId +
                    //                                                            "',0,'" + groupName + "'," + syncId + ")", sqlConnectionLocal);
                    //                                command.ExecuteNonQuery();
                    //                            }
                    //                        }
                    //                    }

                    //                    // removing un - available physicians
                    //                    command = new SqlCommand("delete from Physician where SyncID !=" + syncId, sqlConnectionLocal);
                    //                    command.ExecuteNonQuery();

                    #endregion

                    #region Import Patients for BHE location

                    //AddPatient(sqlConnectionLocal, sqlConnectionBethesda, "BHE");

                    //AddPatient(sqlConnectionLocal, sqlConnectionBethesda, "BMH");

                    #endregion

                    #region Import Employee

                    // ---------------starts physician import process------------------

                    // starts synchronizing
                    var commandEmployee = new SqlCommand(string.Empty, sqlConnectionBethesda)
                    {
                        //CommandText = "select user_oid,GroupName,UserDescription from [soariandbtest].[dbo].[Physician]"
                        CommandText = "BMH_Consent_User",
                        CommandType = CommandType.StoredProcedure
                    };

                    var daEmployee = new SqlDataAdapter(commandEmployee);

                    var employeeDs = new DataSet();
                    daEmployee.Fill(employeeDs);

                    int syncIdEmployee = Convert.ToInt32(DateTime.Now.Ticks % 65323);

                    foreach (DataTable dataTable in employeeDs.Tables)
                    {
                        foreach (DataRow dataRow in dataTable.Rows)
                        {
                            commandEmployee = new SqlCommand("select * from EmployeeInformation where EmpID='" + dataRow["LoginID"] + "'", sqlConnectionLocal);

                            daEmployee = new SqlDataAdapter(commandEmployee);

                            var physiciansCheck = new DataSet();
                            daEmployee.Fill(physiciansCheck);

                            if (physiciansCheck.Tables.Count == 0 || physiciansCheck.Tables[0].Rows.Count == 0)
                            {
                                string lastName = dataRow["LastName"].ToString();
                                string firstName = dataRow["FirstName"].ToString();
                                string loginID = dataRow["LoginID"].ToString();

                                commandEmployee = new SqlCommand(@"insert into EmployeeInformation
                                           values('" + loginID + "','" + lastName + "','" + firstName + "','" + syncIdEmployee + "')", sqlConnectionLocal);
                                commandEmployee.ExecuteNonQuery();
                            }
                        }
                    }

                    // removing un - available physicians
                    commandEmployee = new SqlCommand("delete from EmployeeInformation where SyncID !=" + syncIdEmployee, sqlConnectionLocal);
                    commandEmployee.ExecuteNonQuery();

                    #endregion
                }
            }
        }
Exemple #40
0
 private void GenerateThumbnailInteral()
 {
     WebBrowser webBrowser = new WebBrowser();
     webBrowser.ScrollBarsEnabled = false;
     webBrowser.Navigate(this.Url);
     webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
     while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
         System.Windows.Forms.Application.DoEvents();
     webBrowser.Dispose();
 }
Exemple #41
0
        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                string urlAdd = "https://api.weibo.com/oauth2/authorize";

                if ((webBrowser.Url != null && webBrowser.Url.ToString().Contains(urlAdd)))
                {
                    //判断是否已加载完网页
                    if (webBrowser.ReadyState == WebBrowserReadyState.Complete)
                    {
                        try
                        {
                            //获取网页文档对象,相当于获取网页的全部源码
                            HtmlDocument htmlDoc = webBrowser.Document;
                            //设置帐号
                            HtmlElement id = htmlDoc.GetElementById("userId");
                            id.SetAttribute("value", passport);
                            //设置密码
                            HtmlElement pwd = htmlDoc.GetElementById("passwd");
                            pwd.SetAttribute("value", password);
                            //登录

                            HtmlDocument          cd  = webBrowser.Document;
                            HtmlElementCollection dhl = cd.GetElementsByTagName("a");

                            foreach (HtmlElement item in dhl)
                            {
                                if (item.GetAttribute("action-type").Equals("submit"))
                                {
                                    item.InvokeMember("click");
                                    break;
                                }
                            }
                            HtmlElement btn = htmlDoc.GetElementById("submit");
                            if (btn != null)
                            {
                                btn.InvokeMember("click");
                            }
                        }
                        catch (Exception ex)
                        {
                            LogUtil.WriteError(ex);
                        }
                    }
                }
                // 根据id找到对应的元素
                string oauth2Url = "https://api.weibo.com/oauth2/default.html?code=";

                if ((webBrowser.Url != null && webBrowser.Url.ToString().Contains(oauth2Url)))
                {
                    //MessageBox.Show(webBrowser.Url.ToString());
                    var      url  = webBrowser.Url.ToString();
                    char[]   cha  = { '=' };
                    string[] strs = url.Split(cha, StringSplitOptions.RemoveEmptyEntries);
                    if (strs.Count() == 2)
                    {
                        Code = strs[1];
                        try
                        {
                            AccessToken accessToken = o.GetAccessTokenByAuthorizationCode(strs[1]); //请注意这里返回的是AccessToken对象,不是string
                            Share.wFiles.WriteString("WCO", "AcessToken", CryptHelper.EncryptString(oauth.AccessToken));
                            if (submitT != null && submitT.IsAlive)
                            {
                                submitT.Abort();
                            }
                            webBrowser.Dispose();
                        }
                        catch (WeiboException ex)
                        {
                            Console.WriteLine(ex.Message);
                            if (submitT != null && submitT.IsAlive)
                            {
                                submitT.Abort();
                            }
                            webBrowser.Dispose();
                        }
                    }
                }
                string authorizeUrl = "https://api.weibo.com/oauth2/authorize";
                submitT = new Thread(() =>
                {
                    Thread.Sleep(1000);
                    bool search = true;
                    while (search)
                    {
                        if (!webBrowser.IsHandleCreated)
                        {
                            return;
                        }
                        webBrowser.Invoke(new Action(() =>
                        {
                            if (webBrowser.Url != null && webBrowser.Url.ToString() == authorizeUrl)
                            {
                                HtmlDocument cd           = webBrowser.Document;
                                HtmlElementCollection dhl = cd.GetElementsByTagName("a");

                                foreach (HtmlElement item in dhl)
                                {
                                    if (item.GetAttribute("action-type").Equals("submit"))
                                    {
                                        item.InvokeMember("click");
                                        search = false;
                                        break;
                                    }
                                }
                            }
                        }));

                        Thread.Sleep(500);
                    }
                });
                submitT.Start();
            }
            catch (Exception ex)
            {
                LogUtil.WriteError(ex);
            }
        }
Exemple #42
0
        private void WebBrowserThread()
        {
            WebBrowser wb = new WebBrowser();
            wb.Navigate(currentURL);

            wb.DocumentCompleted +=
                new WebBrowserDocumentCompletedEventHandler(
                    wb_DocumentCompleted);

            while (wb.ReadyState != WebBrowserReadyState.Complete)
                Application.DoEvents();

            //Added this line, because the final HTML takes a while to show up

            currentPage = wb.Document.Body.InnerHtml;

            wb.Dispose();
        }
 private Bitmap GetPreviewImage()
 {
     WebBrowser wb = new WebBrowser();
     wb.ScrollBarsEnabled = false;
     wb.Size = new Size(Width, Height);
     wb.ScriptErrorsSuppressed = true;
     wb.NewWindow += new System.ComponentModel.CancelEventHandler(wb_NewWindow);
     wb.Navigate(_url);
     // wait for it to load
     while (wb.ReadyState != WebBrowserReadyState.Complete)
     {
         Application.DoEvents();
     }
     Bitmap bitmap = new Bitmap(Width, Height);
     Rectangle rect = new Rectangle(0, 0, Width, Height);
     wb.DrawToBitmap(bitmap, rect);
     wb.Dispose();
     return bitmap;
 }
Exemple #44
0
        private void GenerateThumbnailInteral()
        {
            WebBrowser webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.Navigate(this.Url);
            //try
            //{
            //    webBrowser.Navigate(this.Url);
            //}
            //catch (Exception exception)
            //{
            //    ErrorMessage = exception.Message;
            //    ThumbnailImage = null;
            //    webBrowser.Dispose();
            //    return;
            //}
            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
            System.Windows.Forms.Application.DoEvents();
            //try
            //{
            //    while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
            //        System.Windows.Forms.Application.DoEvents();
            //}
            //catch (Exception exception)
            //{
            //    ErrorMessage = exception.Message;
            //    ThumbnailImage = null;
            //    webBrowser.Dispose();
            //    return;
            //}

            webBrowser.Dispose();
        }
        private void WebBrowserThread()
        {
            try
            {
                WebBrowser wb = new WebBrowser();
                wb.Navigate(URL);

                //wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
                int i = 0;

                Console.WriteLine("While Loop");
                //while (wb.ReadyState != WebBrowserReadyState.Complete && i < 200000)
                while (wb.Document == null || wb.Document.Body == null || wb.Document.Body.InnerHtml == null || !wb.Document.Body.InnerHtml.Contains("Notes:"))
                {
                    Application.DoEvents();
                    //i++;
                }
                Console.WriteLine("Done");
                //Added this line, because the final HTML takes a while to show up
                GeneratedSource = wb.Document.Body.InnerHtml;

                wb.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("WebBrowserThread() Error: " + e.Message);
                mainForm.showResults();
            }
        }
        private void lstVw_DragDrop(object sender, DragEventArgs e)
        {
            if (readOnlyMode) return;

            string s = (string)e.Data.GetData(DataFormats.Html);
            List<string> urls = new List<string>();

            string sourceUrl = GetSourceURL(s);
            if (sourceUrl != null)
            {
                WebBrowser wb = new WebBrowser();
                wb.DocumentText = s;
                do { Application.DoEvents(); } while (wb.ReadyState != WebBrowserReadyState.Complete);
                urls.AddRange(ExtractUrls(wb.Document.Links, "href", sourceUrl));
                urls.AddRange(ExtractUrls(wb.Document.Images, "src", sourceUrl));
                wb.Dispose();
            }

            var items = new List<ListViewItem>();
            items.AddRange(urls.Select(url => CreateNewItem(url)));
            populateItems(items);

            if (urls.Count > 0)
                this.OnAttachedFileDeleted(e);

            updateToolBarButtons();
        }
        /// <summary>
        /// Returns a SharePoint on-premises / SharePoint Online ClientContext object. Requires claims based authentication with FedAuth cookie.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="icon">Optional icon to use for the popup form</param>
        /// <returns>ClientContext to be used by CSOM code</returns>
        public ClientContext GetWebLoginClientContext(string siteUrl, System.Drawing.Icon icon = null)
        {
            var cookies = new CookieContainer();
            var siteUri = new Uri(siteUrl);

            var thread = new Thread(() =>
            {
                var form = new System.Windows.Forms.Form();
                if (icon != null)
                {
                    form.Icon = icon;
                }
                var browser = new System.Windows.Forms.WebBrowser
                {
                    ScriptErrorsSuppressed = true,
                    Dock = DockStyle.Fill
                };


                form.SuspendLayout();
                form.Width = 900;
                form.Height = 500;
                form.Text = string.Format("Log in to {0}", siteUrl);
                form.Controls.Add(browser);
                form.ResumeLayout(false);

                browser.Navigate(siteUri);

                browser.Navigated += (sender, args) =>
                {
                    if (siteUri.Host.Equals(args.Url.Host))
                    {
                        var cookieString = CookieReader.GetCookie(siteUrl).Replace("; ", ",").Replace(";", ",");
                        if (Regex.IsMatch(cookieString, "FedAuth", RegexOptions.IgnoreCase))
                        {
                            var _cookies = cookieString.Split(',').Where(c => c.StartsWith("FedAuth", StringComparison.InvariantCultureIgnoreCase) || c.StartsWith("rtFa", StringComparison.InvariantCultureIgnoreCase));
                            cookies.SetCookies(siteUri, string.Join(",", _cookies));
                            form.Close();
                        }
                    }
                };

                form.Focus();
                form.ShowDialog();
                browser.Dispose();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            if (cookies.Count > 0)
            {
                var ctx = new ClientContext(siteUrl);
                ctx.ExecutingWebRequest += (sender, e) => e.WebRequestExecutor.WebRequest.CookieContainer = cookies;
                return ctx;

            }

            return null;
        }
        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string urlAdd  = "https://rd.tencent.com/top/ptlogin/ptlogins/login?site=";
            string urlAdd2 = "https://tapd.tencent.com/ptlogin/ptlogins/login?";

            if ((webBrowser.Url != null && webBrowser.Url.ToString().Contains(urlAdd)) || (webBrowser.Url != null && webBrowser.Url.ToString().Contains(urlAdd2)))
            {
                //判断是否已加载完网页
                if (webBrowser.ReadyState == WebBrowserReadyState.Complete)
                {
                    //获取网页文档对象,相当于获取网页的全部源码
                    HtmlDocument htmlDoc = this.webBrowser.Document;
                    //设置帐号
                    HtmlElement id = htmlDoc.GetElementById("username");
                    id.SetAttribute("value", FrmSet.UserName);
                    //设置密码
                    HtmlElement pwd = htmlDoc.GetElementById("password_input");
                    pwd.SetAttribute("value", FrmSet.PassWord);
                    //登录
                    HtmlElement btn = htmlDoc.GetElementById("login_button");
                    if (btn != null)
                    {
                        btn.InvokeMember("click");
                    }
                }
            }
            // 根据id找到对应的元素
            HtmlElement htmlEle = webBrowser.Document.GetElementById("checkout_btn");

            if (htmlEle != null)
            {
                // 激活html元素的 click 成员
                if (search)
                {
                    htmlEle.InvokeMember("click");
                }

                System.Threading.Thread submitT = new Thread(() =>
                {
                    Thread.Sleep(1000);

                    try
                    {
                        while (search)
                        {
                            webBrowser.Invoke(new Action(() =>
                            {
                                HtmlDocument cd           = webBrowser.Document;
                                HtmlElementCollection dhl = cd.GetElementsByTagName("BUTTON");

                                foreach (HtmlElement item in dhl)
                                {
                                    if (item.InnerText == "提交" || item.InnerText == "Submit")
                                    {
                                        item.InvokeMember("click");
                                        search = false;
                                        Share.wFiles.WriteString("WCO", "LastCheckOutTime", string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));

                                        showTipsDelegate();

                                        webBrowser.Dispose();
                                    }
                                }
                            }));

                            Thread.Sleep(1000);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtil.WriteError(ex);
                    }
                });
                submitT.Start();
            }
        }
Exemple #49
0
 /// <summary>
 /// 使用WebBrowser生成图片
 /// </summary>
 private void _GenerateImage()
 {
     WebBrowser browser = new WebBrowser();
     browser.ScrollBarsEnabled = false;
     browser.Navigate(_url);
     browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(_DocumentCompleted);
     while (browser.ReadyState != WebBrowserReadyState.Complete)
         Application.DoEvents();
     browser.Dispose();
 }