public AndroidAgent(
            IActivityTracker activityTracker,
            int contentId = -1)
        {
            ActivityTracker = activityTracker;
            ContentId       = contentId;

            var displaySize = GetRealSize(Application
                                          .Context
                                          .GetSystemService(global::Android.Content.Context.WindowService)
                                          .JavaCast <IWindowManager> ()
                                          .DefaultDisplay);

            Identity = new AgentIdentity(
                AgentType.Android,
                new Sdk(
                    SdkId.XamarinAndroid,
                    new FrameworkName(typeof(Java.Interop.Runtime)
                                      .Assembly
                                      .GetCustomAttribute <TargetFrameworkAttribute> ()
                                      .FrameworkName),
                    Array.Empty <string> (),
                    "Android"),
                GetApplicationName(),
                deviceManufacturer: Build.Manufacturer,
                screenWidth: displaySize.X,
                screenHeight: displaySize.Y);

            RepresentationManager.AddProvider(new AndroidRepresentationProvider());

            ViewHierarchyHandlerManager.AddViewHierarchyHandler("Android", this);
        }
示例#2
0
 PulseEmitter(AgentContext Context, AgentIdentity Identity, PulseEmitterConfig Config)
     : base(Context, Identity)
 {
     this.Timer           = new Timer(Config.Frequency.TotalMilliseconds);
     this.Timer.AutoReset = true;
     this.Timer.Elapsed  += OnPulse;
 }
示例#3
0
        public MacAndroidCoordinateMapper(AgentIdentity agentIdentity)
        {
            hostRect = agentIdentity.DeviceManufacturer == "Xamarin"
                ? GetXapHostRect()
                : GetGoogleHostRect();

            scale = agentIdentity.ScreenWidth / hostRect.Width;
        }
示例#4
0
        /// <summary>
        /// Provides very basic workbook parsing and shunting of code cells
        /// into the evaluation service. Does not display non-code-cell contents
        /// but does evaluate a workbook from top-to-bottom. Restores nuget
        /// packages from the workbook's manifest.
        /// </summary>
        static async Task <int> WorkbookPlayerMain(InteractiveSession session, ClientSessionUri sessionUri)
        {
            var path = new FilePath(sessionUri.WorkbookPath);

            if (!path.FileExists)
            {
                Error.WriteLine($"File does not exist: {path}");
                return(1);
            }

            // load the workbook file
            var workbook = new WorkbookPackage(path);
            await workbook.Open(
                quarantineInfo => Task.FromResult(true),
                path);

            #pragma warning disable 0618
            // TODO: WorkbookDocumentManifest needs to eliminate AgentType like we've done on web
            // to avoid having to use the the flavor mapping in AgentIdentity.
            var targetPlatformIdentifier = AgentIdentity.GetFlavorId(workbook.PlatformTargets [0]);
            #pragma warning restore 0618

            // initialize the session based on manifest metadata from the workbook file
            language = workbook.GetLanguageDescriptions().First();
            await session.InitializeAsync(new InteractiveSessionDescription (
                                              language,
                                              targetPlatformIdentifier,
                                              new EvaluationEnvironment(Environment.CurrentDirectory)));

            // restore NuGet packages
            await session.PackageManagerService.RestoreAsync(
                workbook.Pages.SelectMany(page => page.Packages));

            // insert and evaluate cells in the workbook
            foreach (var cell in workbook.IndexPage.Contents.OfType <CodeCell> ())
            {
                var buffer = cell.CodeAnalysisBuffer.Value;

                lastCodeCellId = await session.EvaluationService.InsertCodeCellAsync(
                    buffer,
                    lastCodeCellId);

                ForegroundColor = ConsoleColor.DarkYellow;
                Write(GetPrompt());
                ResetColor();

                WriteLine(buffer);

                await session.EvaluationService.EvaluateAsync(lastCodeCellId);

                if (lastCellEvaluationStatus != CodeCellEvaluationStatus.Success)
                {
                    break;
                }
            }

            return(0);
        }
