예제 #1
0
        /// <summary>
        /// Инициализируем Awesomium
        /// </summary>
        private void initAwesomium()
        {
            //Инициализируем параметры запуска ядра авесомиума
            WebCore.Initialize(new WebConfig()
            {
                LogLevel  = LogLevel.None,
                UserAgent = compileUA()
            });

            //Создаём сессию
            ss = WebCore.CreateWebSession(new WebPreferences
            {
                //   ProxyConfig = "https://lv-134-87-2.fri-gate.biz:443",
                WebSecurity               = true,
                LoadImagesAutomatically   = false,
                RemoteFonts               = false,
                JavascriptApplicationInfo = false
            });


            //Инициализируем браузер, для работы с сайтом.
            wv = WebCore.CreateWebView(
                1680,
                1050,
                ss,
                WebViewType.Offscreen);
        }
예제 #2
0
        private Shop MakeClickNCollectOrderAlreadyPaid()
        {
            var webSession = new WebSession();
            var customer   = _webAuthentificationService.ConnectCustomer(
                "*****@*****.**",
                "notfunnypassword"
                );

            webSession.ConnectCustomer(customer);

            var articleBarCode = "0102030405";
            var article        = _articlesService.GetArticles(articleBarCode).First();

            webSession.AddArticle(article);
            var availablesShops = _shopInfosService.GetShops();

            Assert.AreEqual(2, availablesShops.Count());

            var selectedShop = availablesShops.First(
                shop => shop.Address.City == "Toulouse"
                );

            webSession.SetClickNCollectDeliveryMode(selectedShop.Id);

            webSession.PayWtihBC(
                "4545-5555-5555-5555",
                "01/25",
                "111"
                );
            webSession.CompleteTransaction();

            return(webSession.GetSelectedShop());
        }
예제 #3
0
        public static void SessionLogin(string sessionID, string accountID)
        {
            WebSession sessionsBySessionID = SessionService.sessionGateway.GetSessionsBySessionID(sessionID);

            sessionsBySessionID.AccountID = accountID;
            SessionService.sessionGateway.UpdateByPK(sessionsBySessionID);
        }
예제 #4
0
 public AuthController(ISimpleCRUDService crudService, JWTTokenProvider jwtTokenProvider, IPasswordHasher passwordHasher, WebSession webSession)
 {
     _crudService      = crudService;
     _jwtTokenProvider = jwtTokenProvider;
     _passwordHasher   = passwordHasher;
     _webSession       = webSession;
 }
예제 #5
0
        /*----------------------------------------------------*/

        public void Validate_ReturnHome_NavigationItem()
        {
            if (ModuleUser.MasterNavElement != null)
            {
                cNavElement aReturnHomeNavElement = ModuleUser.MasterNavElement.Find_ChildElement("ReturnHome");

                if (aReturnHomeNavElement != null)
                {
                    cModuleState aModuleState = WebSession.ModuleState("Home");
                    if (aModuleState == null && WebSession.HasStaffUser)
                    {
                        aModuleState = WebSession.ModuleState("Staff");
                    }
                    if (aModuleState != null)
                    {
                        //WebSession.Remove_ModuleState("Home");
                        aReturnHomeNavElement.Visible    = true;
                        aReturnHomeNavElement.Enabled    = true;
                        aReturnHomeNavElement.SourceFile = WebAppl.Remove_RootFromURL(aModuleState.LastURL);
                        String aDefaultPageKey = ReturnHomeModuleDefaultPageKey();
                        aReturnHomeNavElement.SourceFile = cWebLib.AddQuerystringParameter(aReturnHomeNavElement.SourceFile, "Page", aDefaultPageKey);
                    }
                    else
                    {
                        aReturnHomeNavElement.Visible = false;
                    }
                }
            }
        }
예제 #6
0
 public OutlookWebAccessApplication(string virtualDirectory, WebSession webSession) : base(virtualDirectory, webSession)
 {
     webSession.SendingRequest += delegate(object sender, HttpWebRequestEventArgs e)
     {
         e.Request.Expect = null;
     };
 }
예제 #7
0
        IWebView IWebViewLifeCycleManager.Create()
        {
            if (_Session == null)
            {
                _Session = (_WebSessionPath != null) ? WebCore.CreateWebSession(_WebSessionPath, new WebPreferences()) :
                           WebCore.CreateWebSession(new WebPreferences());

                WebCore.ShuttingDown += WebCore_ShuttingDown;
            }

            WebControl nw = new WebControl()
            {
                WebSession          = _Session,
                Visibility          = Visibility.Hidden,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment   = VerticalAlignment.Stretch,
                ContextMenu         = new ContextMenu()
                {
                    Visibility = Visibility.Collapsed
                }
            };

            Grid.SetColumnSpan(nw, 2);
            Grid.SetRowSpan(nw, 2);
            Panel.SetZIndex(nw, 0);
            this.MainGrid.Children.Add(nw);
            return(nw);
        }
예제 #8
0
        public MainWindow()
        {
            if (!WebCore.IsInitialized)
            {
                WebCore.Initialize(new WebConfig()
                {
                    HomeURL             = new Uri("http://localhost"),
                    RemoteDebuggingPort = 8001,
                });
            }

            // Create a WebSession.
            WebSession session = WebCore.CreateWebSession(new WebPreferences()
            {
                SmoothScrolling = true
            });

            session.AddDataSource("core", new ResourceDataSource(ResourceType.Embedded, Assembly.GetExecutingAssembly()));

            InitializeComponent();
            webControl.DocumentReady        += onDocumentReady;
            webControl.ConsoleMessage       += onConsoleMessage;
            webControl.LoadingFrameComplete += onLoadingFrameComplete;

            webControl.WebSession = session;
        }
예제 #9
0
            public WebTimeJob()
            {
                var kv = new System.Collections.Specialized.NameValueCollection();

                kv.Add("User-Agent", UserAgent.PC);
                session = new WebSession(customHeader: kv);
            }
