示例#1
0
        public static T Find(SearchCriteria searchCriteria, UIItem item)
        {
            T element = null;

            try
            {
                element = item.Get <T>(searchCriteria);
            }
            catch (AutomationException ex)
            {
                LoggerUtil.Info($"Element is not found: {ex}");
            }

            return(element);
        }
示例#2
0
        public static UIItem FindItemByIndex(TreeScope treeScope, Condition condition, int index)
        {
            var    elements = App.GetInstance().Window.AutomationElement.FindAll(treeScope, condition);
            UIItem element  = null;

            for (var i = 0; i < elements.Count; i++)
            {
                if (i == index)
                {
                    element = new UIItem(elements[i], new NullActionListener());
                }
            }
            LoggerUtil.Info($"Element {element.Name} is found");
            return(element);
        }
示例#3
0
        /// <summary>
        /// Sends credentials to the server to attempt authentication.
        /// </summary>
        /// <param name="username">
        /// Username to authorize with.
        /// </param>
        /// <param name="password">
        /// Password to authorize with.
        /// </param>
        public void AttemptAuthentication(string username, SecureString password)
        {
            var msg = new AuthenticationMessage(AuthenticationAction.Requested, username, password);

            var logger = LoggerUtil.GetAppWideLogger();

            try
            {
                PushMessage(msg);
            }
            catch (Exception e)
            {
                LoggerUtil.RecursivelyLogException(logger, e);
            }
        }
示例#4
0
        /// <summary>
        /// 注册
        /// </summary>
        public virtual void Register()
        {
            var proxy = Proxy();

            if (proxy == null)
            {
                return;
            }
            //
            SetProxy(Key, proxy);
            if (Exists <ILogger>())
            {
                LoggerUtil.InfoAsync($"接口代理[{typeof(T).FullName}]注册完成");
            }
        }
示例#5
0
        public void AddBlockAction(BlockType cause, Uri requestUri, string categoryNameString, string matchingRule)
        {
            LoggerUtil.GetAppWideLogger().Info($"Sending block action to server: cause={cause}, requestUri={requestUri}, categoryNameString={categoryNameString}, matchingRule={matchingRule}");
            BlockInfo blockInfo = new BlockInfo(cause, requestUri, categoryNameString, matchingRule);

            //ReportList.Add(blockInfo);

            string json = JsonConvert.SerializeObject(blockInfo);

            byte[] formData = Encoding.UTF8.GetBytes(json);

            HttpStatusCode statusCode;

            WebServiceUtil.Default.SendResource(ServiceResource.AccountabilityNotify, formData, out statusCode);
        }