示例#5
0
        public void Add_enforces_max_table_size()
        {
            int maxEntryCount = 100;

            IAgentIdentity agentIdentity = new AgentIdentity
            {
                ID = "agentId" + DateTime.UtcNow.Ticks,
                PathToAgentDataDirectory = _pathToDbDirectory
            };

            SqliteLogRepository logRepository = new SqliteLogRepositoryDecorator(
                agentIdentity,
                new InMemoryLogWriter(100),
                maxEntryCount);

            logRepository.Initialize();

            //default Add operations per trim execution is 100
            for (int entryNumber = 0; entryNumber < maxEntryCount + 1; entryNumber++)
            {
                logRepository.Add(new LogEntry(MessageLevel.Verbose, "add test", entryNumber.ToString()));

                Thread.Sleep(1);
            }

            using (SQLiteConnection dbConnection = ((SqliteLogRepositoryDecorator)logRepository).GetNewDbConnection())
            {
                dbConnection.Open();

                using (SQLiteCommand dbCommand = new SQLiteCommand("SELECT count(*) FROM Log", dbConnection))
                {
                    long rowCount = (long)dbCommand.ExecuteScalar();

                    Assert.AreEqual(maxEntryCount, rowCount, "Incorrect number of rows trimmed from Log table.");
                }

                using (
                    SQLiteCommand dbCommand = new SQLiteCommand(
                        "SELECT Message FROM Log ORDER BY Time LIMIT 1",
                        dbConnection))
                {
                    string oldestMessage = (string)dbCommand.ExecuteScalar();

                    Assert.AreEqual("1", oldestMessage, "Incorrect rows trimmed from table.");
                }

                using (
                    SQLiteCommand dbCommand = new SQLiteCommand(
                        "SELECT Message FROM Log ORDER BY Time DESC LIMIT 1",
                        dbConnection))
                {
                    string newestMessage = (string)dbCommand.ExecuteScalar();

                    Assert.AreEqual("100", newestMessage, "Incorrect rows trimmed from table.");
                }
            }
        }
        //重写基类的异常处理方法
        public override void OnException(ExceptionContext context)
        {
            var         e   = context.Exception;
            ReturnModel ret = null;

            AgentPrincipal principal = null;
            AgentIdentity  identity  = null;
            long           agentid   = 0;

            //系统级错误
            if (e is FailException)
            {
                var fexp = e as FailException;
                ret = new ReturnModel(fexp.Code, fexp.Msg, fexp.RetData);
            }
            else if (e is NoLoginException)
            {
                ret = new ReturnModel(ECode.TOKEN_ERROR, "TOKEN错误");
            }
            else if (e is RedisConnectException)
            {
                ret = new ReturnModel(ECode.SYSTEM_ERROR, "系统异常", e.Message);
            }
            else if (e is ParameterException)
            {
                ret = new ReturnModel(ECode.PARAMETER_ERROR, "参数错误", e.Message);
            }
            else if (e is MySqlException)
            {
                ret = new ReturnModel(ECode.SYSTEM_ERROR, "系统异常", e.Message);
            }
            else
            {
                //用户级错误
                principal = context.HttpContext.User as AgentPrincipal;
                identity  = principal.Identity as AgentIdentity;
                agentid   = identity.AgentId;

                if (e is NoPermissionException)
                {
                    var ex  = e as NoPermissionException;
                    var msg = ex.Permissions.Select(f => f.ToString()).Aggregate((r, i) => $"{r} {i}");

                    ret = new ReturnModel(ECode.UNAUTHORIZED, "没有权限", ex.Message + msg);
                }
                else
                {
                    ret = new ReturnModel(ECode.Exception, "系统异常", string.Format("{0},{1}", e.Message, e.StackTrace));
                }
            }

            Log.Logger("Exception").Error(string.Format("{0}:{1}", ret.Msg, ret.Data));
            context.Result = new JsonResult(ret);
            base.OnException(context);
        }