예제 #10
0
        public async Task <IActionResult> Index(int page = 1)
        {
            ViewBag.Title = "Activities";
            var dataPage = new WebsessionPage();

            try
            {
                var user = await UserManager.GetUserAsync(HttpContext.User);

                var webSession = new WebSession(Configuration, Context, Logger);

                var dataWeb = webSession.GetWebSessionPage(page, user.Id);

                if (!string.IsNullOrEmpty(CommonHelper.GetCookie(Request, Const.CookieSessionId)))
                {
                    foreach (var web in dataWeb.Results)
                    {
                        if (web.Id.Equals(CommonHelper.GetCookie(Request, Const.CookieSessionId)))
                        {
                            web.Current = true;
                        }
                    }
                }

                dataPage.Pagination = dataWeb;
            }
            catch (Exception e)
            {
                Log.Logger.Error("HttpGet SendSms: " + e.Message);
                ModelState.AddModelError(string.Empty, "Activity");
            }

            return(View(dataPage));
        }
예제 #11
0
        private Page getNextPage(Page current, WebSession session)
        {
            Page next = null;

            if (IsDNQ(session))
            {
                next = new Page {
                    Controller = "Quote", Action = "DNQ"
                };
            }
            else if (IsCustomerService(session))
            {
                next = new Page {
                    Controller = "Quote", Action = "CustomerService"
                };
            }
            while (next == null)
            {
                if (_flow.IndexOf(current) < _flow.Count - 1)
                {
                    current = _flow[_flow.IndexOf(current) + 1];
                }

                if (IsRequired(current, session))
                {
                    next = current;
                }
            }

            return(next);
        }
예제 #12
0
        public string CreateWebSessionFromDiscordId(string discordUserId)
        {
            ReportUser reportUser = _wrapper.ReportUserRepository.GetOne <ReportUser>(f => f.DiscordId == discordUserId);

            if (reportUser != null)
            {
                WebSession webSession = this.CreateWebSession(reportUser.Username);
                return(webSession.SessionCookie);
            }
            else
            {
                if (SystemShouldAutoCreateAccounts())
                {
                    ReportUser newUser = new ReportUser();
                    newUser.PasswordHash        = HashPassword(GenerationHelper.CreateRandomString(true, true, false, 20));
                    newUser.Username            = discordUserId;
                    newUser.IsOrganizationAdmin = false;
                    newUser.OrganizationRoles   = new List <string>();
                    _wrapper.ReportUserRepository.AddOne <ReportUser>(newUser);
                    WebSession webSession = this.CreateWebSession(newUser.Username);
                    return(webSession.SessionCookie);
                }
                else
                {
                    return("");
                }
            }
        }
예제 #13
0
        public XElement LoadCoverages(WebSession session)
        {
            Int32  account = LoadAccount(session.Quote.getCustomer().getMarketKeyCode());
            Int32  form    = 3;
            String units   = "1";

            if (session.Quote.getPolicyInfo().getHoUnitsInBldg() > 0)
            {
                units = session.Quote.getPolicyInfo().getHoUnitsInBldg().ToString();
            }
            DateTime date      = session.Quote.getPolicyInfo().getEffDate();
            String   zip       = session.Quote.getCustomer().getZipCode1().ToString("00000");
            String   key       = "KdQuoteFlow_RenterServices_LoadCoverages_" + account + "_" + form + "_" + date + "_" + zip + "_" + units;
            XElement scenarios = (XElement)CacheManager.GetData(key);

            if (scenarios == null)
            {
                Scenarios ws = new Scenarios {
                    Url = Environmentals.HOWebService + "/DecisionMaker/quotesvc/Scenarios.asmx"
                };
                XElement coverages = XElement.Parse(ws.LookupCoverages(account, form, date, zip));
                scenarios = coverages.Element(coverages.GetDefaultNamespace() + "Scenarios");
                scenarios.Elements().Where(x => x.Attribute("Units").Value != units).Remove();
                CacheManager.Add(key, scenarios, CacheManager.ExpireEveryDayAtSix);
            }

            return(scenarios);
        }
예제 #14
0
        public void REQ_17_FinalizeOnlineBracket_WithDelieveryModeClickNCollect()
        {
            WebSession webSession = MakeWebConnectedSession();

            var availablesShops = _shopsService.GetShops();

            Assert.AreEqual(2, availablesShops.Count());

            var selectedShop = availablesShops.First(
                shop => shop.Address.City == "Balma"
                );

            webSession.SetClickNCollectDeliveryMode(selectedShop.Id);
            Assert.AreEqual(DeliveryMode.ClickCollect, webSession.SelectedDeliveryMode);
            Assert.AreEqual(DeliveryMode.ClickCollect, webSession.SelectedDeliveryMode);
            Assert.AreEqual(selectedShop.Id, webSession.GetSelectedShop().Id);
            Assert.IsFalse(webSession.CanCompleteTransaction);
            Assert.IsTrue(
                webSession.PayWtihBC(
                    "4545-5555-5555-5555",
                    "01/25",
                    "111"
                    )
                );

            Assert.IsTrue(webSession.CanCompleteTransaction);
            webSession.CompleteTransaction();
            var orders = webSession.GetSelectedShop().GetClickAndCollectOrder();

            Assert.AreEqual(1, orders.Count());
        }
예제 #15
0
        private WebSession InitializeCoreAndSession()
        {
            if (!WebCore.IsInitialized)
            {
                WebCore.Initialize(new WebConfig()
                {
                    AssetProtocol = "https",
                    LogLevel      = LogLevel.Normal
                });
            }

            // Build a data path string. In this case, a Cache folder under our executing directory.
            // - If the folder does not exist, it will be created.
            // - The path should always point to a writeable location.
            string dataPath = String.Format("{0}{1}Cache", Path.GetDirectoryName(Application.ExecutablePath), Path.DirectorySeparatorChar);

            // Check if a session synchronizing to this data path, is already created;
            // if not, create a new one.
            session = WebCore.Sessions[dataPath] ??
                      WebCore.CreateWebSession(dataPath, new WebPreferences()
            {
            });

            session.AddDataSource(DataSource.CATCH_ALL, new MyDataSource());

            // The core must be initialized by now. Print the core version.
            Debug.Print(WebCore.Version.ToString());

            // Return the session.
            return(session);
        }