示例#6
0
        /// <summary>
        /// Detects whether we are blocked by a captive portal and returns result accordingly.
        /// </summary>
        private async Task <bool> IsCaptivePortalActive()
        {
            if (!NetworkStatus.Default.HasIpv4InetConnection && !NetworkStatus.Default.HasIpv6InetConnection)
            {
                // No point in checking further if no internet available.
                try
                {
                    IPHostEntry entry = Dns.GetHostEntry("connectivitycheck.cloudveil.org");
                }
                catch (Exception ex)
                {
                    m_logger.Info("No DNS servers detected as up by captive portal.");
                    LoggerUtil.RecursivelyLogException(m_logger, ex);

                    return(false);
                }

                // Did we get here? This probably means we have internet access, but captive portal may be blocking.
            }

            CaptivePortalDetected ret = checkCaptivePortalState();

            if (ret == CaptivePortalDetected.NoResponseReturned)
            {
                m_logger.Info("Captive Portal no response returned.");

                // If no response is returned, this may mean that
                // a) the network is still initializing
                // b) we have no internet.
                // Schedule a Trigger() for 1.5 second in the future to handle (a)

                Task.Delay(1500).ContinueWith((task) =>
                {
                    Trigger();
                });

                return(false);
            }
            else if (ret == CaptivePortalDetected.Yes)
            {
                m_logger.Info("Captive portal detected.");
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public void AddExemptionRequest(HttpWebRequest request, X509Certificate certificate)
        {
            try
            {
                using (SqliteCommand command = m_connection.CreateCommand())
                {
                    bool clearExemptionData  = false;
                    bool createExemptionData = false;

                    SqliteParameter param0 = new SqliteParameter("$certHash", certificate.GetCertHashString());
                    SqliteParameter param1 = new SqliteParameter("$host", request.Host);

                    command.CommandText = $"SELECT Thumbprint, Host, DateExempted, ExpireDate FROM cert_exemptions WHERE Thumbprint = $certHash AND Host = $host";
                    command.Parameters.Add(param0);
                    command.Parameters.Add(param1);
                    using (SqliteDataReader reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            clearExemptionData = !isReaderRowCurrentlyExempted(reader);
                        }
                        else
                        {
                            createExemptionData = true;
                        }
                    }

                    if (clearExemptionData)
                    {
                        command.CommandText = $"UPDATE cert_exemptions SET DateExempted = NULL, ExpireDate = NULL WHERE Thumbprint = $certHash AND Host = $host";
                        command.ExecuteNonQuery();

                        OnAddCertificateExemption?.Invoke(request.Host, certificate.GetCertHashString(), false);
                    }
                    else if (createExemptionData)
                    {
                        command.CommandText = $"INSERT INTO cert_exemptions (DateExempted, ExpireDate, Thumbprint, Host) VALUES (NULL, NULL, $certHash, $host)";
                        command.ExecuteNonQuery();

                        OnAddCertificateExemption?.Invoke(request.Host, certificate.GetCertHashString(), false);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerUtil.RecursivelyLogException(m_logger, ex);
            }
        }
示例#8
0
        /// <summary>
        /// Called when each request is intercepted and has not gone to the server yet.
        /// </summary>
        internal ProxyNextAction OnBeforeRequest(GoproxyWrapper.Session args)
        {
            ProxyNextAction nextAction = ProxyNextAction.AllowAndIgnoreContent;
            int             trackId    = 0;

            lock (trackIdLock)
            {
                trackId = nextTrackId++;
            }

            // Don't allow filtering if our user has been denied access and they
            // have not logged back in.
            if (m_ipcServer != null && m_ipcServer.WaitingForAuth)
            {
                return(ProxyNextAction.AllowAndIgnoreContentAndResponse);
            }

            try
            {
                ZonedDateTime        date             = m_timeDetection.GetRealTime();
                TimeRestrictionModel todayRestriction = null;

                if (m_policyConfiguration != null && m_policyConfiguration.TimeRestrictions != null && date != null)
                {
                    todayRestriction = m_policyConfiguration.TimeRestrictions[(int)date.ToDateTimeOffset().DayOfWeek];
                }

                string urlString           = args.Request.Url;
                Uri    url                 = new Uri(urlString);
                Uri    serviceProviderPath = new Uri(CompileSecrets.ServiceProviderApiPath);

                if (url.Host == serviceProviderPath.Host)
                {
                    return(ProxyNextAction.AllowAndIgnoreContentAndResponse);
                }
                else if (todayRestriction != null && todayRestriction.RestrictionsEnabled && !m_timeDetection.IsDateTimeAllowed(date, todayRestriction))
                {
                    sendBlockResponse(args, urlString, null, BlockType.TimeRestriction);
                    return(ProxyNextAction.DropConnection);
                }
            }
            catch (Exception e)
            {
                LoggerUtil.RecursivelyLogException(m_logger, e);
            }

            return(nextAction);
        }
        /// <summary>
        /// Add a new Product.
        /// </summary>
        /// <param name="product">The new Product.</param>
        /// <returns>If Product was added.</returns>
        public bool AddProduct(Product product)
        {
            this.libraryContext.Products.Add(product);
            var successful = this.libraryContext.SaveChanges() != 0;

            if (successful)
            {
                LoggerUtil.LogInfo($"Product added successfully : {product.Id},{product.Name} ", MethodBase.GetCurrentMethod());
            }
            else
            {
                LoggerUtil.LogError($"Product failed to add to database : {product.Id},{product.Name}", MethodBase.GetCurrentMethod());
            }

            return(successful);
        }
示例#10
0
        /// <summary>
        /// Add a new Bid.
        /// </summary>
        /// <param name="bid">The new Bid.</param>
        /// <returns>If Bid was added.</returns>
        public bool AddBid(Bid bid)
        {
            this.libraryContext.Bids.Add(bid);
            var successful = this.libraryContext.SaveChanges() != 0;

            if (successful)
            {
                LoggerUtil.LogInfo($"Bid added successfully : {bid.Id}", MethodBase.GetCurrentMethod());
            }
            else
            {
                LoggerUtil.LogError($"Bid failed to add to database : {bid.Id}", MethodBase.GetCurrentMethod());
            }

            return(successful);
        }
示例#11
0
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            var dependencyAssemblyPrefix = AppSettingConfig.IocDependencyAssemblyPattern;
            //var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>();
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().Cast <Assembly>();

            if (!dependencyAssemblyPrefix.IsNullOrWhiteSpace())
            {
                var regex = new Regex(dependencyAssemblyPrefix);
                assemblies = assemblies.Where(p => regex.IsMatch(p.FullName));
            }
            var dependencyType = typeof(IDependency);

            builder.RegisterAssemblyTypes(assemblies.ToArray()).Where(type => dependencyType.IsAssignableFrom(type) && !type.IsAbstract).AsImplementedInterfaces().InstancePerLifetimeScope();
            LoggerUtil.InfoAsync($"Ioc模块[{typeof(DependencyModule).FullName}]注册完成");
        }
示例#12
0
        public static UIItem FindItemByIndex(TreeScope treeScope, Condition condition, int index)
        {
            var    elements = Scope.DefaultWindow.AutomationElement.FindAll(treeScope, condition);
            UIItem element  = null;

            for (var i = 0; i < elements.Count; i++)
            {
                if (i == index)
                {
                    element = new UIItem(elements[i], new NullActionListener());
                }
            }
            AssertionUtil.AssertNotNull(element, "Element is not found");
            LoggerUtil.Info($"Element {element.Name} is found");
            return(element);
        }
        /// <summary>
        /// Add a new UserReview.
        /// </summary>
        /// <param name="userReview">The new UserReview.</param>
        /// <returns>If price was UserReview.</returns>
        public bool AddUserReview(UserReview userReview)
        {
            this.libraryContext.UserReviews.Add(userReview);
            var successful = this.libraryContext.SaveChanges() != 0;

            if (successful)
            {
                LoggerUtil.LogInfo($"UserReview added successfully : {userReview.Id}", MethodBase.GetCurrentMethod());
            }
            else
            {
                LoggerUtil.LogError($"UserReview failed to add to database : {userReview.Id}", MethodBase.GetCurrentMethod());
            }

            return(successful);
        }
        /// <summary>
        /// Add a new category.
        /// </summary>
        /// <param name="category">The new category.</param>
        /// <returns>If category was added.</returns>
        public bool AddCategory(Category category)
        {
            this.libraryContext.Categories.Add(category);
            var successful = this.libraryContext.SaveChanges() != 0;

            if (successful)
            {
                LoggerUtil.LogInfo($"Category added successfully : {category.Name} ", MethodBase.GetCurrentMethod());
            }
            else
            {
                LoggerUtil.LogError($"Category failed to add to database : {category.Name}", MethodBase.GetCurrentMethod());
            }

            return(successful);
        }
示例#15
0
        public int OnBlacklist(Session args, string url, int[] categories)
        {
            try
            {
                RequestBlocked?.Invoke((short)categories[0], BlockType.None, new Uri(url), "NOT AVAILABLE");

                sendBlockResponse(args, url, categories);
            }
            catch (Exception ex)
            {
                m_logger.Error("Exception occurred while processing blacklist notification.");
                LoggerUtil.RecursivelyLogException(m_logger, ex);
            }

            return(0);
        }
示例#16
0
 private void assignPedToAlloedVehicleIfHeGettingInto(Ped ped)
 {
     if (IsPedAlloedToAssignVehicle(ped))
     {
         LoggerUtil.logInfo(ped, "Ped is allowed to assign a vehicle...");
         Vehicle vehicle = (Vehicle)tryingToEnterVehclesWithPeds[ped];
         pedsAndVehicleManagment.addVehicaleAndAssignItToPed(ped, vehicle);
         closestVehicleCache.Remove(ped);
         if (vehicle.Driver != null)
         {
             vehicle.Driver.Delete();
             ped.SetIntoVehicle(vehicle, VehicleSeat.Driver);
             LoggerUtil.logInfo(ped, "Driver should leave vehicle then flee from the ped!");
         }
     }
 }
示例#17
0
        private void MainWindow_Activated(object sender, EventArgs e)
        {
            try
            {
                // Show binary version # in the title bar.
                string title = System.Diagnostics.Process.GetCurrentProcess().ProcessName;

                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                title     += " - Version " + System.Reflection.AssemblyName.GetAssemblyName(assembly.Location).Version.ToString(3);
                this.Title = title;
            }
            catch (Exception err)
            {
                LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), err);
            }
        }