示例#7
0
        public void Add_throws_exception_if_called_before_Initialize()
        {
            IAgentIdentity agentIdentity = new AgentIdentity
            {
                ID = "agentId" + DateTime.UtcNow.Ticks,
                PathToAgentDataDirectory = _pathToDbDirectory
            };

            SqliteLogRepository logRepository = new SqliteLogRepository(agentIdentity, new InMemoryLogWriter(100));

            logRepository.Add(new LogEntry(MessageLevel.Verbose, "add test", "should throw exception"));
        }
示例#8
0
        public async Task OneAgentProcessForManyTickets(int ticketCount)
        {
            MainThread.Ensure();

            var           ticketRequests = new Task <AgentProcessTicket> [ticketCount];
            AgentIdentity firstIdentity  = null;

            Func <Task <AgentProcessTicket> > RequestTicketAsync = async() => {
                var ticket = await workbookApp.RequestTestTicketAsync();

                ticket.ShouldNotBeNull();

                var identity = await ticket.GetAgentIdentityAsync();

                identity.ShouldNotBeNull();

                Interlocked.CompareExchange(ref firstIdentity, identity, null);

                return(ticket);
            };

            await Task.Run(async() => {
                for (var i = 0; i < ticketRequests.Length; i++)
                {
                    ticketRequests [i] = RequestTicketAsync();
                }

                await Task.WhenAll(ticketRequests).ConfigureAwait(false);
            });

            MainThread.Ensure();

            foreach (var ticketRequest in ticketRequests)
            {
                ticketRequest.IsCompleted.ShouldBeTrue();

                var ticket   = ticketRequest.Result;
                var identity = await ticket.GetAgentIdentityAsync();

                identity.Id.ShouldEqual(firstIdentity.Id);
                identity.ShouldBeSameAs(firstIdentity);
            }

            observedAgentIdentityIds.ShouldNotContain(firstIdentity.Id);
            observedAgentIdentityIds.Add(firstIdentity.Id);

            foreach (var ticketRequest in ticketRequests)
            {
                ticketRequest.Result.Dispose();
            }
        }
示例#9
0
        AgentConnection(
            IAgentTicket ticket,
            AgentType type,
            AgentIdentity identity,
            IAgentClient apiClient,
            AgentFeatures features)
        {
            this.ticket = ticket;

            Type     = type;
            Identity = identity;
            Api      = apiClient;
            Features = features;
        }
示例#10
0
        public iOSAgent()
        {
            Identity = new AgentIdentity(
                AgentType.iOS,
                Sdk.FromEntryAssembly(SdkId.XamarinIos, "iOS"),
                NSBundle.MainBundle.InfoDictionary ["CFBundleName"] as NSString,
                screenWidth: (int)UIScreen.MainScreen.Bounds.Width,
                screenHeight: (int)UIScreen.MainScreen.Bounds.Height);

            RepresentationManager.AddProvider(new iOSRepresentationProvider());
            new UnifiedNativeHelper().Initialize();

            ViewHierarchyHandlerManager.AddViewHierarchyHandler("UIKit", this);
        }
示例#11
0
        public AgentAssociation(AgentIdentity identity, AgentClient client)
        {
            if (identity == null)
            {
                throw new ArgumentNullException(nameof(identity));
            }

            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            Identity = identity;
            Client   = client;
        }
示例#12
0
        AgentConnection(
            IAgentTicket ticket,
            AgentType type,
            AgentIdentity identity,
            AgentClient apiClient,
            ImmutableArray <string> assemblySearchPaths,
            AgentFeatures features)
        {
            this.ticket = ticket;

            Type                = type;
            Identity            = identity;
            Api                 = apiClient;
            AssemblySearchPaths = assemblySearchPaths;
            Features            = features;
        }
