Exemplo n.º 1
0
        static void Main()
        {
            //new CrashLogTraceListener();

            using (Mutex mutex = new Mutex(false, MutexName))
            {
                if (mutex.WaitOne(1, true) == false)
                {
                    MessageBox.Show("Another instance of ConnectUO 2.0 Updater is running.  Please wait for that instance to close before running the Updater again.", "Already Running");
                    return;
                }

                for (Process[] processArray = Process.GetProcessesByName("ConnectUO.exe"); processArray.Length > 0; processArray = Process.GetProcessesByName("ConnectUO.exe"))
                {
                    Thread.Sleep(50);
                }

                _applicationInfo = new ApplicationInfo();

                Directory.SetCurrentDirectory(_applicationInfo.BaseDirectory);

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmUpdate());

                if (_status == UpdateStatus.Success)
                {
                    Process.Start(Path.Combine(_applicationInfo.BaseDirectory, "ConnectUO.exe"));
                }

                _applicationInfo.Process.Kill();
            }
        }
        public BmGame(String[] args)
        {
            int width = WIDTH;
            int height = HEIGHT;

            int realWidth = width + WIDTH_EX;
            int realHeight = height;

            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth = realWidth;
            graphics.PreferredBackBufferHeight = realHeight;

            IsFixedTimeStep = true;

            Content.RootDirectory = "Content";

            ApplicationInfo info = new ApplicationInfo(width, height);
            #if WINDOWS
            info.nativeInterface = this;
            info.realWidth = realWidth;
            info.realHeight = realHeight;
            IsMouseVisible = true;
            #endif
            info.args = args;

            application = new BmApplication(Content, info);
        }
 /// <summary>
 /// Copies the elements of the specified <see cref="ApplicationInfo">ApplicationInfo</see> array to the end of the collection.
 /// </summary>
 /// <param name="value">An array of type <see cref="ApplicationInfo">ApplicationInfo</see> containing the Components to add to the collection.</param>
 public void AddRange(ApplicationInfo[] value)
 {
     for (int i = 0; (i < value.Length); i = (i + 1))
     {
         this.Add(value[i]);
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            packageId = PanelSecurity.PackageId;

            // load app info
            try
            {
                app = ES.Services.ApplicationsInstaller.GetApplication(packageId, PanelRequest.ApplicationID);
                if (app == null)
                    RedirectToBrowsePage();


                LoadApplicationSettingsControl();

                if (!IsPostBack)
                {
                    BindWebSites();
                    BindDatabaseVersions();
                    ToggleControls();
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("APPINSTALLER_INIT_FORM", ex);
                return;
            }
        }
Exemplo n.º 5
0
		// 将CStringArray中的主机事项写入ini文件或者registry
		public static void SaveHosts(ApplicationInfo appInfo,
			ArrayList saHost)
		{
			string strEntry = null;
			int i = 0;

			for(i=0; i<saHost.Count; i++) 
			{

				strEntry = "entry" + Convert.ToString(i+1);
			
				string strValue = (string)saHost[i];
			
				appInfo.SetString("ServerAddress",
					strEntry,
					strValue);
			}

			// 最后一次,截断
			strEntry = "entry" + Convert.ToString(i+1);
			appInfo.SetString("ServerAddress",
				strEntry,
				"");
	
		}
Exemplo n.º 6
0
 public static ApplicationInfo ToApplication(this DataRow dr)
 {
     ApplicationInfo info = new ApplicationInfo();
     info.ApplicationID = dr.GetGuid("ApplicationID");
     info.ApplicationName = dr.GetString("ApplicationName");
     return info;
 }
Exemplo n.º 7
0
 public Summary(DeviceInfo deviceInfo, ApplicationInfo applicationInfo)
 {
     this.Date = DateTime.SpecifyKind(deviceInfo.Date, DateTimeKind.Utc);
     this.ApplicationId = applicationInfo.ApplicationId;
     this.PlatformId = deviceInfo.PlatformType;
     this.Version = applicationInfo.Version;
     this.Count++;
 }
Exemplo n.º 8
0
        /// <summary>
        /// Calls <see cref="CheckCommandArguments"/> and checks, if there are errors or not.
        /// </summary>
        /// <param name="args">The arguments given to the application.</param>
        /// <param name="appInfo">Informations on the app.</param>    
        /// <returns><c>True</c> if the command arguments are valid, otherwise <c>false</c>.</returns>
        public static bool AreCommandArgumentsValid(string[] args, ApplicationInfo appInfo)
        {
            var result = CheckCommandArguments(args, appInfo);
#if TRACE
            result.ForEach(line => Trace.WriteLine(line));
#endif
            return result.Count == 0;
        }
        public void CreateApplication(string name)
        {
            var applicationInfo = new ApplicationInfo();
            applicationInfo.Name = name;
            applicationInfo.CreatedAt = DateTime.UtcNow;

            UseRepository(repositoryService=>repositoryService.CreateApplication(applicationInfo));
        }
Exemplo n.º 10
0
        protected override void Setup(ApplicationInfo info)
        {
            base.Setup(info);

            MyWindow myWindow = new MyWindow(new WindowTemplate());

            SetWindow(myWindow);
        }
Exemplo n.º 11
0
        public static void Main(string[] args)
        {
            var applicationInfo = new ApplicationInfo();
            Console.WriteLine("***************************************************************");
            Console.WriteLine(string.Format("-- {0} {1}", applicationInfo.AssemblyTitle, applicationInfo.AssemblyVersion));
            Console.WriteLine(string.Format("-- {0}", applicationInfo.AssemblyCopyright));
            Console.WriteLine("***************************************************************");

            GetRandomFiles();
        }
Exemplo n.º 12
0
        protected override void Setup(ApplicationInfo info)
        {
            base.Setup(info);

            MyWindow win = new MyWindow(new WindowTemplate()
            {
                HasFrame = true,
            });

            SetWindow(win);
        }
Exemplo n.º 13
0
        public void StartApplication(string configFile)
        {
            //start in separate thread
            ApplicationInfo appInfo = new ApplicationInfo(XDocument.Load(configFile));

            appInfo.Completed += appInfo_Completed;
            //when the app is about to stop services, it should check whether the service is used by other programs
            appInfo.ServiceCheckCallback = new ServiceCheckFunction(IsServiceUsedByOtherApps);
            apps.Add(appInfo);

            appInfo.Start();
        }
Exemplo n.º 14
0
		public override Resources getResourcesForApplication (ApplicationInfo app)
		{
			if (app.packageName.Equals ("system")) {
				return mContext.mMainThread.getSystemContext ().getResources ();
			}
			Resources r = mContext.mMainThread.getTopLevelResources (
				app.publicSourceDir, mContext.mPackageInfo);
			if (r != null) {
				return r;
			}
			throw new NameNotFoundException ("Unable to open " + app.publicSourceDir);
		}
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            ApplicationInfo appInfo = new ApplicationInfo()
            {
                Title = "OchreGui Demo",
                ScreenSize = new Size(80, 70),
                Font = "courier12x12_aa_tc.png",
                FontFlags = libtcod.TCODFontFlags.LayoutTCOD,
            };

            using (DemoApplication app = new DemoApplication())
            {
                app.Start(appInfo);
            }
        }
    public static void CreateApplication()
    {
        // Create an offline connection, we use an empty Guid as personId
        // There is a bug to create a constructor without requiring a guid
        //// Use this only if you master application wants to do this in Offline mode
        OfflineWebApplicationConnection offlineConnection =
            new OfflineWebApplicationConnection(Guid.Empty);
        offlineConnection.Authenticate();

        // Setting up the application we want to create
        ApplicationInfo appInfo =
            new ApplicationInfo();
        appInfo.Name = "Android application";
        appInfo.AuthorizationReason =
            "Android aplication";
        appInfo.Description =
            "Just an android application";
        // get a base64 encoded logo
        appInfo.LargeLogo = new ApplicationBinaryConfiguration(
            "C:\\blah.png", "image/gif");
        // base64 encoded public key for this application
        appInfo.PublicKeys.Add(
            GetPublicKeyFromPfxOrP12("C:\\JourneyCompass.cer"));

        // You need to have PrivacyStatement + TermsOfUse or ActionUrl
        appInfo.PrivacyStatement = new ApplicationBinaryConfiguration(
        "C:\\privacy.txt", "text/plain");
        appInfo.TermsOfUse = new ApplicationBinaryConfiguration
            ("C:\\terms.txt", "text/plain");
        //actionUrl
        //appInfo.ActionUrl = new Uri("http://localhost/redirect.aspx");

        // Create and add the rules individually
        List<AuthorizationSetDefinition> rules = new List<AuthorizationSetDefinition>();
        rules.Add((AuthorizationSetDefinition)(new TypeIdSetDefinition(Height.TypeId)));
        rules.Add((AuthorizationSetDefinition)(new TypeIdSetDefinition(new Guid("a5033c9d-08cf-4204-9bd3-cb412ce39fc0"))));
        AuthorizationRule rule1 = new AuthorizationRule(
            HealthRecordItemPermissions.All,
            rules,
            null);
        // Here we are setting up the child as an offline application
        appInfo.OfflineBaseAuthorizations.Add(rule1);

        // Add more rules, if needed

        // Lets make the child app!
        Provisioner.AddApplication(offlineConnection, appInfo);
    }
        public Application(ApplicationInfo info)
        {
            nativeInterface = info.nativeInterface;
            width = info.width;
            height = info.height;
            realWidth = info.realWidth;
            realHeight = info.realHeight;

            sharedApplication = this;

            context = new Context();
            updatables = new UpdatableList(1);
            drawables = new DrawableList(1);

            cmdLine = CreateCommandLine();
            cmdLine.Parse(info.args);
        }
Exemplo n.º 18
0
        /// Setup() gets called immediately after Application.Start(), and we can override this to provide custom
        /// initialization code.
        /// 
        /// The first thing we need to do in this method, however, is call the base method - this
        /// initializes libtcod, opening the system window and setting the font, all according to the options provided in
        /// the ApplicationInfo parameter.
        /// 
        /// After calling the base method, we add our setup code, in this case creating the MyWindow (defined below) object 
        /// and setting it as the current Window.
        protected override void Setup(ApplicationInfo info)
        {
            /// One thing to note: in almost all cases, when overriding a framework method it is necessary
            /// to call the base method first.  The base methods handle most of the gritty details of triggering
            /// events, propagating messages, and calling the necessary stub methods.
            base.Setup(info);

            /// Just use the default options in the WindowTemplate.
            WindowTemplate mainWindowTemplate = new WindowTemplate();

            /// Create the mainWindow with the options specified in mainWindowInfo.  We define MyWindow below.
            MyWindow mainWindow = new MyWindow(mainWindowTemplate);

            /// Set the mainWindow to be MyApplication's window.  Note that if we don't set the application window,
            /// a default one is created and set automatically.
            SetWindow(mainWindow);
        }
Exemplo n.º 19
0
 internal NativeCommandProcessor(ApplicationInfo applicationInfo, ExecutionContext context) : base(applicationInfo)
 {
     this.sync = new object();
     if (applicationInfo == null)
     {
         throw PSTraceSource.NewArgumentNullException("applicationInfo");
     }
     this.applicationInfo = applicationInfo;
     base._context = context;
     base.Command = new NativeCommand();
     base.Command.CommandInfo = applicationInfo;
     base.Command.Context = context;
     base.Command.commandRuntime = base.commandRuntime = new MshCommandRuntime(context, applicationInfo, base.Command);
     base.CommandScope = context.EngineSessionState.CurrentScope;
     ((NativeCommand) base.Command).MyCommandProcessor = this;
     this.inputWriter = new ProcessInputWriter(base.Command);
 }
        public void CreateApplication(ApplicationInfo applicationInfo)
        {
            UseDataContext(dataContext =>
            {
                var appInfo = dataContext.Applications.FirstOrDefault(a => a.Name == applicationInfo.Name);
                if (appInfo != null)
                {
                    throw new ArgumentException(string.Format("Application '{0}' already exist.", applicationInfo.Name));
                }

                appInfo = new Application();
                appInfo.Name = applicationInfo.Name;
                appInfo.CreatedAt = applicationInfo.CreatedAt;

                dataContext.Applications.InsertOnSubmit(appInfo);
                dataContext.SubmitChanges();
            });
        }
Exemplo n.º 21
0
		// 从ini文件或者registry装载已经配置的所有主机事项
		public static ArrayList LoadHosts(ApplicationInfo appInfo)
		{
			ArrayList saResult = new ArrayList();

			for(int i=0; ;i++) 
			{
				string strEntry = "entry" + Convert.ToString(i+1);
					
				string strValue = appInfo.GetString("ServerAddress",
					strEntry,
					"");
				if (strValue == "")
					break;
				saResult.Add(strValue);
			}

			return saResult;
		}
Exemplo n.º 22
0
        protected override void Setup(ApplicationInfo info)
        {
            base.Setup(info);

            DemoWindowTemplate demoTmpl = new DemoWindowTemplate()
            {
                HasFrame = true,
                HasNext = true,
                HasPrevious = false
            };

            pages.Add(new Page1(demoTmpl));

            demoTmpl.HasNext = false;
            demoTmpl.HasPrevious = true;
            pages.Add(new Page2(demoTmpl));

            SetWindow(pages[0]);
        }
		public static ObservableCollection<ApplicationInfo> GenerateApplicationInfos()
		{
			ObservableCollection<ApplicationInfo> result = new ObservableCollection<ApplicationInfo>();

			ApplicationInfo info1 = new ApplicationInfo();
			info1.Name = "Large Collider";
			info1.Author = "C.E.R.N.";
			info1.IconPath = @"../Images/DragAndDrop/LargeIcons/Atom.png";
			result.Add(info1);

			ApplicationInfo info2 = new ApplicationInfo();
			info2.Name = "Paintbrush";
			info2.Author = "Imagine Inc.";
			info2.IconPath = @"../Images/DragAndDrop/LargeIcons/Brush.png";
			result.Add(info2);

			ApplicationInfo info3 = new ApplicationInfo();
			info3.Name = "Lively Calendar";
			info3.Author = "Control AG";
			info3.IconPath = @"../Images/DragAndDrop/LargeIcons/CalendarEvents.png";
			result.Add(info3);

			ApplicationInfo info4 = new ApplicationInfo();
			info4.Name = "Fire Burning ROM";
			info4.Author = "The CD Factory";
			info4.IconPath = @"../Images/DragAndDrop/LargeIcons/CDBurn.png";
			result.Add(info4);

			ApplicationInfo info5 = new ApplicationInfo();
			info5.Name = "Fav Explorer";
			info5.Author = "Star Factory";
			info5.IconPath = @"../Images/DragAndDrop/LargeIcons/favorites.png";
			result.Add(info5);

			ApplicationInfo info6 = new ApplicationInfo();
			info6.Name = "IE Fox";
			info6.Author = "Open Org";
			info6.IconPath = @"../Images/DragAndDrop/LargeIcons/Connected.png";
			result.Add(info6);

			return result;
		}
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            /// Creating an Application class is similar to creating windows and controls - first we need to define
            /// the options in an ApplicationInfo class.
            ///
            /// Here we give our application a title and a screen size.
            ApplicationInfo myApplicationInfo = new ApplicationInfo()
            {
                Title = "Sample1",
                ScreenSize = new Size(80,40)
            };

            /// And then create it.  Notice that the Application implements IDisposable, so placing this in a using...
            /// block ensures proper disposal of resources (including all of the IDispose objects carried over from
            /// libtcod).  Actually starting the application is as easy as calling the Start method and specifying
            /// a previously constructed ApplicationInfo object.
            using (MyApplication myApp = new MyApplication())
            {
                myApp.Start(myApplicationInfo);
            }
        }