示例#18
0
        /// <summary>
        /// Add a new price.
        /// </summary>
        /// <param name="price">The new price.</param>
        /// <returns>If price was added.</returns>
        public bool AddPrice(Price price)
        {
            this.libraryContext.Prices.Add(price);
            var successful = this.libraryContext.SaveChanges() != 0;

            if (successful)
            {
                LoggerUtil.LogInfo($"Price added successfully : {price.Value}{price.Currency} ", MethodBase.GetCurrentMethod());
            }
            else
            {
                LoggerUtil.LogError($"Price failed to add to database : {price.Value}{price.Currency}", MethodBase.GetCurrentMethod());
            }

            return(successful);
        }
        /// <summary>
        /// Get AuctionUser by first name and last name.
        /// </summary>
        /// <param name="firstName">The first name.</param>
        /// <param name="lastName">The last name.</param>
        /// <returns>An AuctionUser.</returns>
        public AuctionUser GetAuctionUserByFistNameAndLastName(string firstName, string lastName)
        {
            if (firstName.IsNullOrEmpty())
            {
                LoggerUtil.LogInfo($"Param firstName is required.", MethodBase.GetCurrentMethod());
                return(null);
            }

            if (lastName.IsNullOrEmpty())
            {
                LoggerUtil.LogInfo($"Param lastName is required.", MethodBase.GetCurrentMethod());
                return(null);
            }

            return(this.auctionUserRepository.GetAuctionUser(firstName, lastName));
        }
        /// <summary>Adds the category.</summary>
        /// <param name="category">The category.</param>
        /// <returns>True if category was added to database.</returns>
        public bool AddCategory(Category category)
        {
            this._auctionDb.Categories.Add(category);
            var successful = this._auctionDb.SaveChanges() != 0;

            if (successful)
            {
                LoggerUtil.LogInfo($"Category added successfully : {category.CategoryName} ");
            }
            else
            {
                LoggerUtil.LogError($"Category failed to add to db : {category.CategoryName}");
            }

            return(successful);
        }
        /// <summary>
        /// Add a new auctionUser.
        /// </summary>
        /// <param name="auctionUser">The new auctionUser.</param>
        /// <returns>If auctionUser was added.</returns>
        public bool AddAuctionUser(AuctionUser auctionUser)
        {
            this.libraryContext.AuctionUsers.Add(auctionUser);
            var successful = this.libraryContext.SaveChanges() != 0;

            if (successful)
            {
                LoggerUtil.LogInfo($"AuctionUser added successfully : {auctionUser.FirstName} ", MethodBase.GetCurrentMethod());
            }
            else
            {
                LoggerUtil.LogError($"AuctionUser failed to add to database : {auctionUser.FirstName}", MethodBase.GetCurrentMethod());
            }

            return(successful);
        }
        /// <summary>
        /// Add a new Auction.
        /// </summary>
        /// <param name="auction">The new Auction.</param>
        /// <returns>If Auction was added.</returns>
        public bool AddAuction(Auction auction)
        {
            this.libraryContext.Auctions.Add(auction);
            var successful = this.libraryContext.SaveChanges() != 0;

            if (successful)
            {
                LoggerUtil.LogInfo($"Auction added successfully ID: {auction.Id}", MethodBase.GetCurrentMethod());
            }
            else
            {
                LoggerUtil.LogError($"Auction failed to add to database ID: {auction.Id}", MethodBase.GetCurrentMethod());
            }

            return(successful);
        }
        /// <summary>Check if the bid is correct.</summary>
        /// <param name="auction">The auction.</param>
        /// <param name="price">The price.</param>
        /// <returns>Return if the bid is correct.</returns>
        public bool IsBidCorrect(Auction auction, Price price)
        {
            if (auction != null && price != null)
            {
                if (auction.Bid == null)
                {
                    if (price.ThePrice > (auction.StartingPrice.ThePrice * 10 / 100) + auction.StartingPrice.ThePrice)
                    {
                        LoggerUtil.LogError("Your bid can be at most 10% from the starting price");
                        return(false);
                    }

                    if (price.ThePrice <= auction.StartingPrice.ThePrice)
                    {
                        LoggerUtil.LogError("Your bid can not be lower than starting price");
                        return(false);
                    }
                }
                else
                {
                    if (price.ThePrice < auction.Bid.Price.ThePrice)
                    {
                        LoggerUtil.LogError("Your bid can not be lower than last bid");
                        return(false);
                    }

                    double v = (auction.Bid.Price.ThePrice * 10) / 100;
                    if (price.ThePrice > v + auction.Bid.Price.ThePrice)
                    {
                        LoggerUtil.LogError("Your bid can be at most 10% from the current price");
                        return(false);
                    }
                }

                if (auction.StartingPrice.Currency != price.Currency)
                {
                    LoggerUtil.LogError("Your price currency does not match the auction currency");
                    return(false);
                }
            }
            else
            {
                return(false);
            }

            return(true);
        }