示例#13
0
        public void Add_inserts_new_record_in_log_table()
        {
            IAgentIdentity agentIdentity = new AgentIdentity
            {
                ID = "agentId" + DateTime.UtcNow.Ticks,
                PathToAgentDataDirectory = _pathToDbDirectory
            };

            SqliteLogRepositoryDecorator logRepository = new SqliteLogRepositoryDecorator(
                agentIdentity,
                new InMemoryLogWriter(100));

            logRepository.Initialize();

            logRepository.Add(new LogEntry(MessageLevel.Verbose, "add test", "should add this row to table"));

            using (SQLiteConnection dbConnection = logRepository.GetNewDbConnection())
            {
                dbConnection.Open();

                string sql = "SELECT * FROM Log";

                using (SQLiteCommand dbCommand = new SQLiteCommand(sql, dbConnection))
                {
                    using (SQLiteDataReader dataReader = dbCommand.ExecuteReader())
                    {
                        Assert.IsTrue(dataReader.HasRows, "Row not added to Log table.");

                        dataReader.Read();

                        object[] columnValues =
                            Enumerable.Range(0, dataReader.FieldCount).Select(dataReader.GetValue).ToArray();

                        Assert.IsTrue(columnValues[1] is DateTime, "'Time' column value incorrect.");
                        Assert.AreEqual(
                            (int)MessageLevel.Verbose,
                            Convert.ToInt32(columnValues[2]),
                            "'Level' column value incorrect.");
                        Assert.AreEqual("add test", columnValues[3], "'Source' column value incorrect.");
                        Assert.AreEqual(
                            "should add this row to table",
                            columnValues[4],
                            "'Message' column value incorrect.");
                    }
                }
            }
        }
示例#14
0
        public void Initialize_adds_log_table_to_db()
        {
            IAgentIdentity agentIdentity = new AgentIdentity
            {
                ID = "agentId" + DateTime.UtcNow.Ticks,
                PathToAgentDataDirectory = _pathToDbDirectory
            };

            SqliteLogRepositoryDecorator logRepository = new SqliteLogRepositoryDecorator(
                agentIdentity,
                new InMemoryLogWriter(100));

            logRepository.Initialize();

            using (SQLiteConnection dbConnection = logRepository.GetNewDbConnection())
            {
                dbConnection.Open();

                bool logTableExists;

                string sql = "SELECT count(name) FROM sqlite_master WHERE name = 'log'";

                using (SQLiteCommand testCommand = new SQLiteCommand(sql, dbConnection))
                {
                    logTableExists = (long)testCommand.ExecuteScalar() > 0;
                }

                Assert.IsTrue(logTableExists, "Log table not created.");

                sql = "select * from log limit 1";

                using (SQLiteCommand testCommand = new SQLiteCommand(sql, dbConnection))
                {
                    using (SQLiteDataReader dataReader = testCommand.ExecuteReader())
                    {
                        string[] columnNames =
                            Enumerable.Range(0, dataReader.FieldCount).Select(dataReader.GetName).ToArray();

                        Assert.IsTrue(columnNames.Contains("ID"), "ID column missing from Log table.");
                        Assert.IsTrue(columnNames.Contains("Time"), "Time column missing from Log table.");
                        Assert.IsTrue(columnNames.Contains("Level"), "Level column missing from Log table.");
                        Assert.IsTrue(columnNames.Contains("Source"), "Source column missing from Log table.");
                        Assert.IsTrue(columnNames.Contains("Message"), "Message column missing from Log table.");
                    }
                }
            }
        }
示例#15
0
        public void All_locks_on_db_file_release_after_being_accessed()
        {
            IAgentIdentity agentIdentity = new AgentIdentity
            {
                ID = DateTime.UtcNow.Ticks.ToString(),
                PathToAgentDataDirectory = _pathToDbDirectory
            };

            SqliteLogRepository logRepository = new SqliteLogRepository(
                agentIdentity,
                new InMemoryLogWriter(100));

            logRepository.Initialize();

            string[] testFiles = Directory.GetFiles(_pathToDbDirectory, "*.log").ToArray();

            Array.ForEach(testFiles, File.Delete);
        }