Exemplo n.º 25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ApplicationParsedData"/> class.
 /// </summary>
 /// <param name="appInfo">The app info.</param>
 /// <param name="runtime">The runtime.</param>
 /// <param name="variables">The variables.</param>
 /// <param name="services">The services.</param>
 /// <param name="urls">The URLs.</param>
 /// <param name="logFilePath">The log file path.</param>
 /// <param name="errorLogFilePath">The error log file path.</param>
 /// <param name="startupLogFilePath">The startup log file path.</param>
 /// <param name="autoWireTemplates">A list of connection string templates for services.</param>
 public ApplicationParsedData(
     ApplicationInfo appInfo, 
     string runtime, 
     ApplicationVariable[] variables, 
     ApplicationService[] services,
     string[] urls,
     string logFilePath, 
     string errorLogFilePath, 
     string startupLogFilePath, 
     Dictionary<string, string> autoWireTemplates)
 {
     this.appInfo = appInfo;
     this.runtime = runtime;
     this.variables = variables;
     this.services = services;
     this.logFilePath = logFilePath;
     this.errorLogFilePath = errorLogFilePath;
     this.startupLogFilePath = startupLogFilePath;
     this.autoWireTemplates = autoWireTemplates;
     this.appUrls = urls;
 }
Exemplo n.º 26
0
        public static Environment CreateEnvironmentRequest()
        {
            ProductIdentity adapterProduct = new ProductIdentity { IconURI = "icon url 1", ProductName = "product name 1", ProductVersion = "3.4.1", VendorName = "Systemic" };
            ProductIdentity applicationProduct = new ProductIdentity { IconURI = "icon url 2", ProductName = "product name 2", ProductVersion = "9.80", VendorName = "Systemic" };
            Property zoneCharge = new Property { Name = "charge", Value = "Negative" };
            Property zoneMaster = new Property { Name = "master", Value = "Annihilus" };
            IDictionary<string, Property> zoneProperties =
                new Dictionary<string, Property> { { zoneCharge.Name, zoneCharge }, { zoneMaster.Name, zoneMaster } };
            Zone theNegativeZone = new Zone
            {
                Description = "The Negative Zone",
                Properties = zoneProperties
            };
            ApplicationInfo applicationInfo = new ApplicationInfo
            {
                AdapterProduct = adapterProduct,
                ApplicationKey = "UnitTesting",
                ApplicationProduct = applicationProduct,
                DataModelNamespace = "http://www.sifassociation.org/au/datamodel/1.4",
                SupportedInfrastructureVersion = "3.0",
                Transport = "REST"
            };
            Environment environmentRequest = new Environment
            {
                ApplicationInfo = applicationInfo,
                AuthenticationMethod = "Basic",
                ConsumerName = "UnitTestConsumer",
                DefaultZone = theNegativeZone,
                InstanceId = "ThisInstance01",
                SessionToken = "2e5dd3ca282fc8ddb3d08dcacc407e8a",
                SolutionId = "auTestSolution",
                Type = Model.Infrastructure.EnvironmentType.DIRECT,
                UserToken = "UserToken01"
            };

            return environmentRequest;
        }
Exemplo n.º 27
0
		// 从ini文件或者registry装载已经配置的所有主机事项
		public int InitialHostArray(ApplicationInfo appInfoParam)
		{
			int i, nMax;
			HostEntry entry = null;

			this.Clear();

			appinfo = appInfoParam;	// 保存下来备用

            if (appInfoParam == null)   // 2006/11/21
                return 0;

			ArrayList saHost = LoadHosts(appInfoParam);
			nMax = saHost.Count;
			for(i=0; i<nMax; i++) 
			{
				entry = new HostEntry();
				entry.m_strHostName = (string)saHost[i];
				this.Add(entry);
				entry.Container = this;
			}

			return 0;
		}
Exemplo n.º 28
0
 public override void SetRef(ApplicationInfo applicationInfo, ServiceInfo databaseInfo, OperationInfo table)
 {
     EnumerationInfo = applicationInfo.Enumerations.GetByName(EnumerationName);
 }
        /// <summary>表单内容界面</summary>
        /// <returns></returns>
        public ActionResult Form(string options)
        {
            JsonData request = JsonMapper.ToObject(options == null ? "{}" : options);

            string applicationName = JsonHelper.GetDataValue(request, "applicationName", ConnectConfiguration.ApplicationName);

            // 所属应用信息
            ApplicationInfo application = ViewBag.application = AppsContext.Instance.ApplicationService[applicationName];

            // 管理员身份标记
            bool isAdminToken = ViewBag.isAdminToken = AppsSecurity.IsAdministrator(this.Account, application.ApplicationName);

            // -------------------------------------------------------
            // 业务数据处理
            // -------------------------------------------------------

            // 实体数据标识
            string id = !request.Keys.Contains("id") ? string.Empty : request["id"].ToString();
            // 文档编辑模式
            DocEditMode docEditMode = DocEditMode.Unkown;
            // 实体数据信息
            ConnectInfo param = null;

            if (string.IsNullOrEmpty(id))
            {
                param = new ConnectInfo();

                param.Id        = param.AppKey = DigitalNumberContext.Generate("Key_Guid");
                param.AppSecret = Guid.NewGuid().ToString().Substring(0, 8);

                param.IsInternal = false;

                // 设置编辑模式【新建】
                docEditMode = DocEditMode.New;
            }
            else
            {
                param = ConnectContext.Instance.ConnectService.FindOne(id);

                if (param == null)
                {
                    ApplicationError.Write(404);
                }

                // 设置编辑模式【编辑】
                docEditMode = DocEditMode.Edit;
            }

            // -------------------------------------------------------
            // 数据加载
            // -------------------------------------------------------

            ViewBag.Title = string.Format("{0}-{1}-{2}", (string.IsNullOrEmpty(param.Name) ? "新应用" : param.Name), application.ApplicationDisplayName, this.SystemName);

            // 加载当前业务实体数据
            ViewBag.entityClassName = KernelContext.ParseObjectType(param.GetType());
            // 加载当前业务实体数据
            ViewBag.param = param;
            // 加载当前文档编辑模式
            ViewBag.docEditMode = docEditMode;

            // 视图
            return(View("/views/main/connect/connect-form.cshtml"));
        }