示例#24
0
        public static IUIItem[] FindAll(SearchCriteria searchCriteria, Window window = null)
        {
            if (window == null)
            {
                window = Scope.DefaultWindow;
            }

            try
            {
                return(window.GetMultiple(searchCriteria));
            }
            catch (AutomationException ex)
            {
                LoggerUtil.Info($"Element is not found: {ex}");
            }
            throw new Exception("Element is not found");
        }
示例#25
0
        /// <summary>
        /// Default ctor.
        /// </summary>
        public CitadelApp()
        {
            m_logger = LoggerUtil.GetAppWideLogger();

            string appVerStr = System.Diagnostics.Process.GetCurrentProcess().ProcessName;

            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            appVerStr += " " + System.Reflection.AssemblyName.GetAssemblyName(assembly.Location).Version.ToString();
            appVerStr += " " + (Environment.Is64BitProcess ? "x64" : "x86");

            m_logger.Info("CitadelGUI Version: {0}", appVerStr);

            // Enforce good/proper protocols
            ServicePointManager.SecurityProtocol = (ServicePointManager.SecurityProtocol & ~SecurityProtocolType.Ssl3) | (SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12);

            this.Startup += CitadelOnStartup;
        }
示例#26
0
 public JsonResult DeleteConfirmed(int id)
 {
     try
     {
         ProductType obj = GetById(id);
         NSession.Delete(obj);
         NSession.Flush();
         NSession.Delete("from WarehouseStockType where SKU='" + obj.SKU + "'");
         NSession.Flush();
         LoggerUtil.GetProductRecord(obj, "删除商品", "商品被删除", CurrentUser, NSession);
     }
     catch (Exception ee)
     {
         return(Json(new { IsSuccess = false, ErrorMsg = "出错了" }));
     }
     return(Json(new { IsSuccess = true }));
 }