示例#16
0
        public WpfAgent(Func <Window> mainWindowCreator = null)
        {
            this.mainWindowCreator = mainWindowCreator;
            latestMainWindow       = mainWindowCreator?.Invoke();
            if (latestMainWindow != null)
            {
                latestMainWindow.WindowState = WindowState.Minimized;
                latestMainWindow.Show();
            }

            Identity = new AgentIdentity(
                AgentType.WPF,
                Sdk.FromEntryAssembly("WPF"),
                Assembly.GetEntryAssembly().GetName().Name);

            RepresentationManager.AddProvider(wpfRepresentationProvider = new WpfRepresentationProvider());

            ViewHierarchyHandlerManager.AddViewHierarchyHandler("WPF", this);
        }
示例#17
0
        public MacAgent()
        {
            #if MAC_MOBILE
            var          agentType = AgentType.MacMobile;
            const string profile   = "Modern";
            #elif MAC_DESKTOP
            var          agentType = AgentType.MacNet45;
            const string profile   = "Full";
            #endif

            Identity = new AgentIdentity(
                agentType,
                Sdk.FromEntryAssembly("Xamarin.Mac", profile),
                NSBundle.MainBundle.InfoDictionary ["CFBundleName"] as NSString);

            RepresentationManager.AddProvider(new MacRepresentationProvider());
            new UnifiedNativeHelper().Initialize();

            ViewHierarchyHandlerManager.AddViewHierarchyHandler("AppKit", this);
        }
示例#18
0
        public TestAgent(IdentifyAgentRequest identifyAgentRequest)
            : base(unitTestContext: true)
        {
            Identity = new AgentIdentity(
                AgentType.Test,
                Sdk.FromEntryAssembly("Test"),
                nameof(TestAgent));

            IdentifyAgentRequest = identifyAgentRequest;

            Action <TestAgent> allocHandler = null;

            lock (allocHandlers) {
                if (allocHandlers.Count > 0)
                {
                    allocHandler = allocHandlers.Pop();
                }
            }

            allocHandler?.Invoke(this);
        }
        public iOSSimulatorCoordinateMapper(AgentIdentity agentIdentity)
        {
            // TODO: Pick the correct window with extra information available when Device Switching work
            //       lands. For now, we know we always launch 5s, but in Xcode 9 there may be multiple
            //       sims open simultaneously.
            var window = InspectableWindow
                         .GetWindows("com.apple.iphonesimulator")
                         .FirstOrDefault(w => w.Title != null &&
                                         (ClientInfo.Flavor == ClientFlavor.Inspector || w.Title.Contains("5s")));

            if (window == null)
            {
                Log.Error(TAG, "Unable to locate simulator window");
                return;
            }

            if (!ShowDeviceBezels(window))
            {
                appBounds         = window.Bounds;
                appBounds.Y      += 22;
                appBounds.Height -= 22;
            }
            else
            {
                var shape            = GetDeviceShape(window);
                var chromeScale      = window.Bounds.Height / GetDeviceFullHeight(shape);
                var verticalMargin   = GetDeviceVerticalMargin(shape) * chromeScale;
                var horizontalMargin = GetDeviceHorizontalMargin(shape) * chromeScale;

                appBounds = new CGRect {
                    X      = window.Bounds.X + horizontalMargin,
                    Y      = window.Bounds.Y + verticalMargin,
                    Width  = window.Bounds.Width - (horizontalMargin * 2),
                    Height = window.Bounds.Height - (verticalMargin * 2),
                };
            }

            scale = agentIdentity.ScreenWidth / appBounds.Width;
        }