Exemplo n.º 30
0
        /// <summary>
        /// Autowires the service connections and ASP.NET health monitoring in the application's web.config
        /// </summary>
        /// <param name="appInfo">The application info structure.</param>
        /// <param name="variables">All application variables.</param>
        /// <param name="services">The services.</param>
        /// <param name="logFilePath">The ASP.NET "Heartbeat" and "Lifetime Events" log file path.</param>
        /// <param name="errorLogFilePath">The ASP.NET "All Errors" events log file path.</param>
        private void AutowireApp(ApplicationInfo appInfo, ApplicationVariable[] variables, ApplicationService[] services, string logFilePath, string errorLogFilePath)
        {
            this.startupLogger.Info(Strings.StartingApplicationAutoWiring);

            // get all config files
            string[] allConfigFiles = Directory.GetFiles(appInfo.Path, "*.config", SearchOption.AllDirectories);

            foreach (string configFile in allConfigFiles)
            {
                if (File.Exists(configFile))
                {
                    string configFileContents = File.ReadAllText(configFile);

                    if (services != null)
                    {
                        Dictionary <string, string> connections = new Dictionary <string, string>();
                        Dictionary <string, string> connValues  = new Dictionary <string, string>();

                        foreach (ApplicationService service in services)
                        {
                            string key      = service.ServiceLabel;
                            string template = string.Empty;

                            if (this.autoWireTemplates.TryGetValue(key, out template))
                            {
                                template = template.Replace(Strings.Host, service.Host);
                                template = template.Replace(Strings.Port, service.Port.ToString(CultureInfo.InvariantCulture));
                                template = template.Replace(Strings.Name, service.InstanceName);
                                template = template.Replace(Strings.User, service.User);
                                template = template.Replace(Strings.Password, service.Password);

                                connections[string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", key, service.Name)] = template;
                            }

                            char[] charsToTrim = { '{', '}' };
                            connValues.Add(string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", service.Name, Strings.User.Trim(charsToTrim)), service.User);
                            connValues.Add(string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", service.Name, Strings.Host.Trim(charsToTrim)), service.Host);
                            connValues.Add(string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", service.Name, Strings.Port.Trim(charsToTrim)), service.Port.ToString(CultureInfo.InvariantCulture));
                            connValues.Add(string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", service.Name, Strings.Password.Trim(charsToTrim)), service.Password);
                            connValues.Add(string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", service.Name, Strings.Name.Trim(charsToTrim)), service.InstanceName);
                        }

                        foreach (string con in connections.Keys)
                        {
                            this.startupLogger.Info(Strings.ConfiguringService + con);
                            configFileContents = configFileContents.Replace(con, connections[con]);
                        }

                        foreach (string key in connValues.Keys)
                        {
                            this.startupLogger.Info(string.Format(CultureInfo.InvariantCulture, Strings.ConfiguringServiceValue, key));
                            configFileContents = configFileContents.Replace(key, connValues[key]);
                        }
                    }

                    File.WriteAllText(configFile, configFileContents);
                }
            }

            string webConfigFile = Path.Combine(appInfo.Path, "web.config");

            if (File.Exists(webConfigFile))
            {
                this.SetApplicationVariables(webConfigFile, variables, logFilePath, errorLogFilePath);

                this.startupLogger.Info(Strings.SavedConfigurationFile);

                this.startupLogger.Info(Strings.SettingUpLogging);

                string appDir                  = Path.GetDirectoryName(webConfigFile);
                string binDir                  = Path.Combine(appDir, "bin");
                string assemblyFile            = typeof(LogFileWebEventProvider).Assembly.Location;
                string destinationAssemblyFile = Path.Combine(binDir, Path.GetFileName(assemblyFile));

                Directory.CreateDirectory(binDir);

                File.Copy(assemblyFile, destinationAssemblyFile, true);

                this.startupLogger.Info(Strings.CopiedLoggingBinariesToBin);

                SiteConfig      siteConfiguration = new SiteConfig(appDir, true);
                HealthMonRewire healthMon         = new HealthMonRewire();
                healthMon.Register(siteConfiguration);

                siteConfiguration.Rewire(false);
                siteConfiguration.CommitChanges();

                this.startupLogger.Info(Strings.UpdatedLoggingConfiguration);

                DirectoryInfo errorLogDir = new DirectoryInfo(Path.GetDirectoryName(errorLogFilePath));
                DirectoryInfo logDir      = new DirectoryInfo(Path.GetDirectoryName(logFilePath));

                DirectorySecurity errorLogDirSecurity = errorLogDir.GetAccessControl();
                DirectorySecurity logDirSecurity      = logDir.GetAccessControl();

                errorLogDirSecurity.SetAccessRule(
                    new FileSystemAccessRule(
                        appInfo.WindowsUserName,
                        FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify | FileSystemRights.CreateFiles,
                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                        PropagationFlags.None,
                        AccessControlType.Allow));

                logDirSecurity.SetAccessRule(
                    new FileSystemAccessRule(
                        appInfo.WindowsUserName,
                        FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify | FileSystemRights.CreateFiles,
                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                        PropagationFlags.None,
                        AccessControlType.Allow));

                errorLogDir.SetAccessControl(errorLogDirSecurity);
                logDir.SetAccessControl(logDirSecurity);
            }
        }
Exemplo n.º 31
0
        private async Task MonitorAppAsync(ApplicationInfo application)
        {
            List <ReplicaOrInstanceMonitoringInfo> repOrInstList;

            if (this.IsTestRun)
            {
                repOrInstList = this.ReplicaOrInstanceList;
            }
            else
            {
                if (!string.IsNullOrEmpty(application.TargetAppType))
                {
                    repOrInstList = await this
                                    .GetDeployedApplicationReplicaOrInstanceListAsync(null, application.TargetAppType)
                                    .ConfigureAwait(true);
                }
                else
                {
                    repOrInstList = await this
                                    .GetDeployedApplicationReplicaOrInstanceListAsync(new Uri(application.TargetApp))
                                    .ConfigureAwait(true);
                }

                if (repOrInstList.Count == 0)
                {
                    this.ObserverLogger.LogInfo("No targetApp or targetAppType specified.");
                    return;
                }
            }

            Process currentProcess = null;

            foreach (var repOrInst in repOrInstList)
            {
                this.Token.ThrowIfCancellationRequested();

                var timer     = new Stopwatch();
                int processId = (int)repOrInst.HostProcessId;
                var cpuUsage  = new CpuUsage();

                try
                {
                    // App level.
                    currentProcess = Process.GetProcessById(processId);

                    this.Token.ThrowIfCancellationRequested();

                    var    procName      = currentProcess.ProcessName;
                    string appNameOrType = GetAppNameOrType(repOrInst);

                    var id = $"{appNameOrType}:{procName}";

                    // Add new resource data structures for each app service process.
                    if (this.allAppCpuData.All(list => list.Id != id))
                    {
                        this.allAppCpuData.Add(new FabricResourceUsageData <int>(ErrorWarningProperty.TotalCpuTime, id, this.DataCapacity, this.UseCircularBuffer));
                        this.allAppMemDataMb.Add(new FabricResourceUsageData <float>(ErrorWarningProperty.TotalMemoryConsumptionMb, id, this.DataCapacity, this.UseCircularBuffer));
                        this.allAppMemDataPercent.Add(new FabricResourceUsageData <double>(ErrorWarningProperty.TotalMemoryConsumptionPct, id, this.DataCapacity, this.UseCircularBuffer));
                        this.allAppTotalActivePortsData.Add(new FabricResourceUsageData <int>(ErrorWarningProperty.TotalActivePorts, id, 1));
                        this.allAppEphemeralPortsData.Add(new FabricResourceUsageData <int>(ErrorWarningProperty.TotalEphemeralPorts, id, 1));
                    }

                    TimeSpan duration = TimeSpan.FromSeconds(15);

                    if (this.MonitorDuration > TimeSpan.MinValue)
                    {
                        duration = this.MonitorDuration;
                    }

                    // Warm up the counters.
                    _ = cpuUsage.GetCpuUsageProcess(currentProcess);
                    _ = this.perfCounters.PerfCounterGetProcessPrivateWorkingSetMb(currentProcess.ProcessName);

                    timer.Start();

                    while (!currentProcess.HasExited && timer.Elapsed <= duration)
                    {
                        this.Token.ThrowIfCancellationRequested();

                        // CPU (all cores).
                        int cpu = cpuUsage.GetCpuUsageProcess(currentProcess);

                        if (cpu >= 0)
                        {
                            this.allAppCpuData.FirstOrDefault(x => x.Id == id).Data.Add(cpu);
                        }

                        // Memory (private working set (process)).
                        var processMem = this.perfCounters.PerfCounterGetProcessPrivateWorkingSetMb(currentProcess.ProcessName);
                        this.allAppMemDataMb.FirstOrDefault(x => x.Id == id).Data.Add(processMem);

                        // Memory (percent in use (total)).
                        var  memInfo  = ObserverManager.TupleGetTotalPhysicalMemorySizeAndPercentInUse();
                        long totalMem = memInfo.TotalMemory;

                        if (totalMem > -1)
                        {
                            double usedPct = Math.Round(((double)(processMem * 100)) / (totalMem * 1024), 2);
                            this.allAppMemDataPercent.FirstOrDefault(x => x.Id == id).Data.Add(Math.Round(usedPct, 1));
                        }

                        Thread.Sleep(250);
                    }

                    timer.Stop();
                    timer.Reset();

                    // Total and Ephemeral ports..
                    this.allAppTotalActivePortsData.FirstOrDefault(x => x.Id == id)
                    .Data.Add(NetworkUsage.GetActivePortCount(currentProcess.Id));

                    this.allAppEphemeralPortsData.FirstOrDefault(x => x.Id == id)
                    .Data.Add(NetworkUsage.GetActiveEphemeralPortCount(currentProcess.Id));
                }
                catch (Exception e)
                {
                    if (e is Win32Exception || e is ArgumentException || e is InvalidOperationException)
                    {
                        this.WriteToLogWithLevel(
                            this.ObserverName,
                            $"MonitorAsync failed to find current service process for {application.TargetApp}/n{e}",
                            LogLevel.Information);
                    }
                    else
                    {
                        if (!(e is OperationCanceledException))
                        {
                            this.WriteToLogWithLevel(
                                this.ObserverName,
                                $"Unhandled exception in MonitorAsync: \n {e}",
                                LogLevel.Warning);
                        }

                        throw;
                    }
                }
                finally
                {
                    currentProcess?.Dispose();
                    currentProcess = null;
                }
            }
        }
Exemplo n.º 32
0
        public void TestSerialization()
        {
            SettingsStore store = SettingsStore.Default;

            SettingsStore.Default = new SettingsStore();

            ExportInfo info = new ExportInfo();

            info.AfterExportEvent = AfterExportEvent.OpenInApplication;

            ApplicationInfo appInfo = new ApplicationInfo();

            appInfo.CommandLine      = "admin";
            appInfo.Id               = Guid.NewGuid();
            appInfo.Name             = "MyApplication";
            appInfo.Path             = "c:\\MyApplication.exe";
            info.ApplicationIdString = appInfo.IdString;
            info.CreateSubFolder     = true;
            info.DontEnlarge         = true;
            info.Dpi = 300;
            info.ExistingFileMode = ExistingFileMode.OverrideWithoutPrompt;

            FileRenameValueProperty prop   = (FileRenameValueProperty)FileRenameManager.Default.GetFileRenameValue("Caption");
            FileRenameValueCustom   custom = (FileRenameValueCustom)FileRenameManager.Default.GetFileRenameValue("CustomText");
            FileRenameValueIndex    index  = (FileRenameValueIndex)FileRenameManager.Default.GetFileRenameValue("Index");
            FileRenameValueCount    count  = (FileRenameValueCount)FileRenameManager.Default.GetFileRenameValue("Count");

            index.StartIndex = 99;

            FileRenameValueReference       propRef    = prop.CreateReference();
            FileRenameValueReferenceString propCustom = (FileRenameValueReferenceString)custom.CreateReference();
            FileRenameValueReference       propIndex  = index.CreateReference();
            FileRenameValueReference       propCount  = count.CreateReference();

            Assert.AreEqual("Caption", propRef.FileRenameValueName);
            Assert.AreEqual("CustomText", propCustom.FileRenameValueName);
            Assert.AreEqual("Index", propIndex.FileRenameValueName);
            Assert.AreEqual("Count", propCount.FileRenameValueName);

            propCustom.Text = "My Custom String";

            info.FileRenameValues.Add(propRef);
            info.FileRenameValues.Add(propCustom);
            info.FileRenameValues.Add(propIndex);
            info.FileRenameValues.Add(propCount);

            info.Folder                         = "c:\\MyFolder\\";
            info.Height                         = 1200;
            info.LongSide                       = 1300;
            info.Name                           = "MyExportInfo";
            info.RenameFiles                    = true;
            info.RenameMask                     = "[Index] - [Caption].[Extension]";
            info.ResizeImages                   = true;
            info.ResizeMode                     = FileResizeMode.ZoomInside;
            info.ResolutionMode                 = ResolutionMode.PixelsPerCm;
            info.ImageDimension                 = ImageDimensionMode.Inches;
            info.ShortSide                      = 1400;
            info.ShowWatermark                  = true;
            info.SubFolder                      = "SubFolder";
            info.Watermark.FontColor            = System.Windows.Media.Colors.Red;
            info.Watermark.FontFamily           = new System.Windows.Media.FontFamily("Arial");
            info.Watermark.FontFamilyName       = "Arial";
            info.Watermark.FontSize             = 13;
            info.Watermark.FontStyle            = System.Windows.FontStyles.Italic;
            info.Watermark.FontStyleName        = "Italic";
            info.Watermark.FontWeight           = System.Windows.FontWeights.Bold;
            info.Watermark.FontWeightName       = "Bold";
            info.Watermark.ImageToTextAlignment = WatermarkImageToTextAlign.Right;
            info.Watermark.ImageUri             = "c:\\Images\\image.png";
            info.Watermark.Layout               = WatermarkLayout.FillPhoto;
            info.Watermark.Opacity              = 0.25;
            info.Watermark.RotateAngle          = 75;
            info.Watermark.ShowWatermark        = true;
            info.Watermark.Text                 = "Hello World";
            info.Watermark.WatermarkIndent      = 5;
            info.Width                          = 1100;
            info.ImageFormat                    = ExportImageFormat.PNG;
            info.CompressionLevel               = 95;
            info.IsLimitFileSize                = true;
            info.LimitFileSize                  = 222;
            info.PngBitsPerChannel              = 16;
            info.Application.Name               = "AppName";
            info.Application.Path               = "AppPath";
            info.Application.CommandLine        = "AppLine";
            info.ApplicationIdString            = Guid.NewGuid().ToString();

            SettingsStore.Default.ExportPresets.Add(info);
            SettingsStore.Default.SaveToXml();
            SettingsStore.Default.ExportPresets.Clear();
            SettingsStore.Default.RestoreFromXml();

            ExportInfo info2 = SettingsStore.Default.ExportPresets[0];

            Assert.AreEqual(info2.AfterExportEvent, info.AfterExportEvent);
            Assert.AreEqual(info2.ApplicationIdString, info.ApplicationIdString);
            Assert.AreEqual(info2.CreateSubFolder, info.CreateSubFolder);
            Assert.AreEqual(info2.DontEnlarge, info.DontEnlarge);
            Assert.AreEqual(info2.Dpi, info.Dpi);
            Assert.AreEqual(info2.ExistingFileMode, info.ExistingFileMode);

            for (int i = 0; i < info.FileRenameValues.Count; i++)
            {
                Assert.AreEqual(info.FileRenameValues[i].GetType(), info2.FileRenameValues[i].GetType());
                Assert.AreEqual(info.FileRenameValues[i].FileRenameValue.GetType(), info2.FileRenameValues[i].FileRenameValue.GetType());
            }

            Assert.AreEqual(info2.Folder, info.Folder);
            Assert.AreEqual(info2.Height, info.Height);
            Assert.AreEqual(info2.LongSide, info.LongSide);
            Assert.AreEqual(info2.Name, info.Name);
            Assert.AreEqual(info2.RenameFiles, info.RenameFiles);
            Assert.AreEqual(info2.RenameMask, info.RenameMask);
            Assert.AreEqual(info2.ResizeImages, info.ResizeImages);
            Assert.AreEqual(info2.ResizeMode, info.ResizeMode);
            Assert.AreEqual(info2.ResolutionMode, info.ResolutionMode);
            Assert.AreEqual(info2.ImageDimension, info.ImageDimension);
            Assert.AreEqual(info2.ShortSide, info.ShortSide);
            Assert.AreEqual(info2.ShowWatermark, info.ShowWatermark);
            Assert.AreEqual(info2.SubFolder, info.SubFolder);
            Assert.AreEqual(info2.Watermark.FontColor, info.Watermark.FontColor);
            Assert.AreEqual(info2.Watermark.FontFamily, info.Watermark.FontFamily);
            Assert.AreEqual(info2.Watermark.FontSize, info.Watermark.FontSize);
            Assert.AreEqual(info2.Watermark.FontStyle, info.Watermark.FontStyle);
            Assert.AreEqual(info2.Watermark.FontWeight, info.Watermark.FontWeight);
            Assert.AreEqual(info2.Watermark.ImageToTextAlignment, info.Watermark.ImageToTextAlignment);
            Assert.AreEqual(info2.Watermark.ImageUri, info.Watermark.ImageUri);
            Assert.AreEqual(info2.Watermark.Layout, info.Watermark.Layout);
            Assert.AreEqual(info2.Watermark.Opacity, info.Watermark.Opacity);
            Assert.AreEqual(info2.Watermark.RotateAngle, info.Watermark.RotateAngle);
            Assert.AreEqual(info2.Watermark.ShowWatermark, info.Watermark.ShowWatermark);
            Assert.AreEqual(info2.Watermark.Text, info.Watermark.Text);
            Assert.AreEqual(info2.Width, info.Width);
            Assert.AreEqual(info2.Watermark.WatermarkIndent, info.Watermark.WatermarkIndent);
            Assert.AreEqual(info2.ImageFormat, info.ImageFormat);
            Assert.AreEqual(info2.CompressionLevel, info.CompressionLevel);
            Assert.AreEqual(info2.IsLimitFileSize, info.IsLimitFileSize);
            Assert.AreEqual(info2.LimitFileSize, info.LimitFileSize);
            Assert.AreEqual(info2.PngBitsPerChannel, info.PngBitsPerChannel);
            Assert.AreEqual(info2.ApplicationIdString, info.ApplicationIdString);
            Assert.AreEqual(info2.Application.Name, info.Application.Name);
            Assert.AreEqual(info2.Application.Path, info.Application.Path);
            Assert.AreEqual(info2.Application.CommandLine, info.Application.CommandLine);
        }
Exemplo n.º 33
0
        /// <summary>
        /// Gets the cpu target for the application.
        /// </summary>
        /// <param name="appInfo">The application info structure.</param>
        /// <returns>CPU target</returns>
        private CpuTarget GetCpuTarget(ApplicationInfo appInfo)
        {
            this.startupLogger.Info(Strings.DetectingCpuTarget);

            string[] allAssemblies = Directory.GetFiles(appInfo.Path, "*.dll", SearchOption.AllDirectories);

            CpuTarget target = CpuTarget.X64;

            foreach (string assembly in allAssemblies)
            {
                target = PlatformTarget.DetectPlatform(assembly);
                if (target == CpuTarget.X86)
                {
                    break;
                }
            }

            this.startupLogger.Info(Strings.DetectedCpuTarget, target.ToString());

            return target;
        }
 public AuthDelegateImplementation(ApplicationInfo appInfo)
 {
     this.appInfo = appInfo;
 }
Exemplo n.º 35
0
 /// <summary>
 /// 设置服务端项目属性
 /// </summary>
 /// <param name="appInfo"></param>
 /// <returns></returns>
 public bool SetApplicationInfo(ApplicationInfo appInfo)
 {
     return(channel.SetApplicationInfo(appInfo));
 }
Exemplo n.º 36
0
 public EnumerationDossier(ApplicationMold mold, ApplicationInfo info)
     : base(info)
 {
     ApplicationMold = mold;
 }
Exemplo n.º 37
0
        private void AutowireUhurufs(ApplicationInfo appInfo, ApplicationVariable[] variables, ApplicationService[] services, string homeAppPath)
        {
            this.startupLogger.Info(Strings.StartingApplicationAutoWiring);

            Dictionary <string, HashSet <string> > persistentFiles = new Dictionary <string, HashSet <string> >();

            foreach (ApplicationVariable var in variables)
            {
                if (var.Name.StartsWith("uhurufs_", StringComparison.Ordinal))
                {
                    string serviceName = var.Name.Split(new string[] { "uhurufs_" }, 2, StringSplitOptions.RemoveEmptyEntries)[0];
                    if (!persistentFiles.ContainsKey(serviceName))
                    {
                        persistentFiles[serviceName] = new HashSet <string>();
                    }

                    string[] persistedItems = var.Value.Trim(new char[] { '"' }).Split(new char[] { ';', ',', ':' });

                    foreach (string item in persistedItems)
                    {
                        persistentFiles[serviceName].Add(item.Replace('/', '\\'));
                    }
                }
            }

            foreach (ApplicationService serv in services)
            {
                if (serv.ServiceLabel.StartsWith("uhurufs", StringComparison.Ordinal))
                {
                    string shareHost = GenerateUhurufsHost(appInfo.InstanceId, serv.InstanceName, serv.User);

                    try
                    {
                        if (!SystemHosts.Exists(shareHost))
                        {
                            // Note: delete the host after the app is deleted
                            SystemHosts.Add(shareHost, serv.Host);
                        }
                    }
                    catch (ArgumentException)
                    {
                        // If the service host cannot be added to hosts connect
                        shareHost = serv.Host;
                    }

                    string remotePath = string.Format(CultureInfo.InvariantCulture, @"\\{0}\{1}", shareHost, serv.InstanceName);
                    string mountPath  = GenerateMountPath(homeAppPath, serv.Name);
                    Directory.CreateDirectory(Path.Combine(mountPath, @".."));

                    // Add the share users credentials to the application user.
                    // This way the application can use the share directly without invoking `net use` with the credentials.
                    using (new UserImpersonator(appInfo.WindowsUserName, ".", appInfo.WindowsPassword, true))
                    {
                        SaveCredentials.AddDomainUserCredential(shareHost, serv.User, serv.Password);
                    }

                    // The impersonated user cannot create links
                    // Note: unmount the share after the app is deleted
                    SambaWindowsClient.Mount(remotePath, serv.User, serv.Password);
                    SambaWindowsClient.LinkDirectory(remotePath, mountPath);

                    if (persistentFiles.ContainsKey(serv.Name))
                    {
                        foreach (string fileSystemItem in persistentFiles[serv.Name])
                        {
                            try
                            {
                                this.PersistFileSystemItem(appInfo.Path, fileSystemItem, Path.Combine(mountPath, appInfo.Name));
                            }
                            catch (Exception ex)
                            {
                                this.startupLogger.Error("Failed linking file/directory: {0}. Exception: {1}", fileSystemItem, ex.ToString());
                            }
                        }
                    }
                }
            }
        }
        public void Active()
        {
            IPEndPoint ipPoint      = new IPEndPoint(IPAddress.Parse(IPAddres), Port);
            Socket     listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            listenSocket.Bind(ipPoint);
            listenSocket.Listen(10);
            Console.WriteLine("Сервер запущен");
            while (true)
            {
                Socket        handler = listenSocket.Accept();
                StringBuilder builder = new StringBuilder();
                int           bytes   = 0;
                byte[]        data    = new byte[256];
                do
                {
                    bytes = handler.Receive(data);
                    builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                }while (handler.Available > 0);
                string sql = builder.ToString();
                JavaScriptSerializer serializer1 = new JavaScriptSerializer();
                serializer1.MaxJsonLength = int.MaxValue;
                CommandSQL commandSQL = serializer1.Deserialize <CommandSQL>(sql);
                string[]   parsingSQL = commandSQL.CommandText.Split(' ');
                string     command    = "";
                string     table      = "";
                if (parsingSQL[0] == "SELECT")
                {
                    command = parsingSQL[0];
                    table   = parsingSQL[3];
                }
                else
                {
                    if (parsingSQL[0] == "INSERT")
                    {
                        command = parsingSQL[0];
                        table   = parsingSQL[2];
                    }
                    else
                    {
                        command = parsingSQL[0];
                        table   = parsingSQL[1];
                    }
                }
                switch (command)
                {
                case "SELECT":
                    switch (table)
                    {
                        #region Applications
                    case "Applications":
                        string       resultApplications = "";
                        Applications applications       = new Applications();
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandApplications = new SQLiteCommand();
                        commandApplications.CommandText = commandSQL.CommandText;
                        string[] paramApplications = commandSQL.Parameters.Split('$');
                        for (int i = 1; i < paramApplications.Length; i += 2)
                        {
                            commandApplications.Parameters.AddWithValue(paramApplications[i], paramApplications[i + 1]);
                        }
                        DataRow[] datarowsApp = mydb.Select(commandApplications);
                        foreach (DataRow row in datarowsApp)
                        {
                            applications.ApplicationName = row[0].ToString();
                            JavaScriptSerializer serializer = new JavaScriptSerializer();
                            serializer.MaxJsonLength = int.MaxValue;
                            string json = serializer.Serialize(applications);
                            resultApplications += "$" + json;
                        }
                        data = Encoding.Unicode.GetBytes(resultApplications);
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;

                        #endregion
                        #region ApplicationInfo
                    case "ApplicationInfo":
                        string          resultApplicationInfo = "";
                        ApplicationInfo applicationInfo       = new ApplicationInfo();
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandApplicationInfo = new SQLiteCommand();
                        commandApplicationInfo.CommandText = commandSQL.CommandText;
                        string[] paramApplicationInfo = commandSQL.Parameters.Split('$');
                        for (int i = 1; i < paramApplicationInfo.Length; i += 2)
                        {
                            commandApplicationInfo.Parameters.AddWithValue(paramApplicationInfo[i], paramApplicationInfo[i + 1]);
                        }
                        DataRow[] datarowsApplicationInfo = mydb.Select(commandApplicationInfo);
                        foreach (DataRow row in datarowsApplicationInfo)
                        {
                            applicationInfo.Application    = row[0].ToString();
                            applicationInfo.AppVersion     = row[1].ToString();
                            applicationInfo.AppDiscription = row[2].ToString();
                            applicationInfo.Flag           = row[3].ToString();
                            applicationInfo.Name_EXE       = row[4].ToString();
                            JavaScriptSerializer serializer = new JavaScriptSerializer();
                            serializer.MaxJsonLength = int.MaxValue;
                            string json = serializer.Serialize(applicationInfo);
                            resultApplicationInfo += "$" + json;
                        }
                        data = Encoding.Unicode.GetBytes(resultApplicationInfo);
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;

                        #endregion
                        #region FilesContains
                    case "FilesContains":
                        string        resultFilesContains = "";
                        FilesContains filesContains       = new FilesContains();
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandFilesContains = new SQLiteCommand();
                        commandFilesContains.CommandText = commandSQL.CommandText;
                        string[] paramFilesContains = null;
                        if (commandSQL.Parameters != null)
                        {
                            paramFilesContains = commandSQL.Parameters.Split('$');
                            for (int i = 1; i < paramFilesContains.Length; i += 2)
                            {
                                commandFilesContains.Parameters.AddWithValue(paramFilesContains[i], paramFilesContains[i + 1]);
                            }
                        }
                        DataRow[] datarowsFilesContains = mydb.Select(commandFilesContains);
                        foreach (DataRow row in datarowsFilesContains)
                        {
                            filesContains.Applications = row[0].ToString();
                            filesContains.AppVersions  = row[1].ToString();
                            filesContains.FilePath     = row[2].ToString();
                            filesContains.DateCreateDB = row[3].ToString();
                            filesContains.Contains     = row[4].ToString();
                            JavaScriptSerializer serializer = new JavaScriptSerializer();
                            serializer.MaxJsonLength = int.MaxValue;
                            string json = serializer.Serialize(filesContains);
                            resultFilesContains += "$" + json;
                        }
                        data = Encoding.Unicode.GetBytes(resultFilesContains);
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;

                        #endregion
                        #region FilesVersions
                    case "FilesVersions":
                        string        resultFilesVersions = "";
                        FilesVersions filesVersions       = new FilesVersions();
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandFilesVersions = new SQLiteCommand();
                        commandFilesVersions.CommandText = commandSQL.CommandText;
                        if (commandSQL.Parameters != null)
                        {
                            string[] paramFilesVersions = commandSQL.Parameters.Split('$');
                            for (int i = 1; i < paramFilesVersions.Length; i += 2)
                            {
                                commandFilesVersions.Parameters.AddWithValue(paramFilesVersions[i], paramFilesVersions[i + 1]);
                            }
                        }
                        DataRow[] datarowsFilesVersions = mydb.Select(commandFilesVersions);
                        foreach (DataRow row in datarowsFilesVersions)
                        {
                            filesVersions.AppVersions  = row[0].ToString();
                            filesVersions.FileHash     = row[1].ToString();
                            filesVersions.CreationDate = row[2].ToString();
                            filesVersions.FileSize     = Convert.ToInt32(row[3].ToString());
                            filesVersions.FilePath     = row[4].ToString();
                            filesVersions.DateCreateDB = row[5].ToString();
                            filesVersions.Applications = row[6].ToString();
                            JavaScriptSerializer serializer = new JavaScriptSerializer();
                            serializer.MaxJsonLength = int.MaxValue;
                            string json = serializer.Serialize(filesVersions);
                            resultFilesVersions += "$" + json;
                        }
                        data = Encoding.Unicode.GetBytes(resultFilesVersions);
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;
                        #endregion
                    }
                    break;

                case "INSERT":
                    switch (table)
                    {
                        #region Applications
                    case "Applications":
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandApplications = new SQLiteCommand();
                        commandApplications.CommandText = commandSQL.CommandText;
                        string[] paramApplications = commandSQL.Parameters.Split('$');
                        for (int i = 1; i < paramApplications.Length; i += 2)
                        {
                            commandApplications.Parameters.AddWithValue(paramApplications[i], paramApplications[i + 1]);
                        }
                        mydb.Insert(commandApplications);
                        data = Encoding.Unicode.GetBytes("True");
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;

                        #endregion
                        #region ApplicationInfo
                    case "ApplicationInfo":
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandApplicationInfo = new SQLiteCommand();
                        commandApplicationInfo.CommandText = commandSQL.CommandText;
                        string[] paramApplicationInfo = commandSQL.Parameters.Split('$');
                        for (int i = 1; i < paramApplicationInfo.Length; i += 2)
                        {
                            commandApplicationInfo.Parameters.AddWithValue(paramApplicationInfo[i], paramApplicationInfo[i + 1]);
                        }
                        mydb.Insert(commandApplicationInfo);
                        data = Encoding.Unicode.GetBytes("True");
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;

                        #endregion
                        #region FilesContains
                    case "FilesContains":
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandFilesContains = new SQLiteCommand();
                        commandFilesContains.CommandText = commandSQL.CommandText;
                        string[] paramFilesContains = commandSQL.Parameters.Split('$');
                        for (int i = 1; i < paramFilesContains.Length; i += 2)
                        {
                            commandFilesContains.Parameters.AddWithValue(paramFilesContains[i], paramFilesContains[i + 1]);
                        }
                        mydb.Insert(commandFilesContains);
                        data = Encoding.Unicode.GetBytes("True");
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;

                        #endregion
                        #region FilesVersions
                    case "FilesVersions":
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandFilesVersions = new SQLiteCommand();
                        commandFilesVersions.CommandText = commandSQL.CommandText;
                        string[] paramFilesVersions = commandSQL.Parameters.Split('$');
                        for (int i = 1; i < paramFilesVersions.Length; i += 2)
                        {
                            commandFilesVersions.Parameters.AddWithValue(paramFilesVersions[i], paramFilesVersions[i + 1]);
                        }
                        mydb.Insert(commandFilesVersions);
                        data = Encoding.Unicode.GetBytes("True");
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;
                        #endregion
                    }
                    break;

                case "Update":
                    switch (table)
                    {
                        #region Applications
                    case "Applications":
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandApplications = new SQLiteCommand();
                        commandApplications.CommandText = commandSQL.CommandText;
                        string[] paramApplications = commandSQL.Parameters.Split('$');
                        for (int i = 1; i < paramApplications.Length; i += 2)
                        {
                            commandApplications.Parameters.AddWithValue(paramApplications[i], paramApplications[i + 1]);
                        }
                        mydb.Insert(commandApplications);
                        data = Encoding.Unicode.GetBytes("True");
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;

                        #endregion
                        #region ApplicationInfo
                    case "ApplicationInfo":
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandApplicationInfo = new SQLiteCommand();
                        commandApplicationInfo.CommandText = commandSQL.CommandText;
                        string[] paramApplicationInfo = commandSQL.Parameters.Split('$');
                        for (int i = 1; i < paramApplicationInfo.Length; i += 2)
                        {
                            commandApplicationInfo.Parameters.AddWithValue(paramApplicationInfo[i], paramApplicationInfo[i + 1]);
                        }
                        mydb.Insert(commandApplicationInfo);
                        data = Encoding.Unicode.GetBytes("True");
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;

                        #endregion
                        #region FilesContains
                    case "FilesContains":
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandFilesContains = new SQLiteCommand();
                        commandFilesContains.CommandText = commandSQL.CommandText;
                        string[] paramFilesContains = commandSQL.Parameters.Split('$');
                        for (int i = 1; i < paramFilesContains.Length; i += 2)
                        {
                            commandFilesContains.Parameters.AddWithValue(paramFilesContains[i], paramFilesContains[i + 1]);
                        }
                        mydb.Insert(commandFilesContains);
                        data = Encoding.Unicode.GetBytes("True");
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;

                        #endregion
                        #region FilesVersions
                    case "FilesVersions":
                        mydb = new SQLite(AppDomain.CurrentDomain.BaseDirectory);
                        SQLiteCommand commandFilesVersions = new SQLiteCommand();
                        commandFilesVersions.CommandText = commandSQL.CommandText;
                        string[] paramFilesVersions = commandSQL.Parameters.Split('$');
                        for (int i = 1; i < paramFilesVersions.Length; i += 2)
                        {
                            commandFilesVersions.Parameters.AddWithValue(paramFilesVersions[i], paramFilesVersions[i + 1]);
                        }
                        mydb.Insert(commandFilesVersions);
                        data = Encoding.Unicode.GetBytes("True");
                        handler.Send(data);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        break;
                        #endregion
                    }
                    break;
                }
            }
        }
Exemplo n.º 39
0
 /// <summary>
 /// Serializes the object to JSON.
 /// </summary>
 /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param>
 /// <param name="obj">The object to serialize to JSON.</param>
 public static void Serialize(JsonWriter writer, ApplicationInfo obj)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 40
0
        public static Instance CreateInstance(Vk api, GraphicsDebugLevel logLevel, string[] requiredExtensions, out ExtDebugReport debugReport, out DebugReportCallbackEXT debugReportCallback)
        {
            var enabledLayers = new List <string>();

            void AddAvailableLayer(string layerName)
            {
                uint layerPropertiesCount;

                api.EnumerateInstanceLayerProperties(&layerPropertiesCount, null).ThrowOnError();

                LayerProperties[] layerProperties = new LayerProperties[layerPropertiesCount];

                fixed(LayerProperties *pLayerProperties = layerProperties)
                {
                    api.EnumerateInstanceLayerProperties(&layerPropertiesCount, layerProperties).ThrowOnError();

                    for (int i = 0; i < layerPropertiesCount; i++)
                    {
                        string currentLayerName = Marshal.PtrToStringAnsi((IntPtr)pLayerProperties[i].LayerName);

                        if (currentLayerName == layerName)
                        {
                            enabledLayers.Add(layerName);
                            return;
                        }
                    }
                }

                Logger.Warning?.Print(LogClass.Gpu, $"Missing layer {layerName}");
            }

            if (logLevel == GraphicsDebugLevel.Slowdowns || logLevel == GraphicsDebugLevel.All)
            {
                AddAvailableLayer("VK_LAYER_KHRONOS_validation");
            }

            var enabledExtensions = requiredExtensions.Append(ExtDebugReport.ExtensionName).ToArray();

            var appName = Marshal.StringToHGlobalAnsi(AppName);

            var applicationInfo = new ApplicationInfo
            {
                PApplicationName   = (byte *)appName,
                ApplicationVersion = 1,
                PEngineName        = (byte *)appName,
                EngineVersion      = 1,
                ApiVersion         = Vk.Version12.Value
            };

            IntPtr *ppEnabledExtensions = stackalloc IntPtr[enabledExtensions.Length];
            IntPtr *ppEnabledLayers     = stackalloc IntPtr[enabledLayers.Count];

            for (int i = 0; i < enabledExtensions.Length; i++)
            {
                ppEnabledExtensions[i] = Marshal.StringToHGlobalAnsi(enabledExtensions[i]);
            }

            for (int i = 0; i < enabledLayers.Count; i++)
            {
                ppEnabledLayers[i] = Marshal.StringToHGlobalAnsi(enabledLayers[i]);
            }

            var instanceCreateInfo = new InstanceCreateInfo
            {
                SType                   = StructureType.InstanceCreateInfo,
                PApplicationInfo        = &applicationInfo,
                PpEnabledExtensionNames = (byte **)ppEnabledExtensions,
                PpEnabledLayerNames     = (byte **)ppEnabledLayers,
                EnabledExtensionCount   = (uint)enabledExtensions.Length,
                EnabledLayerCount       = (uint)enabledLayers.Count
            };

            api.CreateInstance(in instanceCreateInfo, null, out var instance).ThrowOnError();

            Marshal.FreeHGlobal(appName);

            for (int i = 0; i < enabledExtensions.Length; i++)
            {
                Marshal.FreeHGlobal(ppEnabledExtensions[i]);
            }

            for (int i = 0; i < enabledLayers.Count; i++)
            {
                Marshal.FreeHGlobal(ppEnabledLayers[i]);
            }

            if (!api.TryGetInstanceExtension(instance, out debugReport))
            {
                throw new Exception();
                // TODO: Exception.
            }

            if (logLevel != GraphicsDebugLevel.None)
            {
                var flags = logLevel switch
                {
                    GraphicsDebugLevel.Error => DebugReportFlagsEXT.DebugReportErrorBitExt,
                    GraphicsDebugLevel.Slowdowns => DebugReportFlagsEXT.DebugReportErrorBitExt | DebugReportFlagsEXT.DebugReportPerformanceWarningBitExt,
                    GraphicsDebugLevel.All => DebugReportFlagsEXT.DebugReportInformationBitExt |
                    DebugReportFlagsEXT.DebugReportWarningBitExt |
                    DebugReportFlagsEXT.DebugReportPerformanceWarningBitExt |
                    DebugReportFlagsEXT.DebugReportErrorBitExt |
                    DebugReportFlagsEXT.DebugReportDebugBitExt,
                    _ => throw new NotSupportedException()
                };
                var debugReportCallbackCreateInfo = new DebugReportCallbackCreateInfoEXT()
                {
                    SType       = StructureType.DebugReportCallbackCreateInfoExt,
                    Flags       = flags,
                    PfnCallback = new PfnDebugReportCallbackEXT(DebugReport)
                };

                debugReport.CreateDebugReportCallback(instance, in debugReportCallbackCreateInfo, null, out debugReportCallback).ThrowOnError();
            }
            else
            {
                debugReportCallback = default;
            }

            return(instance);
        }
Exemplo n.º 41
0
        public Boolean boolCampareOrder(string _ctrlID)
        {
            Boolean           boolResult = false;
            DataTable         DeliverDetailTable;
            DataTable         ReceiptDetailTable;
            DataTable         AppDetailTable;
            ApplicationInfo   applicationInfo   = new ApplicationInfo();
            ApplicationDetail applicationDetail = new ApplicationDetail();

            //dgvDevilerDetails.AutoGenerateColumns = false;
            //dgvReceiptDetails.AutoGenerateColumns = false;
            DeliverDetailTable = applicationDetail.SelectDeliverDetailByCtrlID(_ctrlID);
            ReceiptDetailTable = applicationDetail.SelectReceiptDetailByCtrlID(_ctrlID);
            AppDetailTable     = applicationDetail.SelectAppDetailByCtrlID(_ctrlID);
            foreach (DataRow deldr in DeliverDetailTable.Rows)
            {
                foreach (DataRow recdr in ReceiptDetailTable.Rows)
                {
                    if (DeliverDetailTable.Rows.Count == ReceiptDetailTable.Rows.Count && deldr["ItemID2"].ToString() == recdr["ItemID2"].ToString() && deldr["ItemID"].ToString() == recdr["ItemID"].ToString() && deldr["App_Count"].ToString() == recdr["App_Count"].ToString() && deldr["ItemHighlight"].ToString() == recdr["ItemHighlight"].ToString())
                    {
                        boolResult = false;
                        goto done;
                    }
                    else
                    {
                        boolResult = true;
                    }
                }
done:
                if (boolResult)
                {
                    goto Finish;
                }
            }
            foreach (DataRow recdr in ReceiptDetailTable.Rows)
            {
                foreach (DataRow deldr in DeliverDetailTable.Rows)
                {
                    if (DeliverDetailTable.Rows.Count == ReceiptDetailTable.Rows.Count && deldr["ItemID2"].ToString() == recdr["ItemID2"].ToString() && deldr["ItemID"].ToString() == recdr["ItemID"].ToString() && deldr["App_Count"].ToString() == recdr["App_Count"].ToString() && deldr["ItemHighlight"].ToString() == recdr["ItemHighlight"].ToString())
                    {
                        boolResult = false;
                        goto done2;
                    }
                    else
                    {
                        boolResult = true;
                    }
                }
done2:
                if (boolResult)
                {
                    goto Finish;
                }
            }
            foreach (DataRow deldr in DeliverDetailTable.Rows)
            {
                foreach (DataRow recdr in AppDetailTable.Rows)
                {
                    if (DeliverDetailTable.Rows.Count == AppDetailTable.Rows.Count && deldr["ItemID2"].ToString() == recdr["ItemID2"].ToString() && deldr["ItemID"].ToString() == recdr["ItemID"].ToString() && deldr["App_Count"].ToString() == recdr["App_Count"].ToString() && deldr["ItemHighlight"].ToString() == recdr["ItemHighlight"].ToString())
                    {
                        boolResult = false;
                        goto done3;
                    }
                    else
                    {
                        boolResult = true;
                    }
                }
done3:
                if (boolResult)
                {
                    goto Finish;
                }
            }
            foreach (DataRow recdr in AppDetailTable.Rows)
            {
                foreach (DataRow deldr in DeliverDetailTable.Rows)
                {
                    if (DeliverDetailTable.Rows.Count == AppDetailTable.Rows.Count && deldr["ItemID2"].ToString() == recdr["ItemID2"].ToString() && deldr["ItemID"].ToString() == recdr["ItemID"].ToString() && deldr["App_Count"].ToString() == recdr["App_Count"].ToString() && deldr["ItemHighlight"].ToString() == recdr["ItemHighlight"].ToString())
                    {
                        boolResult = false;
                        goto done4;
                    }
                    else
                    {
                        boolResult = true;
                    }
                }
done4:
                if (boolResult)
                {
                    goto Finish;
                }
            }
Finish:
            return(boolResult);
        }
Exemplo n.º 42
0
        async Task <object> CreateService(IAsyncServiceContainer container, CancellationToken cancellationToken, Type serviceType)
        {
            if (serviceType == null)
            {
                return(null);
            }

            if (container != this)
            {
                return(null);
            }

            if (serviceType == typeof(IGitHubServiceProvider))
            {
                //var sp = await GetServiceAsync(typeof(SVsServiceProvider)) as IServiceProvider;
                var result = new GitHubServiceProvider(this, this);
                await result.Initialize();

                return(result);
            }
            else if (serviceType == typeof(ILoginManager))
            {
                // These services are got through MEF and we will take a performance hit if ILoginManager is requested during
                // InitializeAsync. TODO: We can probably make LoginManager a normal MEF component rather than a service.
                var serviceProvider = await GetServiceAsync(typeof(IGitHubServiceProvider)) as IGitHubServiceProvider;

                var keychain      = serviceProvider.GetService <IKeychain>();
                var oauthListener = serviceProvider.GetService <IOAuthCallbackListener>();

                // HACK: We need to make sure this is run on the main thread. We really
                // shouldn't be injecting a view model concern into LoginManager - this
                // needs to be refactored. See #1398.
#pragma warning disable VSTHRD011 // Use AsyncLazy<T>
                var lazy2Fa = new Lazy <ITwoFactorChallengeHandler>(() =>
                                                                    ThreadHelper.JoinableTaskFactory.Run(async() =>
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                    return(serviceProvider.GetService <ITwoFactorChallengeHandler>());
                }));
#pragma warning restore VSTHRD011 // Use AsyncLazy<T>

                return(new LoginManager(
                           keychain,
                           lazy2Fa,
                           oauthListener,
                           ApiClientConfiguration.ClientId,
                           ApiClientConfiguration.ClientSecret,
                           ApiClientConfiguration.MinimumScopes,
                           ApiClientConfiguration.RequestedScopes,
                           ApiClientConfiguration.AuthorizationNote,
                           ApiClientConfiguration.MachineFingerprint));
            }
            else if (serviceType == typeof(IUsageService))
            {
                var sp = await GetServiceAsync(typeof(IGitHubServiceProvider)) as IGitHubServiceProvider;

                var environment = new Rothko.Environment();
                return(new UsageService(sp, environment));
            }
            else if (serviceType == typeof(IUsageTracker))
            {
                var usageService = await GetServiceAsync(typeof(IUsageService)) as IUsageService;

                var serviceProvider = await GetServiceAsync(typeof(IGitHubServiceProvider)) as IGitHubServiceProvider;

                var settings = await GetServiceAsync(typeof(IPackageSettings)) as IPackageSettings;

                return(new UsageTracker(serviceProvider, usageService, settings));
            }
            else if (serviceType == typeof(IVSGitExt))
            {
                var vsVersion = ApplicationInfo.GetHostVersionInfo().FileMajorPart;
                return(new VSGitExtFactory(vsVersion, this, GitService.GitServiceHelper).Create());
            }
            else if (serviceType == typeof(IGitHubToolWindowManager))
            {
                return(this);
            }
            else if (serviceType == typeof(IPackageSettings))
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var sp = new ServiceProvider(Services.Dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
                return(new PackageSettings(sp));
            }
            else if (serviceType == typeof(ITippingService))
            {
                return(new TippingService(this));
            }
            // go the mef route
            else
            {
                var sp = await GetServiceAsync(typeof(IGitHubServiceProvider)) as IGitHubServiceProvider;

                return(sp.TryGetService(serviceType));
            }
        }
Exemplo n.º 43
0
        private unsafe void Prepare()
        {
            // Create our API object for OpenXR.
            Xr = XR.GetApi();

            Extensions.Clear();
            //Extensions.Add("XR_KHR_vulkan_enable2");
            Extensions.Add("XR_KHR_vulkan_enable");
            Extensions.Add("XR_EXT_hp_mixed_reality_controller");
            Extensions.Add("XR_HTC_vive_cosmos_controller_interaction");
            Extensions.Add("XR_MSFT_hand_interaction");
            Extensions.Add("XR_EXT_samsung_odyssey_controller");

            uint propCount = 0;

            Xr.EnumerateInstanceExtensionProperties((byte *)null, 0, &propCount, null);

            ExtensionProperties[] props = new ExtensionProperties[propCount];
            for (int i = 0; i < props.Length; i++)
            {
                props[i].Type = StructureType.TypeExtensionProperties;

                fixed(ExtensionProperties *pptr = &props[0])
                Xr.EnumerateInstanceExtensionProperties((byte *)null, propCount, ref propCount, pptr);

                List <string> AvailableExtensions = new List <string>();
                for (int i = 0; i < props.Length; i++)
                {
                    fixed(void *nptr = props[i].ExtensionName)
                    AvailableExtensions.Add(Marshal.PtrToStringAnsi(new System.IntPtr(nptr)));
                }

                for (int i = 0; i < Extensions.Count; i++)
                {
                    if (AvailableExtensions.Contains(Extensions[i]) == false)
                    {
                        Extensions.RemoveAt(i);
                        i--;
                    }
                }

                InstanceCreateInfo instanceCreateInfo;

                var appInfo = new ApplicationInfo()
                {
                    ApiVersion = new Version64(1, 0, 9)
                };

                // We've got to marshal our strings and put them into global, immovable memory. To do that, we use
                // SilkMarshal.
                Span <byte> appName = new Span <byte>(appInfo.ApplicationName, 128);
                Span <byte> engName = new Span <byte>(appInfo.EngineName, 128);
                SilkMarshal.StringIntoSpan(System.AppDomain.CurrentDomain.FriendlyName, appName);
                SilkMarshal.StringIntoSpan("FocusEngine", engName);

                var requestedExtensions = SilkMarshal.StringArrayToPtr(Extensions);
                instanceCreateInfo = new InstanceCreateInfo
                                     (
                    applicationInfo: appInfo,
                    enabledExtensionCount: (uint)Extensions.Count,
                    enabledExtensionNames: (byte **)requestedExtensions
                                     );

                // Now we're ready to make our instance!
                CheckResult(Xr.CreateInstance(in instanceCreateInfo, ref Instance), "CreateInstance");

                // For our benefit, let's log some information about the instance we've just created.
                // skip this, as it crashes on Oculus runtime and is not needed

                /*InstanceProperties properties = new();
                 * CheckResult(Xr.GetInstanceProperties(Instance, ref properties), "GetInstanceProperties");
                 *
                 * var runtimeName = SilkMarshal.PtrToString((nint)properties.RuntimeName);
                 * var runtimeVersion = ((Version)(Version64)properties.RuntimeVersion).ToString(3);
                 *
                 * Console.WriteLine($"[INFO] Application: Using OpenXR Runtime \"{runtimeName}\" v{runtimeVersion}");*/

                // We're creating a head-mounted-display (HMD, i.e. a VR headset) example, so we ask for a runtime which
                // supports that form factor. The response we get is a ulong that is the System ID.
                var getInfo = new SystemGetInfo(formFactor: FormFactor.HeadMountedDisplay);
                CheckResult(Xr.GetSystem(Instance, in getInfo, ref system_id), "GetSystem");
        }
Exemplo n.º 44
0
        void RESTServer_Load(object sender, EventArgs e)
        {
            Response.Clear();
            Response.ContentType = "text/xml";

            APIConfigInfo apiInfo = APIConfigs.GetConfig();

            if (!apiInfo.Enable)
            {
                ResponseErrorInfo((int)ErrorType.API_EC_SERVICE);
                return;
            }

            //check sig
            DNTParam[] parameters = GetParamsFromRequest(Request);


            //GetRequests

            /*---- optional ----*/

            //format
            string format = DNTRequest.GetString("format");
            //callback
            string callback = DNTRequest.GetString("callback");


            /*---- required ----*/

            //api_key
            string api_key = DNTRequest.GetString("api_key");
            //整合程序对象
            ApplicationInfo           appInfo       = null;
            ApplicationInfoCollection appcollection = apiInfo.AppCollection;

            foreach (ApplicationInfo newapp in appcollection)
            {
                if (newapp.APIKey == DNTRequest.GetString("api_key"))
                {
                    appInfo = newapp;
                }
            }

            if (appInfo == null)
            {
                //输出API Key错误
                ResponseErrorInfo((int)ErrorType.API_EC_APPLICATION);
                return;
            }
            //check request ip
            string ip = DNTRequest.GetIP();

            if (appInfo.IPAddresses != null && appInfo.IPAddresses.Trim() != string.Empty && !Utils.InIPArray(ip, appInfo.IPAddresses.Split(',')))
            {
                ResponseErrorInfo((int)ErrorType.API_EC_BAD_IP);
                return;
            }

            /*---- required by specific method----*/



            string sig = GetSignature(parameters, appInfo.Secret);
            //if (sig != DNTRequest.GetString("sig"))
            //{
            //    //输出签名错误
            //    ResponseErrorInfo((int)ErrorType.API_EC_SIGNATURE);
            //    return;
            //}

            //get session_key and check user
            string session_key = DNTRequest.GetString("session_key");
            int    uid         = GetUidFromSessionKey(session_key, appInfo.Secret);



            string method = DNTRequest.GetString("method");

            if (method == string.Empty)
            {
                ResponseErrorInfo((int)ErrorType.API_EC_METHOD);
                return;
            }
            string classname  = method.Substring(0, method.LastIndexOf('.'));
            string methodname = method.Substring(method.LastIndexOf('.') + 1);

            string     content;
            ActionBase action;
            double     lastcallid = -1;
            double     callid     = -1;

            try
            {
                Type type = Type.GetType(string.Format("Discuz.Web.Services.API.Actions.{0}, Discuz.Web.Services", classname), false, true);
                action           = (ActionBase)Activator.CreateInstance(type);
                action.ApiKey    = api_key;
                action.Params    = parameters;
                action.App       = appInfo;
                action.Secret    = appInfo.Secret;
                action.Uid       = uid;
                action.Format    = FormatType.XML;
                action.Signature = sig;

                //call_id    - milliseconds  record last callid
                double.TryParse(DNTRequest.GetString("call_id"), out callid);
                if (callid > -1)
                {
                    if (Session["call_id"] == null)
                    {
                        lastcallid = -1;
                    }
                    else
                    {
                        double.TryParse(Session["call_id"].ToString(), out lastcallid);
                    }
                }
                action.CallId     = callid;
                action.LastCallId = lastcallid;

                if (format.Trim().ToLower() == "json")
                {
                    Response.ContentType = "text/html";
                    action.Format        = FormatType.JSON;
                }

                content = type.InvokeMember(methodname, BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase, null, action, new object[] { }).ToString();
            }
            catch
            {
                content = "";
                ResponseErrorInfo((int)ErrorType.API_EC_METHOD);
                return;
            }
            if (action.ErrorCode > 0)
            {
                ResponseErrorInfo(action.ErrorCode);
                return;
            }

            //update callid
            if (callid > lastcallid)
            {
                Session["call_id"] = callid;
            }

            //成功后适当的地方更新用户在线状态
            if (callback != string.Empty)
            {
                Response.ContentType = "text/html";
                if (action.Format == FormatType.JSON)
                {
                    content = callback + "(" + content + ");";
                }
                else
                {
                    content = callback + "(\"" + content.Replace("\"", "\\\"") + "\");";
                }
            }
            Response.Write(content);
            Response.End();
        }
        static void Main(string[] args)
        {
            // Create ApplicationInfo, setting the clientID from Azure AD App Registration as the ApplicationId
            // If any of these values are not set API throws BadInputException.
            ApplicationInfo appInfo = new ApplicationInfo()
            {
                // ApplicationId should ideally be set to the same ClientId found in the Azure AD App Registration.
                // This ensures that the clientID in AAD matches the AppId reported in AIP Analytics.
                ApplicationId      = clientId,
                ApplicationName    = appName,
                ApplicationVersion = appVersion
            };

            // Initialize Action class, passing in AppInfo.
            Action action = new Action(appInfo);

            // List all labels available to the engine created in Action
            IEnumerable <Label> labels = action.ListLabels();


            // Enumerate parent and child labels and print name/ID.
            foreach (var label in labels)
            {
                Console.WriteLine(string.Format("{0} - {1}", label.Name, label.Id));

                if (label.Children.Count > 0)
                {
                    foreach (Label child in label.Children)
                    {
                        Console.WriteLine(string.Format("\t{0} - {1}", child.Name, child.Id));
                    }
                }
            }

            // Prompt user to enter a label ID from above
            Console.Write("Enter a label identifier from above: ");
            var labelId = Console.ReadLine();

            // Prompt for path inputs
            Console.Write("Enter an input file path: ");
            string inputFilePath = Console.ReadLine();

            Console.Write("Enter an output file path: ");
            string outputFilePath = Console.ReadLine();

            // Set file options from FileOptions struct. Used to set various parameters for FileHandler
            Action.FileOptions options = new Action.FileOptions
            {
                FileName                 = inputFilePath,
                OutputName               = outputFilePath,
                ActionSource             = ActionSource.Manual,
                AssignmentMethod         = AssignmentMethod.Standard,
                DataState                = DataState.Rest,
                GenerateChangeAuditEvent = true,
                IsAuditDiscoveryEnabled  = true,
                LabelId = labelId
            };

            //Set the label on the file handler object
            Console.WriteLine(string.Format("Set label ID {0} on {1}", labelId, inputFilePath));

            // Set label, commit change to outputfile, and send audit event if enabled.
            var result = action.SetLabel(options);

            Console.WriteLine(string.Format("Committed label ID {0} to {1}", labelId, outputFilePath));

            // Create a new handler to read the labeled file metadata.
            Console.WriteLine(string.Format("Getting the label committed to file: {0}", outputFilePath));

            // Update options to read the previously generated file output.
            options.FileName = options.OutputName;

            // Read label from the previously labeled file.
            var contentLabel = action.GetLabel(options);

            // Display the label with protection information.
            Console.WriteLine(string.Format("File Label: {0} \r\nIsProtected: {1}", contentLabel.Label.Name, contentLabel.IsProtectionAppliedFromLabel.ToString()));
            Console.WriteLine("Press a key to quit.");
            Console.ReadKey();
        }
Exemplo n.º 46
0
 public static void Initialise(NexdoxEngine engine, ApplicationInfo appInfo)
 {
     UnitySQLServer = appInfo["UnitySQLServer"];
 }
 private void InitFullScopeAdapter(ApplicationType appType)
 {
     appInfo = GetDefaultApplication(appType);
     adapter = GetDefaultAdapter(appType);
 }
Exemplo n.º 48
0
        /// <summary>
        /// Creates a per application user, sets security access rules for the application deployment directory
        /// and adds a new site to IIS without starting it
        /// </summary>
        /// <param name="appInfo">Structure that contains parameters required for deploying the application.</param>
        /// <param name="version">The dot net framework version supported by the application.</param>
        private void DeployApp(ApplicationInfo appInfo, DotNetVersion version)
        {
            this.startupLogger.Info(Strings.DeployingAppOnIis);

            string aspNetVersion = GetAspDotNetVersion(version);
            string password      = appInfo.WindowsPassword;
            string userName      = appInfo.WindowsUserName;

            try
            {
                mut.WaitOne();
                using (ServerManager serverMgr = new ServerManager())
                {
                    DirectoryInfo deploymentDir = new DirectoryInfo(appInfo.Path);

                    DirectorySecurity deploymentDirSecurity = deploymentDir.GetAccessControl();

                    deploymentDirSecurity.SetAccessRule(
                        new FileSystemAccessRule(
                            userName,
                            FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify,
                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                            PropagationFlags.None,
                            AccessControlType.Allow));

                    deploymentDir.SetAccessControl(deploymentDirSecurity);

                    Site mySite = serverMgr.Sites.Add(this.appName, appInfo.Path, appInfo.Port);
                    mySite.ServerAutoStart = false;

                    ApplicationPool applicationPool = serverMgr.ApplicationPools[this.appName];
                    if (applicationPool == null)
                    {
                        serverMgr.ApplicationPools.Add(this.appName);
                        applicationPool = serverMgr.ApplicationPools[this.appName];
                        applicationPool.ManagedRuntimeVersion        = aspNetVersion;
                        applicationPool.ProcessModel.IdentityType    = ProcessModelIdentityType.SpecificUser;
                        applicationPool.ProcessModel.UserName        = userName;
                        applicationPool.ProcessModel.Password        = password;
                        applicationPool.ProcessModel.LoadUserProfile = true;
                        if (this.cpuTarget == CpuTarget.X86)
                        {
                            applicationPool.Enable32BitAppOnWin64 = true;
                        }
                        else
                        {
                            applicationPool.Enable32BitAppOnWin64 = false;
                        }
                    }

                    mySite.Applications["/"].ApplicationPoolName = this.appName;
                    FirewallTools.OpenPort(appInfo.Port, appInfo.Name);
                    serverMgr.CommitChanges();
                }
            }
            finally
            {
                mut.ReleaseMutex();
                this.startupLogger.Info(Strings.FinishedAppDeploymentOnIis);
            }
        }
Exemplo n.º 49
0
        public unsafe GraphicsAdapterFactoryInstance(bool enableValidation)
        {
            var applicationInfo = new ApplicationInfo
            {
                StructureType = StructureType.ApplicationInfo,
                ApiVersion    = new SharpVulkan.Version(1, 0, 0),
                EngineName    = Marshal.StringToHGlobalAnsi("Xenko"),
                //EngineVersion = new SharpVulkan.Version()
            };

            var desiredLayerNames = new[]
            {
                //"VK_LAYER_LUNARG_standard_validation",
                "VK_LAYER_GOOGLE_threading",
                "VK_LAYER_LUNARG_parameter_validation",
                "VK_LAYER_LUNARG_device_limits",
                "VK_LAYER_LUNARG_object_tracker",
                "VK_LAYER_LUNARG_image",
                "VK_LAYER_LUNARG_core_validation",
                "VK_LAYER_LUNARG_swapchain",
                "VK_LAYER_GOOGLE_unique_objects",
                //"VK_LAYER_LUNARG_api_dump",
                //"VK_LAYER_LUNARG_vktrace"
            };

            IntPtr[] enabledLayerNames = new IntPtr[0];

            if (enableValidation)
            {
                var layers = Vulkan.InstanceLayerProperties;
                var availableLayerNames = new HashSet <string>();

                for (int index = 0; index < layers.Length; index++)
                {
                    var properties  = layers[index];
                    var namePointer = new IntPtr(Interop.Fixed(ref properties.LayerName));
                    var name        = Marshal.PtrToStringAnsi(namePointer);

                    availableLayerNames.Add(name);
                }

                enabledLayerNames = desiredLayerNames
                                    .Where(x => availableLayerNames.Contains(x))
                                    .Select(Marshal.StringToHGlobalAnsi).ToArray();
            }

            var extensionProperties     = Vulkan.GetInstanceExtensionProperties();
            var availableExtensionNames = new List <string>();
            var desiredExtensionNames   = new List <string>();

            for (int index = 0; index < extensionProperties.Length; index++)
            {
                var namePointer = new IntPtr(Interop.Fixed(ref extensionProperties[index].ExtensionName));
                var name        = Marshal.PtrToStringAnsi(namePointer);
                availableExtensionNames.Add(name);
            }

            desiredExtensionNames.Add("VK_KHR_surface");
            if (!availableExtensionNames.Contains("VK_KHR_surface"))
            {
                throw new InvalidOperationException("Required extension VK_KHR_surface is not available");
            }

#if SILICONSTUDIO_PLATFORM_WINDOWS_DESKTOP
            desiredExtensionNames.Add("VK_KHR_win32_surface");
            if (!availableExtensionNames.Contains("VK_KHR_win32_surface"))
            {
                throw new InvalidOperationException("Required extension VK_KHR_win32_surface is not available");
            }
#elif SILICONSTUDIO_PLATFORM_ANDROID
            desiredExtensionNames.Add("VK_KHR_android_surface");
            if (!availableExtensionNames.Contains("VK_KHR_android_surface"))
            {
                throw new InvalidOperationException("Required extension VK_KHR_android_surface is not available");
            }
#elif SILICONSTUDIO_PLATFORM_LINUX
            if (availableExtensionNames.Contains("VK_KHR_xlib_surface"))
            {
                desiredExtensionNames.Add("VK_KHR_xlib_surface");
                HasXlibSurfaceSupport = true;
            }
            else if (availableExtensionNames.Contains("VK_KHR_xcb_surface"))
            {
                desiredExtensionNames.Add("VK_KHR_xcb_surface");
            }
            else
            {
                throw new InvalidOperationException("None of the supported surface extensions VK_KHR_xcb_surface or VK_KHR_xlib_surface is available");
            }
#endif
            bool enableDebugReport = enableValidation && availableExtensionNames.Contains("VK_EXT_debug_report");
            if (enableDebugReport)
            {
                desiredExtensionNames.Add("VK_EXT_debug_report");
            }

            var enabledExtensionNames = desiredExtensionNames.Select(Marshal.StringToHGlobalAnsi).ToArray();

            var createDebugReportCallbackName = Marshal.StringToHGlobalAnsi("vkCreateDebugReportCallbackEXT");

            try
            {
                fixed(void *enabledExtensionNamesPointer = &enabledExtensionNames[0])
                {
                    var insatanceCreateInfo = new InstanceCreateInfo
                    {
                        StructureType         = StructureType.InstanceCreateInfo,
                        ApplicationInfo       = new IntPtr(&applicationInfo),
                        EnabledLayerCount     = enabledLayerNames != null ? (uint)enabledLayerNames.Length : 0,
                        EnabledLayerNames     = enabledLayerNames?.Length > 0 ? new IntPtr(Interop.Fixed(enabledLayerNames)) : IntPtr.Zero,
                        EnabledExtensionCount = (uint)enabledExtensionNames.Length,
                        EnabledExtensionNames = new IntPtr(enabledExtensionNamesPointer)
                    };

                    NativeInstance = Vulkan.CreateInstance(ref insatanceCreateInfo);
                }

                if (enableDebugReport)
                {
                    var createDebugReportCallback = (CreateDebugReportCallbackDelegate)Marshal.GetDelegateForFunctionPointer(NativeInstance.GetProcAddress((byte *)createDebugReportCallbackName), typeof(CreateDebugReportCallbackDelegate));

                    debugReport = DebugReport;
                    var createInfo = new DebugReportCallbackCreateInfo
                    {
                        StructureType = StructureType.DebugReportCallbackCreateInfo,
                        Flags         = (uint)(DebugReportFlags.Error | DebugReportFlags.Warning /* | DebugReportFlags.PerformanceWarning | DebugReportFlags.Information | DebugReportFlags.Debug*/),
                        Callback      = Marshal.GetFunctionPointerForDelegate(debugReport)
                    };
                    createDebugReportCallback(NativeInstance, ref createInfo, null, out debugReportCallback);
                }

                if (availableExtensionNames.Contains("VK_EXT_debug_marker"))
                {
                    var beginDebugMarkerName = System.Text.Encoding.ASCII.GetBytes("vkCmdDebugMarkerBeginEXT");

                    var ptr = NativeInstance.GetProcAddress((byte *)Interop.Fixed(beginDebugMarkerName));
                    if (ptr != IntPtr.Zero)
                    {
                        BeginDebugMarker = (BeginDebugMarkerDelegate)Marshal.GetDelegateForFunctionPointer(ptr, typeof(BeginDebugMarkerDelegate));
                    }

                    var endDebugMarkerName = System.Text.Encoding.ASCII.GetBytes("vkCmdDebugMarkerEndEXT");
                    ptr = NativeInstance.GetProcAddress((byte *)Interop.Fixed(endDebugMarkerName));
                    if (ptr != IntPtr.Zero)
                    {
                        EndDebugMarker = (EndDebugMarkerDelegate)Marshal.GetDelegateForFunctionPointer(ptr, typeof(EndDebugMarkerDelegate));
                    }
                }
            }
            finally
            {
                foreach (var enabledExtensionName in enabledExtensionNames)
                {
                    Marshal.FreeHGlobal(enabledExtensionName);
                }

                foreach (var enabledLayerName in enabledLayerNames)
                {
                    Marshal.FreeHGlobal(enabledLayerName);
                }

                Marshal.FreeHGlobal(applicationInfo.EngineName);
                Marshal.FreeHGlobal(createDebugReportCallbackName);
            }
        }
Exemplo n.º 50
0
        public void OnAgree(object sender, EventArgs args)
        {
            ApplicationInfo.SignAgreement();

            UserInterface.OnLicenseAgreed();
        }
        public void SupportFileLocationForExistingLayoutFileTest(bool leadTilde, bool leadSeparator, string[] existingLayoutFileParts, string[] expectedSupportFileLocationParts, string[] expectedLayoutFileParts)
        {
            string expectedSupportFileLocation;
            string expectedLayoutFile;

            if (expectedSupportFileLocationParts.Length > 0)
            {
                expectedSupportFileLocation = Path.Combine(expectedSupportFileLocationParts);
            }
            else
            {
                expectedSupportFileLocation = IdentityGeneratorTemplateModelBuilder._DefaultSupportLocation;
            }

            if (expectedLayoutFileParts.Length > 0)
            {
                expectedLayoutFile = Path.Combine(expectedLayoutFileParts);
            }
            else
            {
                expectedLayoutFile = Path.Combine(IdentityGeneratorTemplateModelBuilder._DefaultSupportLocation, IdentityGeneratorTemplateModelBuilder._LayoutFileName);
            }
            expectedLayoutFile = expectedLayoutFile.Replace("\\", "/");

            string existingLayoutFile = string.Empty;

            if (leadTilde)
            {
                existingLayoutFile += "~";
            }

            if (leadSeparator)
            {
                existingLayoutFile += Path.DirectorySeparatorChar;
            }

            if (existingLayoutFileParts.Length > 0)
            {
                existingLayoutFile = existingLayoutFile + Path.Combine(existingLayoutFileParts);
            }

            IdentityGeneratorCommandLineModel commandLineModel = new IdentityGeneratorCommandLineModel();

            commandLineModel.Layout = existingLayoutFile;

            IApplicationInfo     applicationInfo = new ApplicationInfo("test", LayoutFileLocationTestProjectBasePath);
            CommonProjectContext context         = new CommonProjectContext();

            context.ProjectFullPath       = LayoutFileLocationTestProjectBasePath;
            context.ProjectName           = "TestProject";
            context.AssemblyName          = "TestAssembly";
            context.CompilationItems      = new List <string>();
            context.CompilationAssemblies = new List <ResolvedReference>();

            Workspace workspace = new RoslynWorkspace(context);
            ICodeGenAssemblyLoadContext assemblyLoadContext = new DefaultAssemblyLoadContext();
            IFileSystem mockFileSystem = new MockFileSystem();
            ILogger     logger         = new ConsoleLogger();

            IdentityGeneratorTemplateModelBuilder modelBuilder = new IdentityGeneratorTemplateModelBuilder(commandLineModel, applicationInfo, context, workspace, assemblyLoadContext, mockFileSystem, logger);

            modelBuilder.DetermineSupportFileLocation(out string supportFileLocation, out string layoutFile);
            Assert.Equal(expectedSupportFileLocation, supportFileLocation);
            Assert.Equal(expectedLayoutFile, layoutFile);
        }
Exemplo n.º 52
0
        /// <summary>
        /// Used to explicitly load the form's settings if <see cref="AutoLoad"/> is false.
        /// </summary>
        /// <returns>True if the previous settings were re-loaded;
        /// False if no previous settings existed.</returns>
        public bool Load()
        {
            bool result = false;

            Conditions.RequireState(this.form != null, "Load requires a non-null Form.");

            if (!this.DesignMode)
            {
                using (ISettingsStore store = ApplicationInfo.CreateUserSettingsStore())
                {
                    ISettingsNode?formLayoutNode = this.GetFormLayoutNode(store, false);
                    if (formLayoutNode != null)
                    {
                        result = true;

                        int             left   = formLayoutNode.GetValue("Left", this.form.Left);
                        int             top    = formLayoutNode.GetValue("Top", this.form.Top);
                        int             width  = formLayoutNode.GetValue("Width", this.form.Width);
                        int             height = formLayoutNode.GetValue("Height", this.form.Height);
                        FormWindowState state  = formLayoutNode.GetValue("WindowState", this.form.WindowState);

                        this.form.SuspendLayout();
                        try
                        {
                            this.form.Location = new Point(left, top);
                            if (this.form.FormBorderStyle == FormBorderStyle.Sizable || this.form.FormBorderStyle == FormBorderStyle.SizableToolWindow)
                            {
                                this.form.Size = new Size(width, height);
                            }

                            // If the form's current state isn't Normal, then it was launched from a
                            // shortcut or command line START command to be Minimized or Maximized.
                            // In those cases, we don't want to override the state.
                            if (this.form.WindowState == FormWindowState.Normal &&
                                (this.AllowLoadMinimized || state != FormWindowState.Minimized))
                            {
                                this.form.WindowState = state;
                            }
                        }
                        finally
                        {
                            this.form.ResumeLayout();
                        }

                        // Make sure the window is somewhere on one of the screens.
                        if (!SystemInformation.VirtualScreen.Contains(left, top))
                        {
                            Point     point         = SystemInformation.VirtualScreen.Location;
                            const int DefaultOffset = 20;
                            point.Offset(DefaultOffset, DefaultOffset);
                            this.form.DesktopLocation = point;
                        }
                    }

                    // Fire the internal event first
                    var eventHandler = this.InternalLoadSettings;
                    eventHandler?.Invoke(this, new SettingsEventArgs(store.RootNode));

                    eventHandler = this.LoadSettings;
                    eventHandler?.Invoke(this, new SettingsEventArgs(store.RootNode));
                }
            }

            return(result);
        }
Exemplo n.º 53
0
        /// <summary>
        /// Determines if the target application is running on the target device.
        /// </summary>
        /// <param name="packageName"></param>
        /// <param name="targetDevice"></param>
        /// <param name="appInfo">Optional cached <see cref="ApplicationInfo"/>.</param>
        /// <returns>True, if the application is running.</returns>
        public static async Task <bool> IsAppRunningAsync(string packageName, DeviceInfo targetDevice, ApplicationInfo appInfo = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(packageName));

            if (appInfo == null)
            {
                appInfo = await GetApplicationInfoAsync(packageName, targetDevice);
            }

            if (appInfo == null)
            {
                Debug.LogError($"{packageName} not installed.");
                return(false);
            }

            var response = await Rest.GetAsync(string.Format(ProcessQuery, FinalizeUrl(targetDevice.IP)), targetDevice.Authorization);

            if (response.Successful)
            {
                var processList = JsonUtility.FromJson <ProcessList>(response.ResponseBody);
                for (int i = 0; i < processList.Processes.Length; ++i)
                {
                    if (processList.Processes[i].ImageName.Contains(appInfo.Name))
                    {
                        return(true);
                    }
                }

                return(false);
            }

            if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
            {
                return(await IsAppRunningAsync(packageName, targetDevice, appInfo));
            }

            Debug.LogError($"{response.ResponseBody}");
            return(false);
        }
        /// <summary>
        /// To get the application icon path
        /// </summary>
        /// <param name="id">An application ID</param>
        /// <returns>The application icon path</returns>
        public string GetApplicationIconPath(string id)
        {
            var info = new ApplicationInfo(id);

            return(info.IconPath);
        }
Exemplo n.º 55
0
        /// <summary>
        /// Uninstalls the target application on the target device
        /// </summary>
        /// <param name="packageName"></param>
        /// <param name="targetDevice"></param>
        /// <param name="appInfo">Optional cached <see cref="ApplicationInfo"/>.</param>
        /// <returns>True, if uninstall was a success.</returns>
        public static async Task <bool> UninstallAppAsync(string packageName, DeviceInfo targetDevice, ApplicationInfo appInfo = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(packageName));

            if (appInfo == null)
            {
                appInfo = await GetApplicationInfoAsync(packageName, targetDevice);
            }

            if (appInfo == null)
            {
                Debug.LogWarning($"Application '{packageName}' not found");
                return(false);
            }

            Debug.Log($"Attempting to uninstall {packageName} on {targetDevice.MachineName}...");

            string query    = $"{string.Format(InstallQuery, FinalizeUrl(targetDevice.IP))}?package={UnityWebRequest.EscapeURL(appInfo.PackageFullName)}";
            var    response = await Rest.DeleteAsync(query, targetDevice.Authorization);

            if (response.Successful)
            {
                Debug.Log($"Successfully uninstalled {packageName} on {targetDevice.MachineName}.");
            }
            else
            if (!response.Successful)
            {
                if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
                {
                    return(await UninstallAppAsync(packageName, targetDevice));
                }

                Debug.LogError($"Failed to uninstall {packageName} on {targetDevice.MachineName}");
                Debug.LogError(response.ResponseBody);
                return(false);
            }

            return(true);
        }
Exemplo n.º 56
0
        /// <summary>
        /// Stops the target application on the target device.
        /// </summary>
        /// <param name="packageName"></param>
        /// <param name="targetDevice"></param>
        /// <param name="appInfo">Optional cached <see cref="ApplicationInfo"/>.</param>
        /// <returns>true, if application was successfully stopped.</returns>
        public static async Task <bool> StopAppAsync(string packageName, DeviceInfo targetDevice, ApplicationInfo appInfo = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(packageName));

            if (appInfo == null)
            {
                appInfo = await GetApplicationInfoAsync(packageName, targetDevice);
            }

            if (appInfo == null)
            {
                Debug.LogWarning($"Application '{packageName}' not found");
                return(false);
            }

            string   query    = $"{string.Format(AppQuery, FinalizeUrl(targetDevice.IP))}?package={UnityWebRequest.EscapeURL(appInfo.PackageFullName.EncodeTo64())}";
            Response response = await Rest.DeleteAsync(query, targetDevice.Authorization);

            if (!response.Successful)
            {
                if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
                {
                    return(await StopAppAsync(packageName, targetDevice));
                }

                Debug.LogError(response.ResponseBody);
                return(false);
            }

            while (!await IsAppRunningAsync(packageName, targetDevice, appInfo))
            {
                await new WaitForSeconds(1f);
            }

            return(true);
        }
Exemplo n.º 57
0
        /// <summary>
        /// Gets the dot net version that the application runs on.
        /// </summary>
        /// <param name="appInfo">The application info structure.</param>
        /// <returns>The .net version supported by the application</returns>
        private DotNetVersion GetAppVersion(ApplicationInfo appInfo)
        {
            this.startupLogger.Info(Strings.DeterminingApplication);

            DotNetVersion version = NetFrameworkVersion.GetFrameworkFromConfig(Path.Combine(appInfo.Path, "web.config"));

            if (version == DotNetVersion.Two)
            {
                string[] allAssemblies = Directory.GetFiles(appInfo.Path, "*.dll", SearchOption.AllDirectories);

                foreach (string assembly in allAssemblies)
                {
                    if (NetFrameworkVersion.GetVersion(assembly) == DotNetVersion.Four)
                    {
                        version = DotNetVersion.Four;
                        break;
                    }
                }
            }

            this.startupLogger.Info(Strings.DetectedNet + GetAspDotNetVersion(version));

            return version;
        }
Exemplo n.º 58
0
        /// <summary>
        /// Downloads and launches the Log file for the target application on the target device.
        /// </summary>
        /// <param name="packageName"></param>
        /// <param name="targetDevice"></param>
        /// <param name="appInfo">Optional cached <see cref="ApplicationInfo"/>.</param>
        /// <returns>The path of the downloaded log file.</returns>
        public static async Task <string> DownloadLogFileAsync(string packageName, DeviceInfo targetDevice, ApplicationInfo appInfo = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(packageName));

            if (appInfo == null)
            {
                appInfo = await GetApplicationInfoAsync(packageName, targetDevice);
            }

            if (appInfo == null)
            {
                Debug.LogWarning($"Application '{packageName}' not found");
                return(string.Empty);
            }

            string logFile  = $"{Application.temporaryCachePath}/{targetDevice.MachineName}_{DateTime.Now.Year}{DateTime.Now.Month}{DateTime.Now.Day}{DateTime.Now.Hour}{DateTime.Now.Minute}{DateTime.Now.Second}_player.txt";
            var    response = await Rest.GetAsync(string.Format(FileQuery, FinalizeUrl(targetDevice.IP), appInfo.PackageFullName), targetDevice.Authorization);

            if (!response.Successful)
            {
                if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
                {
                    return(await DownloadLogFileAsync(packageName, targetDevice));
                }

                Debug.LogError(response.ResponseBody);
                return(string.Empty);
            }

            File.WriteAllText(logFile, response.ResponseBody);
            return(logFile);
        }
Exemplo n.º 59
0
        /// <summary>
        /// sets the initial data for an application
        /// </summary>
        /// <param name="variables">All variables needed to run the application.</param>
        public void ConfigureApplication(ApplicationVariable[] variables)
        {
            try
            {
                ApplicationParsedData parsedData = PluginHelper.GetParsedData(variables);
                this.startupLogger = new FileLogger(parsedData.StartupLogFilePath);

                this.appName = RemoveSpecialCharacters(parsedData.AppInfo.Name) + parsedData.AppInfo.Port.ToString(CultureInfo.InvariantCulture);
                this.appPath = parsedData.AppInfo.Path;

                this.applicationInfo = parsedData.AppInfo;

                this.autoWireTemplates = parsedData.AutoWireTemplates;

                this.aspDotNetVersion = this.GetAppVersion(this.applicationInfo);

                this.cpuTarget = this.GetCpuTarget(this.applicationInfo);

                this.AutowireApp(parsedData.AppInfo, variables, parsedData.GetServices(), parsedData.LogFilePath, parsedData.ErrorLogFilePath);
            }
            catch (Exception ex)
            {
                this.startupLogger.Error(ex.ToString());
                throw;
            }
        }
 public ApplicationItem(Context context, ApplicationInfo info)
 {
     Info    = info;
     m_title = info.LoadLabel(context.PackageManager);
 }