示例#27
0
 private void StealClosestVehicle(Ped ped, List <Vehicle> closestVehiclesToPed)
 {
     foreach (Vehicle vehicle in closestVehiclesToPed)
     {
         if (isPedAllowedToStealVehicle(ped, vehicle))
         {
             if (!vehicle.Equals(ped.VehicleTryingToEnter))
             {
                 LoggerUtil.logInfo(ped, "was allowed to steal vehciel: " + vehicle.GetHashCode());
                 AddVehicleToPedTryingToEnterVehicles(ped, vehicle);
                 ped.Task.EnterVehicle(vehicle, VehicleSeat.Driver, -1, 30, EnterVehicleFlags.AllowJacking);
                 LoggerUtil.logInfo(ped, "Is entering vehicle: " + vehicle.GetHashCode());
             }
             break;
         }
     }
 }
示例#28
0
        /// <summary>
        /// Called when the background initialization function has returned.
        /// </summary>
        /// <param name="sender">
        /// Event origin.
        /// </param>
        /// <param name="e">
        /// Event args.
        /// </param>
        private void OnBackgroundInitComplete(object sender, RunWorkerCompletedEventArgs e)
        {
            // Must ensure we're not blocking internet now that we're running.
            WFPUtility.EnableInternet();

            if (e.Cancelled || e.Error != null)
            {
                m_logger.Error("Error during initialization.");
                if (e.Error != null && m_logger != null)
                {
                    LoggerUtil.RecursivelyLogException(m_logger, e.Error);
                }

                Current.Shutdown(-1);
                return;
            }
        }
        /// <summary>
        /// Validation for description .
        /// </summary>
        /// <param name="description">The description.</param>
        /// <returns>If UserReview is valid or not.</returns>
        private bool ValidateDescription(string description)
        {
            if (description.IsNullOrEmpty())
            {
                LoggerUtil.LogInfo($"Description is invalid. You tried to add an userRole with null empty description.", MethodBase.GetCurrentMethod());
                return(false);
            }

            if ((description.Length < 3) || (description.Length > 100))
            {
                LoggerUtil.LogInfo(
                    $"Description is invalid. You tried to add an userRole with invalid length description.", MethodBase.GetCurrentMethod());
                return(false);
            }

            return(true);
        }
示例#30
0
        public void NotifyTimeZoneChanged(DateTimeZone oldZone, DateTimeZone newZone)
        {
            LoggerUtil.GetAppWideLogger().Info($"Sending time zone changed to server. oldZone = {oldZone.Id}, newZone = {newZone.Id}");
            TimeZoneChangeInfo info = new TimeZoneChangeInfo()
            {
                new_zone_id = newZone?.Id,
                old_zone_id = oldZone?.Id
            };

            string json = JsonConvert.SerializeObject(info);

            byte[] formData = Encoding.UTF8.GetBytes(json);

            HttpStatusCode statusCode;

            WebServiceUtil.Default.SendResource(ServiceResource.AccountabilityNotify, formData, out statusCode);
        }