示例#20
0
        /// <summary>
        /// Provides very basic workbook parsing and shunting of code cells
        /// into the evaluation service. Does not display non-code-cell contents
        /// but does evaluate a workbook from top-to-bottom. Restores nuget
        /// packages from the workbook's manifest.
        /// </summary>
        static async Task <int> WorkbookPlayerMain(string workbookPath)
        {
            var path = new FilePath(workbookPath);

            if (!path.FileExists)
            {
                Error.WriteLine($"File does not exist: {path}");
                return(1);
            }

            // load the workbook file
            var workbook = new WorkbookPackage(path);
            await workbook.Open(
                quarantineInfo => Task.FromResult(true),
                path);

            // create and get ready to deal with the session; a more complete
            // client should handle more than just OnNext from the observer.
            var session = InteractiveSession.CreateWorkbookSession();

            session.Events.Subscribe(new Observer <InteractiveSessionEvent> (OnSessionEvent));

            #pragma warning disable 0618
            // TODO: WorkbookDocumentManifest needs to eliminate AgentType like we've done on web
            // to avoid having to use the the flavor mapping in AgentIdentity.
            var targetPlatformIdentifier = AgentIdentity.GetFlavorId(workbook.PlatformTargets [0]);
            #pragma warning restore 0618

            // initialize the session based on manifest metadata from the workbook file
            language = workbook.GetLanguageDescriptions().First();
            await session.InitializeAsync(new InteractiveSessionDescription (
                                              language,
                                              targetPlatformIdentifier,
                                              new EvaluationEnvironment(Environment.CurrentDirectory)));

            // restore NuGet packages
            await session.PackageManagerService.RestoreAsync(
                workbook.Pages.SelectMany(page => page.Packages));

            // insert and evaluate cells in the workbook
            foreach (var cell in workbook.IndexPage.Contents.OfType <CodeCell> ())
            {
                var buffer = cell.CodeAnalysisBuffer.Value;

                lastCodeCellId = await session.EvaluationService.InsertCodeCellAsync(
                    buffer,
                    lastCodeCellId);

                WriteReplPrompt();
                WriteLine(buffer);

                await session.EvaluationService.EvaluateAsync(lastCodeCellId);
                await EvaluationServiceRaceBug();

                if (lastCellEvaluationStatus != CodeCellEvaluationStatus.Success)
                {
                    break;
                }
            }

            return(0);
        }
示例#21
0
文件: EventEmitter.cs 项目: 0xCM/z0
 protected EventEmitter(IAgentContext Context, AgentIdentity Identity)
     : base(Context, Identity)
 {
 }
示例#22
0
 public static PulseEmitter Define(AgentContext Context, AgentIdentity Identity, PulseEmitterConfig Config)
 => new PulseEmitter(Context, Identity, Config);
示例#23
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var identity = new AgentIdentity(10001, "honan");

            SetPrincipal(context, new AgentPrincipal(identity));
        }
 public AgentType GetAgentType()
 => AgentIdentity.GetAgentType(Id);
        #pragma warning disable 0618

        public static WorkbookAppInstallation Locate(AgentType agentType)
        => LookupById(AgentIdentity.GetFlavorId(agentType));
示例#26
0
 public static ComputerIdentity ToComputerIdentity(this AgentIdentity agentInfo)
 {
     return(new ComputerIdentity(agentInfo.ComputerName, agentInfo.DomainName));
 }
 public async Task <AgentIdentity> GetAgentIdentityAsync(CancellationToken cancellationToken)
 => agentIdentity ?? (agentIdentity = await client.GetAgentIdentityAsync(cancellationToken));
示例#28
0
 protected EventSink(AgentContext Context, AgentIdentity Identity)
     : base(Context, Identity)
 {
 }
示例#29
0
 public static IServiceAgent Define(AgentContext Context, AgentIdentity Identity)
 => new SystemEventSink(Context, Identity);
示例#30
0
 SystemEventSink(AgentContext Context, AgentIdentity Identity)
     : base(Context, Identity)
 {
 }