예제 #16
0
            private Task <SynchronizationContext> InitTask(string ipath)
            {
                TaskCompletionSource <SynchronizationContext> tcs = new TaskCompletionSource <SynchronizationContext>();
                TaskCompletionSource <object> complete            = new TaskCompletionSource <object>();

                Task.Factory.StartNew(() =>
                {
                    WebCore.Initialize(new WebConfig());
                    WebSession session = WebCore.CreateWebSession(WebPreferences.Default);

                    _EndTask = complete.Task;

                    _Father._WebView        = WebCore.CreateWebView(500, 500);
                    ipath                   = ipath ?? "javascript\\index.html";
                    _Father._WebView.Source = new Uri(string.Format("{0}\\{1}", Assembly.GetExecutingAssembly().GetPath(), ipath));

                    WebCore.Started += (o, e) => { tcs.SetResult(SynchronizationContext.Current); };

                    while (_Father._WebView.IsLoading)
                    {
                        WebCore.Run();
                    }
                    complete.SetResult(null);
                }
                                      );

                return(tcs.Task);
            }
예제 #17
0
 public void UpdateSession(WebSession webSession)
 {
     SessionId          = webSession.SessionId;
     SteamLogin         = webSession.SteamLogin;
     SteamLoginSecure   = webSession.SteamLoginSecure;
     RememberLoginToken = webSession.RememberLoginToken;
 }
예제 #18
0
        public LauncherForm(IApplicationCore AppCore)
        {
            this.AppCore = AppCore;

            PageStack = new Stack<Uri>();

            InitializeComponent();

            if (!WebCore.IsInitialized)
            {
                WebCore.Initialize(new WebConfig() {
                    HomeURL = new Uri(@"asset://bzlauncher/home"),
                    LogLevel = LogLevel.None,
                    RemoteDebuggingHost = @"127.0.0.1",
                    RemoteDebuggingPort = 8001
                }, true);
            }
            session = WebCore.CreateWebSession(@".\SessionDataPath", WebPreferences.Default);

            DataSource = new LauncherDataSource();
            ResourceInterceptor = new LauncherResourceInterceptor();

            session.AddDataSource("bzlauncher", DataSource);
            WebCore.ResourceInterceptor = ResourceInterceptor;
        }
예제 #19
0
        /// <summary>
        /// implement any cleanup here
        /// </summary>
        public void Dispose()
        {
            httpResponseHandler     = null;
            CustomUpStreamProxyUsed = null;

            WebSession.FinishSession();
        }
        public static HttpWebRequest BuildGetRequest(Uri _addr, WebSession _session)
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            if (_session.querySessionVars != null && _session.querySessionVars.Count > 0)
            {
                _addr = new Uri(string.Format("{0}&{1}", _addr.AbsoluteUri, _session.GetCombinedVars()));
            }
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_addr);

            httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            httpWebRequest.Method = "GET";
            if (Setting.SettingInstance.Proxy != null && Setting.SettingInstance.Proxy.Address != null)
            {
                httpWebRequest.Proxy = Setting.SettingInstance.Proxy;
            }
            httpWebRequest.AllowAutoRedirect = false;
            httpWebRequest.KeepAlive         = false;
            if (_session.sessionHeader != null && _session.sessionHeader.Count > 0)
            {
                httpWebRequest.Headers.Add(_session.sessionHeader);
            }
            if (_session.sessionCookie != null && _session.sessionCookie.Count > 0)
            {
                httpWebRequest.CookieContainer = _session.sessionCookie;
            }
            httpWebRequest.Timeout = Setting.SettingInstance.HttpReadWriteTimeout;
            return(httpWebRequest);
        }
예제 #21
0
        public void TestCutting()
        {
            var session = new WebSession();
            var buf     = session.GetRaw("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png");
            var ms      = new MemoryStream(buf);
            var img     = (Bitmap)Image.FromStream(ms);
            var eff     = new EffImage(img);

            // 透明底rgb是0
            eff.ProcessEach((_, i, j) =>
            {
                var color = _.At(i, j);

                if (color.R == 0)
                {
                    _.Set(i, j, Color.White);
                }
            });

            eff.GrayScale();
            eff.AdativeBinarization();
            eff = EffImage.CutH(eff, 200, 330);
            eff = EffImage.CutV(eff, 100, 230);
            eff.Origin.Save("z:/cut.bmp");
        }
예제 #22
0
        public Boolean IsRequired(Page page, WebSession session)
        {
            switch (page.Action)
            {
            case "AccidentsViolations":
                if (session.HasAccidentsViolations)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }

            case "Discounts":
                if (session.IsVibeState)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
예제 #23
0
 public static void CopyCookieContainer(this WebSession session, CookieContainer container)
 {
     foreach (Cookie c in container.GetAllCookies())
     {
         session.SetCookie(new Uri(c.Domain), String.Format("{0}={1};", c.Name, c.Value), c.HttpOnly, true); // (yn) Crossing Fingers
     }
 }
예제 #24
0
        /// <summary>
        /// implement any cleanup here
        /// </summary>
        public void Dispose()
        {
            httpResponseHandler          = null;
            CustomUpStreamHttpProxyUsed  = null;
            CustomUpStreamHttpsProxyUsed = null;

            WebSession.Dispose();
        }
 protected override void OnEndRequest(HttpContext context, EventArgs e)
 {
     if (WebSession.IsInitialized)
     {
         Logger.Debug("End Session");
         WebSession.EndSession(context, _cryptographicService);
     }
 }
예제 #26
0
        private bool VerifyWebServiceCommand(
            WebSession session,
            string webServiceURL,
            TestWebServiceCall webServiceCall,
            int command_index)
        {
            bool       success    = true;
            UriBuilder uriBuilder = new UriBuilder(webServiceURL + "/" + webServiceCall.command);
            string     fullUrl    = uriBuilder.ToString();

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string jsonResultString         = "";

            _logger.WriteLine("WebServiceValidator: INFO: Sending command #{0}", command_index + 1);
            _logger.WriteLine("url: {0}", fullUrl);

            try
            {
                SessionWebClient webClient        = new SessionWebClient(session);
                object           jsonResultObject = null;

                if (webServiceCall.queryParameters != null)
                {
                    jsonResultString =
                        webClient.POST(fullUrl, (Dictionary <string, object>)webServiceCall.queryParameters);
                }
                else
                {
                    jsonResultString =
                        webClient.GET(fullUrl);
                }

                jsonResultObject = serializer.DeserializeObject(jsonResultString);

                success = AreObjectsEqual("", webServiceCall.ignoreFields, webServiceCall.result, jsonResultObject);
            }
            catch (System.Exception ex)
            {
                _logger.WriteLine("WebServiceValidator: ERROR: Exception sending command");
                _logger.WriteLine(ex.Message);
                _logger.WriteLine(ex.StackTrace);
                success = false;
            }

            if (success)
            {
                _logger.WriteLine("WebServiceValidator: INFO: Received expected result");
            }
            else
            {
                _logger.WriteLine("WebServiceValidator: ERROR: Received unexpected result");
            }

            _logger.WriteLine("Result: {0}", jsonResultString);
            _logger.WriteLine();

            return(success);
        }
 public AwesomiumWPFWebWindowFactory(string iWebSessionPath = null)
 {
     if (_Session == null)
     {
         _Session = (iWebSessionPath != null) ?
                    WebCore.CreateWebSession(iWebSessionPath, new WebPreferences()) :
                    WebCore.CreateWebSession(new WebPreferences());
     }
 }
예제 #28
0
        /// <inheritdoc />
        public override bool Equals(WebSession other)
        {
            if (other is MobileSession mobileSession)
            {
                return(Equals(mobileSession));
            }

            return(false);
        }
예제 #29
0
        public IEnumerable <LightOrderInfo> GetOrdersToPack()
        {
            if (!WebSession.HasUserRight(OrdersPackingUserRights.ViewOrdersPackingWidget))
            {
                return(new LightOrderInfo[0]);
            }

            return(m_ordersFacade.GetAndSyncPaidOrders(DateTime.Now.AddDays(-30), true).Select(i => new LightOrderInfo(i)));
        }
 public AwesomiumWPFWebWindowFactory(string iWebSessionPath=null)
 {
     if (_Session == null)
     {
         _Session = (iWebSessionPath != null) ?
                     WebCore.CreateWebSession(iWebSessionPath, new WebPreferences()) :
                     WebCore.CreateWebSession(new WebPreferences());
     }
 }
예제 #31
0
        public PackingOrderModel FindOrder(string number)
        {
            WebSession.EnsureUserRight(OrdersPackingUserRights.OpenOrderPackingApplication);

            number = number.Trim();
            if (number.Length < 3)
            {
                throw new Exception("Musí být alespoň tři čísla");
            }

            var seek = m_orderRepository.SearchOrder(number, OrderStatus.ReadyToPack.Id);

            IPurchaseOrder filtered = null;

            if (seek != null)
            {
                filtered = m_orderRepository.GetOrder(seek.Value);
            }

            if (filtered == null)
            {
                Log.Info("Číslo objednávky nenalezeno");
                Log.Info("Spojuji se se Zásilkovnou...");
                var orderNumber = m_shipmentProvider.GetOrderNumberByPackageNumber(number);
                if (string.IsNullOrWhiteSpace(orderNumber))
                {
                    throw new Exception($"Objednávka {number} nebyla nalezena");
                }

                var paid =
                    m_orderRepository.GetOrdersByStatus(
                        OrderStatus.ReadyToPack,
                        DateTime.Now.AddDays(-90),
                        DateTime.Now.AddDays(1)).ToList();

                var order = paid.FirstOrDefault(o => (o.PreInvoiceId == orderNumber) || (o.OrderNumber == orderNumber));
                if (order == null)
                {
                    Log.Info("Aplikace nemá načtenu tuto zásilku, je třeba aktualizovat seznam zásilek z Floxu...");

                    paid = m_ordersFacade.GetAndSyncPaidOrders(DateTime.Now.AddDays(-30)).ToList();

                    order = paid.FirstOrDefault(o => (o.PreInvoiceId == orderNumber) || (o.OrderNumber == orderNumber));
                    if (order == null)
                    {
                        Log.Error("Nenalezeno");
                        throw new Exception($"Trasovací číslo bylo nalezeno v Zásilkovně pro objednávku č. {orderNumber}, která ale není mezi objednávkami k zabalení. Zkontrolujte objednávku ve FLOXu.");
                    }
                }

                Log.Info("Objednávka nalezena");

                return(MapOrder(order));
            }

            return(MapOrder(filtered));
        }
예제 #32
0
파일: frmMain.cs 프로젝트: dodola/MEditor
        public FrmMain()
        {
            InitializeComponent();
            string dataPath = String.Format("{0}{1}Cache", Path.GetDirectoryName(Application.ExecutablePath), Path.DirectorySeparatorChar);

            session = WebCore.Sessions[dataPath] ?? WebCore.CreateWebSession(dataPath, WebPreferences.Default);
            session.AddDataSource("local", new ResourceDataSource(ResourceType.Packed));
            this.webControl1.WebSession = session;
        }
예제 #33
0
/*====================================================*/

        public override void CorePage_Load(Object aSrc, EventArgs aEvent)
        {
            bool AdminKey = false;

            if (ModuleUser == null || WebSession == null)
            {
                Response.Redirect(WebAppl.LogoutURL);
            }

            if (ModuleUser.MasterNavElement != null && !WebSession.HasAdminUser)
            {
                XmlNodeList aNodeList = ModuleNode.SelectNodes("AdminNavigation/NavElement");
                foreach (XmlNode aNode in aNodeList)
                {
                    cNavElement aAdminNavElement = ModuleUser.MasterNavElement.Find_ChildElement(cXMLDoc.AttributeToString(aNode, "Key"));
                    if (aAdminNavElement.Key == NavKey)
                    {
                        AdminKey = true;
                        break;
                    }

                    foreach (cXMLNavElement aNavElement in aAdminNavElement.Elements)
                    {
                        if (aNavElement.Key == NavKey)
                        {
                            AdminKey = true;
                            break;
                        }
                    }
                }

                if (AdminKey && !WebSession.HasAdminUser)
                {
                    String aError = System.Configuration.ConfigurationSettings.AppSettings["PermissionErrorPage"];
                    if (aError != "")
                    {
                        String aRetURL = cWebLib.Get_QueryString(Request, "ReturnURL", "");
                        WebSession.CurrentUrl = aRetURL;
                        String aUrl = WebAppl.Build_RootURL(aError);
                        Response.Redirect(aUrl);
                    }
                    else
                    {
                        WebSession.LogoutAllUsers();
                        Response.Redirect(WebAppl.LogoutURL);
                    }
                }

                base.CorePage_Load(aSrc, aEvent);
            }
            else
            {
                base.CorePage_Load(aSrc, aEvent);
            }

            // Update Activity Log
        }
예제 #34
0
        public AwesomiumHTMLWindow(WebSession iSession, WebControl iWebControl)
        {
            _Session = iSession;
            _WebControl = iWebControl;
            _WebControl.SynchronousMessageTimeout = 0;
            _WebControl.ExecuteWhenReady(FireLoaded);
            _WebControl.ConsoleMessage += _WebControl_ConsoleMessage;

            MainFrame = new AwesomiumWebView(_WebControl);
        }
        public AwesomiumWPFWebWindowFactory(string webSessionPath=null) 
        {
            if (_Session != null)
                return;

            _Session = (webSessionPath != null) ?
                            WebCore.CreateWebSession(webSessionPath, new WebPreferences()) :
                            WebCore.CreateWebSession(new WebPreferences());

            WebCore.ShuttingDown += WebCore_ShuttingDown;
        }
예제 #36
0
 // --------------------------------------------------
 // Browser (Constructor)
 // --------------------------------------------------
 public Browser(WebSession session=null)
 {
     // Make a session if one wasn't provided
     if(session == null) session = WebCore.CreateWebSession(new WebPreferences());
     // Create the WebView
     view = WebCore.CreateWebView(1024, 768, session);
     // view.LoadingFrameComplete += DocumentReady;
     view.DocumentReady += DocumentReady;
     view.ConsoleMessage += ConsoleMessage;
     view.ShowCreatedWebView += OnShowCreatedWebView;
 }
예제 #37
0
파일: Browser.cs 프로젝트: dnmsk/rProject
 public Browser(BrowserSettings browserSettings)
 {
     _browserSettings = browserSettings;
     var preferences = new WebPreferences();
     if (browserSettings.Proxy?.Length > 0) {
         preferences.ProxyConfig = browserSettings.Proxy;
     }
     WebCore.DoWork(() => {
         _session = WebCore.CreateWebSession(preferences);
         return default(int);
     });
 }
예제 #38
0
        public bool ValidateWebService(Command command)
        {
            bool success = true;
            string web_service_url= "";
            string script_path = "";
            TestWebServiceScript testScript= null;

            if (command.HasArgumentWithName("S"))
            {
                script_path= command.GetTypedArgumentByName<CommandArgument_String>("S").ArgumentValue;
            }
            else
            {
                _logger.WriteLine("WebServiceValidator: Missing expected validation script parameter");
                success = false;
            }

            if (command.HasArgumentWithName("W"))
            {
                web_service_url= command.GetTypedArgumentByName<CommandArgument_String>("W").ArgumentValue;
            }
            else
            {
                _logger.WriteLine("WebServiceValidator: ERROR: No WebService URL given");
                success = false;
            }

            // Deserialize the web service script
            if (success)
            {
                success = ParseWebServiceScript(script_path, out testScript);
            }

            if (success)
            {
                WebSession session = new WebSession();
                int command_index = 0;

                foreach (TestWebServiceCall webServiceCall in testScript.commands)
                {
                    if (!VerifyWebServiceCommand(session, web_service_url, webServiceCall, command_index))
                    {
                        success = false;
                        break;
                    }

                    command_index++;
                }
            }

            return success;
        }
예제 #39
0
        public WebForm()
        {
            WebCore.Initialize( WebConfig.Default );
            session = WebCore.CreateWebSession( WebPreferences.Default );

            Debug.Print( WebCore.Version.ToString() );

            // Notice that 'Control.DoubleBuffered' has been set to true
            // in the designer, to prevent flickering.

            InitializeComponent();

            // Initialize the view.
            InitializeView( WebCore.CreateWebView( this.ClientSize.Width, this.ClientSize.Height, session ) );
        }
        public AwesomiumWPFWebWindow(WebSession iSession)
        {
            _Session = iSession;

            _WebControl = new WebControl()
            {
                WebSession = _Session,
                Visibility = Visibility.Hidden,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                ContextMenu = new ContextMenu() { Visibility = Visibility.Collapsed }
            };

            _AwesomiumHTMLWindow = new AwesomiumHTMLWindow(_Session, _WebControl);     
        }
예제 #41
0
 internal BrowserTab(BrowserSettings browserSettings, WebSession session)
 {
     WebCore.DoWork(() => {
         _webView = WebCore.CreateWebView(browserSettings.WindowWidth, browserSettings.WindowHeight, session, WebViewType.Offscreen);
         return default(int);
     });
     _reloadThread = new Thread(() => {
         while (true) {
             Thread.Sleep(TimeSpan.FromHours(1));
             WebCore.QueueWork(() => {
                 _webView.Reload(true);
             });
         }
     });
     _reloadThread.Start();
 }
예제 #42
0
        public FrameworkElement Initialize() {
            if (_session == null) {
                if (!WebCore.IsInitialized) {
                    WebCore.Initialize(new WebConfig {
                        UserAgent = DefaultUserAgent,
                        ReduceMemoryUsageOnNavigation = true,
                        LogLevel = LogLevel.None,
#if DEBUG
                        RemoteDebuggingHost = @"127.0.0.1",
                        RemoteDebuggingPort = 45451,
#endif
                        AdditionalOptions = new[] {
                            @"disable-desktop-notifications"
                        },
                        CustomCSS = @"
::-webkit-scrollbar { width: 8px!important; height: 8px!important; }
::-webkit-scrollbar-track { box-shadow: none!important; border-radius: 0!important; background: #000!important; }
::-webkit-scrollbar-corner { background: #000 !important; }
::-webkit-scrollbar-thumb { border: none !important; box-shadow: none !important; border-radius: 0 !important; background: #333 !important; }
::-webkit-scrollbar-thumb:hover { background: #444 !important; }
::-webkit-scrollbar-thumb:active { background: #666 !important; }"
                    });
                }

                _session = WebCore.CreateWebSession(FilesStorage.Instance.GetTemporaryFilename(@"Awesomium"), new WebPreferences {
                    EnableGPUAcceleration = true,
                    WebGL = true,
                    SmoothScrolling = false,
                    FileAccessFromFileURL = true,
                    UniversalAccessFromFileURL = true
                });
            }

            _inner = new BetterWebControl {
                WebSession = _session,
                UserAgent = DefaultUserAgent
            };

            _inner.LoadingFrame += OnLoadingFrame;
            _inner.LoadingFrameComplete += OnLoadingFrameComplete;
            _inner.LoadingFrameFailed += OnLoadingFrameComplete;
            _inner.DocumentReady += OnDocumentReady;
            return _inner;
        }
예제 #43
0
        private WebSession InitializeCoreAndSession()
        {
            if ( !WebCore.IsRunning )
                WebCore.Initialize( new WebConfig() { LogLevel = LogLevel.Normal } );

            // Build a data path string. In this case, a Cache folder under our executing directory.
            // - If the folder does not exist, it will be created.
            // - The path should always point to a writeable location.
            string dataPath = String.Format( "{0}{1}Cache", Path.GetDirectoryName( Application.ExecutablePath ), Path.DirectorySeparatorChar );

            // Check if a session synchronizing to this data path, is already created;
            // if not, create a new one.
            session = WebCore.Sessions[ dataPath ] ??
                WebCore.CreateWebSession( dataPath, WebPreferences.Default );

            // The core must be initialized by now. Print the core version.
            Debug.Print( WebCore.Version.ToString() );

            // Return the session.
            return session;
        }
        IWebView IWebViewLifeCycleManager.Create()
        {
            if (_Session == null)
            {
                _Session = (_WebSessionPath != null) ? WebCore.CreateWebSession(_WebSessionPath, new WebPreferences()) :
                        WebCore.CreateWebSession(new WebPreferences());

                WebCore.ShuttingDown += WebCore_ShuttingDown;
            }

            WebControl nw = new WebControl()
            {
                WebSession = _Session,
                Visibility = Visibility.Hidden,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                ContextMenu = new ContextMenu() { Visibility = Visibility.Collapsed }
            };
            Grid.SetColumnSpan(nw, 2);
            Grid.SetRowSpan(nw, 2);
            Panel.SetZIndex(nw, 0);
            this.MainGrid.Children.Add(nw);
            return nw;
        }
예제 #45
0
    // We override this to assign a WebSession to the WebUIComponent,
    // before it goes live. The component will go live after Start.
    protected override void Awake()
    {
        if ( Application.isEditor )
            return;

        if ( !webUI )
            return;

        // Get or create an in-memory WebSession.
        if ( session == null )
        {
            session = WebCore.CreateWebSession( new WebPreferences() { SmoothScrolling = true } );
            UnityEngine.Debug.Log( "Created In-Memory Session" );
        }

        if ( session.GetDataSource( "media" ) == null )
        {
            // Create and add a ResourceDataSource. This will be used to load assets
            // from the resources assembly (AwesomiumSampleResources) available with this sample.
            ResourceDataSource dataSource = new ResourceDataSource(
                ResourceType.Embedded,
                typeof( AwesomiumSampleResources.Loader ).Assembly );
            session.AddDataSource( "media", dataSource );

            UnityEngine.Debug.Log( "Added DataSource" );
        }

        // Assign the WebSession to the WebUIComponent.
        webUI.WebSession = session;
        UnityEngine.Debug.Log( String.Format( "WebSession Assigned to {0}.", barType ) );
    }
예제 #46
0
        static void Main(string[] args)
        {
            bool help = false;
            bool screens = false;
            string user = null, pass = null;
            string chatUrl = null, scriptUrl = null;
            string sessionPath = null;
            // http://geekswithblogs.net/robz/archive/2009/11/22/command-line-parsing-with-mono.options.aspx
            OptionSet options = new OptionSet()
                .Add("?|h|help", "Print this message", option => help = option != null)
                .Add("u=|user=|username="******"Required: StackExchange username or email", option => user = option)
                .Add("p=|pass=|password="******"Required: StackExchange password", option => pass = option)
                .Add("c=|chat-url=", "Required: Chatroom URL", option => chatUrl = option)
                .Add("b=|bot-script=|script-url=", "Required: The URL of a bot script", option => scriptUrl = option)
                .Add("s|screens|screenshot", "Display screenshots at checkpoints", option => screens = option != null)
                .Add("session-path=", "Path to browser session (profile), where settings are saved", option => sessionPath = option);

            #if DEBUG
            string[] lines = File.ReadAllLines("account.txt");
            user = lines[0];
            pass = lines[1];
            chatUrl = "http://chat.stackexchange.com/rooms/118/root-access";
            scriptUrl = "https://raw.github.com/allquixotic/SO-ChatBot/master/master.js";
            screens = true;
            sessionPath = "session";
            #else
            try
            {
                options.Parse(args);
            }
            catch (OptionException)
            {
                ShowHelp(options, "Error - usage is:");
            }

            if (help)
            {
                ShowHelp(options, "Usage:");
            }

            if (user == null)
            {
                ShowHelp(options, "Error: A username is required");
            }

            if (pass == null)
            {
                ShowHelp(options, "Error: A password is required");
            }

            if (chatUrl == null)
            {
                ShowHelp(options, "Error: A chat URL is required");
            }

            if (scriptUrl == null)
            {
                ShowHelp(options, "Error: A bot script is required");
            }

            if (sessionPath == null)
            {
                sessionPath = "session";
            }
            #endif

            try
            {
                WebConfig config = new WebConfig();
                WebCore.Initialize(config);

                WebPreferences prefs = new WebPreferences();
                prefs.LoadImagesAutomatically = true;
                prefs.RemoteFonts = false;
                prefs.WebAudio = false;
                prefs.Dart = false;
                prefs.CanScriptsCloseWindows = false;
                prefs.CanScriptsOpenWindows = false;
                prefs.WebSecurity = false;
                prefs.Javascript = true;
                prefs.LocalStorage = true;
                prefs.Databases = false;            // ?

                aweSession = WebCore.CreateWebSession(sessionPath, prefs);
                aweSession.ClearCookies();
                aweView = WebCore.CreateWebView(1024, 768, aweSession);
                aweView.ResponsiveChanged += aweView_ResponsiveChanged;
                aweView.Crashed += aweView_Crashed;
                aweView.ConsoleMessage += aweView_ConsoleMessage;
                eView.WebView = aweView;
                eView.AutoScreenshot = true;
                eView.ScreenshotsEnabled = screens;

                go(user, pass, scriptUrl, chatUrl);
            }
            finally
            {
                if (aweView != null && aweView.IsResponsive)
                    aweView.Dispose();
                WebCore.Shutdown();
            }
        }
예제 #47
0
        private bool VerifyWebServiceCommand(
            WebSession session,
            string webServiceURL,
            TestWebServiceCall webServiceCall,
            int command_index)
        {
            bool success= true;
            UriBuilder uriBuilder = new UriBuilder(webServiceURL + "/" + webServiceCall.command);
            string fullUrl = uriBuilder.ToString();

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string jsonResultString = "";

            _logger.WriteLine("WebServiceValidator: INFO: Sending command #{0}", command_index+1);
            _logger.WriteLine("url: {0}", fullUrl);

            try
            {
                SessionWebClient webClient = new SessionWebClient(session);
                object jsonResultObject= null;

                if (webServiceCall.queryParameters != null)
                {
                    jsonResultString =
                        webClient.POST(fullUrl, (Dictionary<string, object>)webServiceCall.queryParameters);
                }
                else
                {
                    jsonResultString =
                        webClient.GET(fullUrl);
                }

                jsonResultObject = serializer.DeserializeObject(jsonResultString);

                success = AreObjectsEqual("", webServiceCall.ignoreFields, webServiceCall.result, jsonResultObject);
            }
            catch (System.Exception ex)
            {
                _logger.WriteLine("WebServiceValidator: ERROR: Exception sending command");
                _logger.WriteLine(ex.Message);
                _logger.WriteLine(ex.StackTrace);
                success = false;
            }

            if (success)
            {
                _logger.WriteLine("WebServiceValidator: INFO: Received expected result");
            }
            else
            {
                _logger.WriteLine("WebServiceValidator: ERROR: Received unexpected result");
            }

            _logger.WriteLine("Result: {0}", jsonResultString);
            _logger.WriteLine();

            return success;
        }
예제 #48
0
        private void ReloadWebCore()
        {
            //if (WebCore.IsRunning)
            //    WebCore.Shutdown();

            if (_aweWebView != null && _aweWebView.Surface != null && !((BitmapSurface)_aweWebView.Surface).IsDisposed)
            {
                ((BitmapSurface)_aweWebView.Surface).Dispose();
            }

            if (_aweWebView != null && !_aweWebView.IsDisposed)
            {
                _aweWebView.Dispose();
                _aweWebView = null;
            }

            if (!WebCore.IsRunning)
            {
                // webcore moze da se iniciajlizuje samo jednom u okviru procesa. cak ni shutdown ne pomaze.

                // awesomium setup
                var cnfg = new WebConfig();
                cnfg.AdditionalOptions = new string[]
                                             {
                                                 "--enable-accelerated-filters"
                                                 , "--enable-accelerated-painting"
                                                 , "--enable-accelerated-plugins"
                                                 , "--enable-threaded-compositing"
                                                 , "--gpu-startup-dialog"
                                             };
                cnfg.UserAgent = Settings.BrowserUserAgent;
                //cnfg.AutoUpdatePeriod = 50;

                WebCore.Initialize(cnfg);

                WebPreferences webPreferences = WebPreferences.Default;
                webPreferences.ProxyConfig = "auto";
                _aweWebSession = WebCore.CreateWebSession(
                    String.Format("{0}{1}Cache", Path.GetDirectoryName(Application.ExecutablePath),
                                  Path.DirectorySeparatorChar),
                    webPreferences);
            }
        }
예제 #49
0
 public SessionWebClient(WebSession session)
 {
     Session = session;
 }
예제 #50
0
        /// <summary>
        /// Create a new visual to render.
        /// </summary>
        /// <returns></returns>
        private WebControl CreateRenderable()
        {
            // Get the web control.
            var pControl = new WebControl();

            // Create a web-session with our settings.
            if (pWebSession == null)
            {
                pWebSession = WebCore.CreateWebSession(new WebPreferences()
                {
                    EnableGPUAcceleration = Properties.Settings.Default.EnableGPUAcceleration,
                    Databases = Properties.Settings.Default.EnableWebDatabases,
                    WebGL = Properties.Settings.Default.EnableWebGL,
                    WebSecurity = Properties.Settings.Default.EnableWebSecurity,
                    FileAccessFromFileURL = Properties.Settings.Default.EnableWebFileAccessFromFileURL,
                    Plugins = true,
                });
            }
            pControl.WebSession = pWebSession;

            // Set the render dimensions.
            pControl.Width = this.RenderResolution.X;
            pControl.Height = this.RenderResolution.Y;

            // Hide the surface while we load.
            if (ActiveSurface != null)
                ActiveSurface.ContentOpacity = 0.01;

            // When the process has been createad, bind the global JS objects.
            // http://awesomium.com/docs/1_7_rc3/sharp_api/html/M_Awesomium_Core_IWebView_CreateGlobalJavascriptObject.htm
            pControl.ProcessCreated += (object sender, EventArgs e) =>
            {
                // CALLING window.Surface = {} in JS here has no effect.

                // Bind all the Authority.request and Authority.call methods.
                Log.Write("Display Process Created (1)", this.ToString(), Log.Type.AppError);
                BindAPIFunctions(pControl);
            };

            UrlEventHandler p = null;
            p = new UrlEventHandler((object senderOuter, UrlEventArgs eOuter) =>
                {
                    // Unbind this handler.
                    pControl.DocumentReady -= p;

                    // Force a re-load so the $(document).ready will have access to our Authority.request etc.
                    pControl.Reload(false);

                    // CALLING window.Surface = {} in JS here has no effect.
                    //SignalSurfacePropertiesChanged();
                    Log.Write("Display DocReady (1)", this.ToString(), Log.Type.AppError);
                    

                    // Bind the other events.
                    #region Events
                    // Handle navigating away from the URL in the load instruction.
                    pControl.AddressChanged += (object sender, UrlEventArgs e) =>
                    {
                        // Rebind the API methods?
                        Log.Write("Display has changed web address. " + e.Url, this.ToString(), Log.Type.DisplayInfo);
                    };

                    // Handle console messages.
                    pControl.TitleChanged += (object sender, TitleChangedEventArgs e) =>
                    {
                        this.Title = e.Title;
                    };

                    // Document ready.. do we beat JQuery?
                    pControl.DocumentReady += (object sender, UrlEventArgs e) =>
                    {
                        // Show the surface now we are loaded.
                        if (ActiveSurface != null)
                            ActiveSurface.ContentOpacity = 1.0;

                        // CALLING window.Surface = {} in JS here does not work quick enough.
                        Log.Write("Display DocReady (2)", this.ToString(), Log.Type.AppError);
                        SignalSurfacePropertiesChanged();

                        // EXPERIMENTAL - this sort of works.. depends on how the page detects touch events..
                        // SEE: Nice example: http://paulirish.com/demo/multi
                        // SEE: Nicer example: Bing maps!
                        // Try to inject multi-touch into the page.
                        if (ActiveSurface.AttemptMultiTouchInject)
                        {
                            pControl.ExecuteJavascript(Properties.Resources.MultiTouchInject);   
                        }
                        
                    };

                    // Handle changes in responsiveness.
                    pControl.ResponsiveChanged += (object sender, ResponsiveChangedEventArgs e) =>
                    {
                        // If it is not responsive, log the problem.
                        if (!e.IsResponsive)
                        {
                            Log.Write("Display is not responsive.  Try reloading.", this.ToString(), Log.Type.DisplayError);
                            //this.Reload(false, true);
                        }
                        else
                        {
                            Log.Write("Ready", this.ToString(), Log.Type.DisplayError);
                        }
                    };

                    // Handle crashes by reloading.
                    pControl.Crashed += (object sender, CrashedEventArgs e) =>
                    {
                        // Log the crash.
                        Log.Write("Display crashed - forcing reload. Termination Status = " + e.Status.ToString(), this.LoadInstruction, Log.Type.DisplayError);

                        // Force a hard-reload.  This will remove then re-create the entire web control.
                        this.Reload(true);
                    };
                    /*
                    // Handle javascript updates.
                    pControl.JSConsoleMessageAdded += (object sender, Awesomium.Core.JSConsoleMessageEventArgs e) =>
                    {
                        Log.Write("JS line " + e.LineNumber + ": " + e.Message, pActiveDisplay.ToString(), Log.Type.DisplayInfo);
                    };
            
                    // Handle pop-up messages (like alert).
                    pControl.ShowPopupMenu += (object sender, PopupMenuEventArgs e) =>
                    {
                    
                    };
                    */
                    #endregion
                });
            pControl.DocumentReady += p;

            // Set the load instruction.
            //   n.b. we have to then re-load it later to get access to our value
            pControl.Source = new Uri(this.LoadInstruction);

            // Return the created control.
            return pControl;
        }
예제 #51
0
        public Form1()
        {
            InitializeComponent();

            Session = WebCore.CreateWebSession(
                   String.Format("{0}{1}Cache",
                   Path.GetDirectoryName(Application.ExecutablePath), Path.DirectorySeparatorChar),
                   new WebPreferences()
                   {
                       SmoothScrolling = true,
                       WebGL = true,
                       // Windowed views, support full hardware acceleration.
                       EnableGPUAcceleration = true,
                   });

            webControl1.WebSession = Session;

            //this.Hide();
        }
예제 #52
0
파일: WebHost.cs 프로젝트: tommybiteme/X
 public void ProcessRequest(WebSession conn)
 {
     AddPendingCall();
     try
     {
         new WebRequest(this, conn).Process();
     }
     finally
     {
         RemovePendingCall();
     }
 }