Example #1
0
 /// <summary>
 /// Send the failure message to our own app instance
 /// </summary>
 /// <param name="appInstance">An app instance</param>
 public override void VisitAppInstance(AppInstance appInstance)
 {
     if (appInstance == this.Instance)
     {
         appInstance.Send("MSG_GENERAL_FAILURE " + Failure.Serialize());
     }
 }
Example #2
0
 public GeneralFailure(MsgGeneralFailure failure, AppInstance instance)
 {
     this.Failure = failure;
     this.Instance = instance;
     if (instance != null)
         instance.Issue(this);
 }
Example #3
0
 /// <summary>
 /// Send a message to this app instance that manifest failed
 /// </summary>
 /// <param name="appInstance">the app instance to visit</param>
 public override void VisitAppInstance(AppInstance appInstance)
 {
     if (appInstance == instance)
     {
         appInstance.Send("APP_MANIFEST_FAIL " + Fail.Serialize());
         appInstance.Disconnect();
     }
 }
Example #4
0
 public ManifestFail(string message, AppInstance instance)
 {
     Fail = new AppManifestFail();
     Fail.Message = message;
     this.instance = instance;
     if (instance != null)
         instance.Issue(this);
 }
Example #5
0
 public Create(AppManifest manifest, AppInstance instance)
 {
     this.manifest = manifest;
     this.instance = instance;
     this.okMsg = new AppManifestOk();
     this.okMsg.InstanceId = manifest.InstanceId != null ? manifest.InstanceId : instance.InstanceId;
     this.Log = Logger.GetInstance();
 }
Example #6
0
 public GeneralFailure(ParseException ex, AppInstance instance)
 {
     this.Failure = new MsgGeneralFailure();
     this.Failure.Received = ex.Received;
     this.Failure.Message = ex.Message;
     this.Instance = instance;
     if (instance != null)
         instance.Issue(this);
 }
Example #7
0
 /// <summary>
 /// Get the Query object associated with this MSG_QUERY
 /// </summary>
 /// <param name="data">the JSON data without a verb</param>
 /// <param name="instance">the app instance that issued this query</param>
 /// <returns>either a DirectedQuery or UndirectedQuery</returns>
 public static new Command Parse(string data, AppInstance instance)
 {
     MsgQuery query = MsgQuery.Deserialize(data) as MsgQuery;
     Query ret = null;
     if (query.InstanceId.Count == 0)
         ret = new UndirectedQuery(query, instance);
     else
         ret = new DirectedQuery(query, instance);
     return ret;
 }
Example #8
0
 public Query(MsgQuery query, AppInstance instance)
 {
     this.FromInstance = instance;
     this.query = query;
     if (instance != null)
         this.query.FromInstanceId = instance.InstanceId;
     this.guid = query.Id;
     this.HasValidGuid = false;
     this.ShouldArchive = false;
 }
Example #9
0
        public void DumpInfo(StreamWriter output)
        {
            uint apiVersion = Vulkan.Version.Make(1, 0, 0);

            DumpHeader(apiVersion, output);

            AppInstance instance = AppCreateInstance(apiVersion);

            output.WriteLine("Instance Extensions and layers:");
            output.WriteLine("===============================");
            AppDumpExtensions("", "Instance", instance.Extensions, output);

            output.WriteLine("Instance Layers\tcount = {0}", instance.Layers.Length);
            foreach (LayerExtensionList layer in instance.Layers)
            {
                LayerProperties layerProp = layer.LayerProperties;

                uint major, minor, patch;

                ExtractVersion(layerProp.SpecVersion, out major, out minor, out patch);
                string specVersion  = string.Format("{0}.{1}.{2}", major, minor, patch);
                string layerVersion = string.Format("{0}", layerProp.ImplementationVersion);

                output.WriteLine("\t{0} ({1}) Vulkan version {2}, layer version {3}",
                                 layerProp.LayerName, layerProp.Description,
                                 specVersion, layerVersion);

                AppDumpExtensions("\t", layerProp.LayerName, layer.ExtensionProperties, output);
            }

            PhysicalDevice[] objs = instance.Instance.EnumeratePhysicalDevices();
            AppGpu[]         gpus = new AppGpu[objs.Length];

            for (uint i = 0; i < objs.Length; i++)
            {
                gpus[i] = AppGpuInit(i, objs[i]);
                AppGpuDump(gpus[i], output);
                output.WriteLine();
                output.WriteLine();
            }

            for (uint i = 0; i < gpus.Length; i++)
            {
                AppGpuDestroy(gpus[i]);
            }

            AppDestroyInstance(instance);
            output.Flush();
        }
Example #10
0
        private static void RedirectOrCreateNewInstance()
        {
            var instance = (GetLastActiveInstance() ?? AppInstance.FindOrRegisterInstanceForKey(App.Id.ToString()));

            if (instance.IsCurrentInstance)
            {
                Windows.UI.Xaml.Application.Start(p => new App());
            }
            else
            {
                // open new instance if user prefers to
                if (ApplicationSettingsStore.Read(SettingsKey.AlwaysOpenNewWindowBool) is bool alwaysOpenNewWindowBool && alwaysOpenNewWindowBool)
                {
                    OpenNewInstance();
                }
Example #11
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static SystemInfo GetInfo()
        {
            var sysInfo = new SystemInfo();

            sysInfo.ServerIP = GetServerIP();
            AppendSysInfo(sysInfo, ".", Process.GetCurrentProcess().ProcessName);

            var currentThread = Thread.CurrentThread;

            sysInfo.ThreadId   = currentThread.ManagedThreadId;
            sysInfo.ThreadName = currentThread.Name;
            sysInfo.ThreadPool = AppInstance.GetThreadPool().ActiveThreads;

            return(sysInfo);
        }
Example #12
0
        static void Main(string[] args)
        {
            AppInstance.RegisterTypeAlias <LoadMemCachedStatsListener>();
            ObjectIOCFactory.GetSingleton <ApplicationHub>().Register <ExitCommandListener>(new ExitCommandListener());
            ApplicationHost.GetInstance(args).Start();

            var exitHanlder = new ConsoleExitHanlder();

            exitHanlder.Exit += new EventHandler((source, e) =>
            {
                ApplicationHost.GetInstance().Stop();
            });

            Console.ReadLine();
        }
Example #13
0
        private static void AssignOrCreateInstanceForFile(string filePath)
        {
            var instance = (GetLastActiveInstance() ?? AppInstance.FindOrRegisterInstanceForKey(App.Id.ToString()));

            if (instance.IsCurrentInstance)
            {
                App.IsFirstInstance = IsFirstInstance;
                Windows.UI.Xaml.Application.Start(p => new App());
                IsFirstInstance = false;
            }
            else
            {
                instance.RedirectActivationTo();
            }
        }
Example #14
0
        private static bool OnDeployInstance(ByteArray byteArray, IDeamonServerService serverService)
        {
            AppInstance instance = new AppInstance();

            instance.ReadFromByteArray(byteArray);

            int crc = byteArray.readIntNCRC();

            if (crc == byteArray.CRC)
            {
                serverService.OnDeployInstance(ref instance);
            }
            byteArray.Recycle();
            return(true);
        }
Example #15
0
        public void RunTest()
        {
            AppInstance.RegisterTypeAlias <TestApplication>();

            ObjectIOCFactory.GetSingleton <ApplicationHub>().Register <TestApplication>(new TestApplication()
            {
                Name = "TestApplicationForCode"
            });

            ApplicationHost.GetInstance().Init();

            ApplicationHost.GetInstance().Start();

            ApplicationHost.GetInstance().Stop();
        }
Example #16
0
        protected override void ExecuteCmdlet()
        {
            if (System.IO.File.Exists(Path))
            {
                if (Force)
                {
                    ClientContext.Site.ActivateFeature(Constants.APPSIDELOADINGFEATUREID);
                }
                AppInstance instance = null;

                FileStream appPackageStream = new FileStream(Path, FileMode.Open, FileAccess.Read);
                if (Locale == -1)
                {
                    if (LoadOnly)
                    {
                        instance = this.SelectedWeb.LoadApp(appPackageStream, CultureInfo.CurrentCulture.LCID);
                    }
                    else
                    {
                        instance = this.SelectedWeb.LoadAndInstallApp(appPackageStream);
                    }
                }
                else
                {
                    if (LoadOnly)
                    {
                        instance = this.SelectedWeb.LoadApp(appPackageStream, Locale);
                    }
                    else
                    {
                        instance = this.SelectedWeb.LoadAndInstallAppInSpecifiedLocale(appPackageStream, Locale);
                    }
                }
                ClientContext.Load(instance);
                ClientContext.ExecuteQuery();


                if (Force)
                {
                    ClientContext.Site.DeactivateFeature(Constants.APPSIDELOADINGFEATUREID);
                }
                WriteObject(instance);
            }
            else
            {
                WriteError(new ErrorRecord(new IOException(Properties.Resources.FileDoesNotExist), "1", ErrorCategory.InvalidArgument, null));
            }
        }
Example #17
0
        private static void Run()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            DebugHelper.WriteLine(Title);
            DebugHelper.WriteLine("Build: " + Build);
            DebugHelper.WriteLine("Command line: " + Environment.CommandLine);

            if (!string.IsNullOrEmpty(PersonalPathDetectionMethod))
            {
                DebugHelper.WriteLine("Personal path detection method: " + PersonalPathDetectionMethod);
            }

            DebugHelper.WriteLine("Personal path: " + PersonalFolder);
            DebugHelper.WriteLine("Operating system: " + Helpers.GetWindowsProductName());

            SilentRun = CLI.IsCommandExist("silent", "s");
#if WindowsStore
            SilentRun = SilentRun || AppInstance.GetActivatedEventArgs().Kind == ActivationKind.StartupTask;
#endif

#if STEAM
            SteamFirstTimeConfig = CLI.IsCommandExist("SteamConfig");
#endif

            IgnoreHotkeyWarning = CLI.IsCommandExist("NoHotkeys");

            CheckPuushMode();
            DebugWriteFlags();
            CleanTempFiles();

            SettingManager.LoadInitialSettings();

            Uploader.UpdateServicePointManager();
            UpdateManager = new GitHubUpdateManager("ShareX", "ShareX", Dev, Portable);

            LanguageHelper.ChangeLanguage(Settings.Language);

            Helpers.TryFixHandCursor();
            DebugHelper.WriteLine("MainForm init started.");
            MainForm = new MainForm();
            DebugHelper.WriteLine("MainForm init finished.");

            Application.Run(MainForm);

            CloseSequence();
        }
Example #18
0
        private async void sendMessage()
        {
            string      url     = Ultils.getUrl();
            string      content = messTextbox.Text;
            MessageSend mess    = new MessageSend()
            {
                Content        = content,
                ConversationId = this.ConversationId,
                Type           = 1
            };

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppInstance.getInstance().GetUser().Token);
                HttpResponseMessage response = client.PostAsJsonAsync("/api/Messages", mess).Result;
                if (!response.IsSuccessStatusCode)
                {
                    System.Windows.MessageBox.Show("Lá»—i khi gá»­i tin");
                }
            }
            messTextbox.Text = "";


            //send to hub
            Message hubmess = new Message()
            {
                ArrivalTime    = DateTimeOffset.Now,
                Content        = mess.Content,
                ConversationId = mess.ConversationId,
                Id             = 0,
                SenderId       = AppInstance.getInstance().GetUser().Id,
                Type           = mess.Type
            };

            string json = JsonConvert.SerializeObject(hubmess);

            try
            {
                await connection.InvokeAsync("SendMessage", "mess", json);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }
Example #19
0
 public App()
 {
     // The theme can only be changed in ctor
     AppViewModel = new AppViewModel(this)
     {
         AppSetting = AppContext.LoadSetting() ?? AppSetting.CreateDefault()
     };
     RequestedTheme = AppViewModel.AppSetting.Theme switch
     {
         ApplicationTheme.Dark => Microsoft.UI.Xaml.ApplicationTheme.Dark,
         ApplicationTheme.Light => Microsoft.UI.Xaml.ApplicationTheme.Light,
         _ => RequestedTheme
     };
     AppInstance.GetCurrent().Activated += (_, arguments) => ActivationRegistrar.Dispatch(arguments);
     InitializeComponent();
 }
Example #20
0
            private static bool StartupActivation()
            {
                if (Debugger.IsAttached)
                {
                    return(false);
                }

                try
                {
                    return(AppInstance.GetActivatedEventArgs()?.Kind == ActivationKind.StartupTask);
                }
                catch
                {
                    return(false);
                }
            }
Example #21
0
        static ModuleEnvironment()
        {
            UserNamePattern = GetValueFromConfig("passports:UserNamePattern", UserNamePattern);

            DefaultSecurityProvider = GetValueFromConfig("passports:Security.DefaultSecurityProvider", DefaultSecurityProvider);
            HashSalt         = GetValueFromConfig("passports:Security.HashSalt", HashSalt);
            EncryptSalt      = GetValueFromConfig("passports:Security.EncryptSalt", EncryptSalt);
            BCryptFactor     = GetValueFromConfig("passports:Security.BCryptFactor", BCryptFactor);
            MD5Factor        = GetValueFromConfig("passports:Security.MD5Factor", MD5Factor);
            WeakPasswords    = GetValueFromConfig("passports:Security.WeakPasswords", WeakPasswords);
            PasswordStrength = GetValueFromConfig("passports:Security.PasswordStrength", PasswordStrength);

            ThirdLinkedCacheName = GetValueFromConfig("third:LinkedCache", ThirdLinkedCacheName);

            AppInstance.RegisterTypeAlias <IIMProvider, EasemobProvider>(IMProviderName);
        }
Example #22
0
        static void Main(string[] args)
        {
            AppInstance.RegisterTypeAlias <QueueProcessor>();
            AppInstance.RegisterTypeAliasByModule <DatabaseListener>(AppConfig.LoggingKey);
            ObjectIOCFactory.GetSingleton <ApplicationHub>().Register <ExitCommandListener>(new ExitCommandListener());
            ApplicationHost.GetInstance(args).Start();

            var exitHanlder = new ConsoleExitHanlder();

            exitHanlder.Exit += new EventHandler((source, e) =>
            {
                ApplicationHost.GetInstance().Stop();
            });

            Console.ReadLine();
        }
Example #23
0
        public Broadcast(String rawData, AppInstance instance)
        {
            var dp = (MsgBroadcast)MsgBroadcast.Deserialize(rawData);
            guid = dp.Id;
            msgContent = dp.Content;

            var bcast = new MsgBroadcast();
            bcast.FromInstanceId = instance.InstanceId;
            bcast.Id = guid;
            bcast.Content = msgContent;

            msg = verb + ' ' + bcast.Serialize();

            this.FromInstance = instance;
            sendto = new List<AppInstance>();
        }
Example #24
0
        private static void Main()
        {
            if (mutex.WaitOne(TimeSpan.Zero, true))
            {
                InitializeLoggerConfig();

                try
                {
                                        #if (!DEBUG)
                    var args = AppInstance.GetActivatedEventArgs();
                    if (args != null)
                    {
                        //when the app was launched on system startup, Kind argument will be "StartupTask"
                        //otherwise i.e. when the app was launched normal way it will be "Launch"
                        if (args.Kind == ActivationKind.StartupTask)
                        {
                            StartMinimized = true;
                        }
                    }
                                        #endif

                    if (!StartMinimized)
                    {
                        foreach (var arg in Environment.GetCommandLineArgs())
                        {
                            if (arg == MinimizedArg)
                            {
                                //log the app version since the app launches with minimized arg only after it was updated
                                var ver = Package.Current.Id.Version;
                                LogManager.GetLogger(typeof(Startup))
                                .Info($"Started with {MinimizedArg} argument, ver.: [{ver.Major.ToString()}.{ver.Minor.ToString()}.{ver.Build.ToString()}.{ver.Revision.ToString()}]");
                                StartMinimized = true;
                            }
                        }
                    }
                }
                catch { }

                App.Main();
                mutex.ReleaseMutex();
            }
            else
            {
                NativeMethods.PostMessage((IntPtr)HWND_BROADCAST, WM_SHOWME, IntPtr.Zero,
                                          IntPtr.Zero);
            }
        }
Example #25
0
        private async void ReloadMember()
        {
            string      url            = Ultils.getUrl();
            List <long> userIds        = new List <long>();
            string      user           = "";
            long        conversationId = this.ConversationId;

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppInstance.getInstance().GetUser().Token);
                HttpResponseMessage response = client.GetAsync("/api/Conversations/Members?id=" + conversationId, HttpCompletionOption.ResponseContentRead).Result;
                //HttpResponseMessage response = client.PostAsJsonAsync("/api/ConversationsView/Members", AppInstance.getInstance().getUser().Id).Result;
                List <User> users = await response.Content.ReadAsAsync <List <User> >();

                foreach (User Conv_users in users)
                {
                    if (Conv_users.Id != AppInstance.getInstance().GetUser().Id)
                    {
                        userIds.Add(Conv_users.Id);
                    }
                }
            }

            foreach (long id in userIds)
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(url);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppInstance.getInstance().GetUser().Token);
                    HttpResponseMessage response = client.GetAsync("/api/Users/" + id, HttpCompletionOption.ResponseContentRead).Result;
                    User users = await response.Content.ReadAsAsync <User>();

                    user += users.Username + " ";
                    AppInstance.getInstance().SetFullname(users.Id, users.FullName);
                }
            }
            if (user.Length > 20)
            {
                user = user.Substring(0, 17) + "...";
            }
            this.Title = user;
        }
Example #26
0
        private void Bgworker_DoWork(object sender, DoWorkEventArgs e)
        {
            List <Contact> contactList = new List <Contact>();
            ObservableCollection <ContactListItem> contactItems = new ObservableCollection <ContactListItem>();

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(Ultils.url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppInstance.getInstance().GetUser().Token);
                HttpResponseMessage response = client.GetAsync("/api/Users/Owner/Contacts", HttpCompletionOption.ResponseContentRead).Result;
                if (response.IsSuccessStatusCode)
                {
                    contactList = response.Content.ReadAsAsync <List <Contact> >().Result;
                }
            }

            foreach (Contact contact in contactList)
            {
                if (contact.Status == 0)
                {
                    long id = contact.FromUserId;
                    if (id == AppInstance.getInstance().GetUser().Id)
                    {
                        continue;
                    }
                    using (HttpClient client = new HttpClient())
                    {
                        client.BaseAddress = new Uri(Ultils.url);
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppInstance.getInstance().GetUser().Token);
                        HttpResponseMessage response = client.GetAsync("/api/Users/" + id, HttpCompletionOption.ResponseContentRead).Result;
                        User users = response.Content.ReadAsAsync <User>().Result;
                        AppInstance.getInstance().SetFullname(users.Id, users.FullName);
                        contactItems.Add(new ContactListItem()
                        {
                            FromUserId = id,
                            Username   = AppInstance.getInstance().GetFullname(contact.ToUserId),
                            Status     = 0
                        });
                    }
                }
            }
            e.Result = contactItems;
        }
Example #27
0
        static void Main(string[] args)
        {
            IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

            if (activatedArgs is ToastNotificationActivatedEventArgs)
            {
                return;
            }

            if (activatedArgs is CommandLineActivatedEventArgs CmdActivate)
            {
                if (CmdActivate.Operation.Arguments.StartsWith("RX-Explorer.exe"))
                {
                    if (AppInstance.RecommendedInstance != null)
                    {
                        AppInstance.RecommendedInstance.RedirectActivationTo();
                    }
                    else if (ApplicationData.Current.LocalSettings.Values["LastActiveGuid"] is string LastGuid &&
                             !string.IsNullOrWhiteSpace(LastGuid) &&
                             AppInstance.FindOrRegisterInstanceForKey(LastGuid) is AppInstance TargetInstance &&
                             !TargetInstance.IsCurrentInstance)
                    {
                        TargetInstance.RedirectActivationTo();
                    }
                    else if (AppInstance.GetInstances().FirstOrDefault() is AppInstance ExistInstance)
                    {
                        ExistInstance.RedirectActivationTo();
                    }
                    else
                    {
                        string      InstanceId = Guid.NewGuid().ToString();
                        AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                        ApplicationData.Current.LocalSettings.Values["LastActiveGuid"] = InstanceId;

                        Application.Start((p) => new App());
                    }
                }
                else
                {
                    string      InstanceId = Guid.NewGuid().ToString();
                    AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                    ApplicationData.Current.LocalSettings.Values["LastActiveGuid"] = InstanceId;

                    Application.Start((p) => new App());
                }
            }
Example #28
0
        private static string ParseDeployInstance(ByteArray byteArray)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("DeployInstance(");

            sb.Append("instance : AppInstance");

            sb.Append("){\r\n");
            int         crc__    = byteArray.readIntNCRC(); // parse global seq
            AppInstance instance = new AppInstance();

            instance.ReadFromByteArray(byteArray);
            sb.AppendFormat(@"instance = ""{0}""", instance);
            sb.Append("}");
            return(sb.ToString());
        }
Example #29
0
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            var isProtocolActivated = AppInstance.GetCurrent().GetActivatedEventArgs() is { Kind : ExtendedActivationKind.Protocol };

            if (isProtocolActivated && AppInstance.GetInstances().Count > 1)
            {
                var notCurrent = AppInstance.GetInstances().First(ins => !ins.IsCurrent);
                await notCurrent.RedirectActivationToAsync(AppInstance.GetCurrent().GetActivatedEventArgs());

                return;
            }

            Current.Resources[ApplicationWideFontKey] = new FontFamily(AppViewModel.AppSetting.AppFontFamilyName);
            await AppKnownFolders.InitializeAsync();

            await AppViewModel.InitializeAsync(isProtocolActivated);
        }
Example #30
0
        private async Task SetupHubConnectionAsync()
        {
            string url = Ultils.url + "chathub";

            connection = new HubConnectionBuilder()
                         .WithUrl(url)
                         .Build();

            connection.Closed += async(error) =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);

                await connection.StartAsync();
            };


            connection.On <string, string>("ReceiveMessage", (type, message) =>
            {
                if (type.Equals("call"))
                {
                    long cvid = long.Parse(message.Split('-')[0]);

                    Conversation cv = AppInstance.getInstance().GetConversations().Where(x => x.Id == cvid).First();
                    if (cv != null)
                    {
                        long userid = long.Parse(message.Split('-')[1]);
                        CallList.Add(new CallPanelItem()
                        {
                            Cvid   = cvid,
                            Name   = cv.Name + " has a Calling ",
                            Userid = userid
                        });
                    }
                    lvCall.ItemsSource = CallList;
                }
            });

            try
            {
                await connection.StartAsync();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }
Example #31
0
        public static void DeployInstance(AppInstance instance, ref ByteArray byteArray)
        {
            byteArray.Reset();
            byteArray.WriteHeader();


            byteArray.writeInt(EnumDeamonMethods.SERVER_DEPLOYINSTANCE_HASH);
            byteArray.EncryptKey = EnumDeamonMethods.SERVER_DEPLOYINSTANCE_HASH;
            byteArray.CRC        = 0;
            byteArray.writeDynamicsInt(ByteArray.globalSeq);

            instance.WriteToByteArray(byteArray);

            ++ByteArray.globalSeq;
            byteArray.writeIntNCRC(byteArray.CRC);
            byteArray.EncryptKey = 0;
        }
Example #32
0
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary launchOptions)
        {
            NSUrlCache.SharedCache.RemoveAllCachedResponses();

            UIView.AppearanceWhenContainedIn(new [] { typeof(UIAlertController) }).TintColor = new UIColor((nfloat)0x06 / 0xFF, (nfloat)0x6A / 0xFF, (nfloat)0xB9 / 0xFF, 1.0f);

            App.InitializeServiceLocator(RegisterPlatformTypes);

            InitializeExposureNotificationClient();

            Xamarin.Forms.Forms.SetFlags("RadioButton_Experimental");

            global::Xamarin.Forms.Forms.Init();
            global::Xamarin.Forms.FormsMaterial.Init();

            FFImageLoading.Forms.Platform.CachedImageRenderer.Init();
            global::FFImageLoading.ImageService.Instance.Initialize(new FFImageLoading.Config.Configuration());


            _notificationCenterDelegate.OnRecieved += async(UserNotificationCenterDelegate sender, UNNotificationResponse response) =>
            {
                var navigationParameters = new NavigationParameters();
                await AppInstance?.NavigateToSplashAsync(Destination.ContactedNotifyPage, navigationParameters);
            };
            UNUserNotificationCenter.Current.Delegate = _notificationCenterDelegate;

            LoadApplication(new App());

            if (!IsUniversalLinks(launchOptions) && !IsLocalNotification(launchOptions))
            {
                InvokeOnMainThread(async() => await AppInstance?.NavigateToSplashAsync(Destination.HomePage, new NavigationParameters()));
            }

            UIApplication.SharedApplication.SetMinimumBackgroundFetchInterval(UIApplication.BackgroundFetchIntervalMinimum);

            try
            {
                _exposureDetectionBackgroundService.Value.Schedule();
            }
            catch (Exception exception)
            {
                _loggerService.Value.Exception("failed to Scheduling", exception);
            }

            return(base.FinishedLaunching(app, launchOptions));
        }
        private static void GetActivationInfo()
        {
            AppActivationArguments args = AppInstance.GetCurrent().GetActivatedEventArgs();
            ExtendedActivationKind kind = args.Kind;

            OutputMessage($"ActivationKind: {kind}");

            if (kind == ExtendedActivationKind.Launch)
            {
                if (args.Data is ILaunchActivatedEventArgs launchArgs)
                {
                    string   argString  = launchArgs.Arguments;
                    string[] argStrings = argString.Split();
                    foreach (string arg in argStrings)
                    {
                        if (!string.IsNullOrWhiteSpace(arg))
                        {
                            OutputMessage(arg);
                        }
                    }
                }
            }
            else if (kind == ExtendedActivationKind.File)
            {
                if (args.Data is IFileActivatedEventArgs fileArgs)
                {
                    IStorageItem file = fileArgs.Files.FirstOrDefault();
                    OutputMessage(file.Name);
                }
            }
            else if (kind == ExtendedActivationKind.Protocol)
            {
                if (args.Data is IProtocolActivatedEventArgs protocolArgs)
                {
                    Uri uri = protocolArgs.Uri;
                    OutputMessage(uri.AbsoluteUri);
                }
            }
            else if (kind == ExtendedActivationKind.StartupTask)
            {
                if (args.Data is IStartupTaskActivatedEventArgs startupArgs)
                {
                    OutputMessage(startupArgs.TaskId);
                }
            }
        }
Example #34
0
        /// <summary>
        /// Parses a Mycroft command from a JSON object
        /// </summary>
        /// <returns>
        /// Returns the Command object that needs to be routed through the system
        /// </returns>
        public static Command Parse(String input, AppInstance instance)
        {
            // TODO error handling - catch exceptions, then create a new Command
            // that contains the error to send back

            // Break the message body into the type token and the JSON blob,
            // then delegate to the specific command parser (MsgCmd.Parse(), AppCmd.Parse(), etc.)
            String type = getType(input);

            try
            {
                if (type != null)
                {
                    var startJson = input.IndexOf('{');
                    string rawData = startJson < 0 ? "" : input.Substring(startJson);

                    if (type.StartsWith("MSG"))
                    {
                        return MsgCommand.Parse(type, rawData, instance);
                    }
                    else if (type.StartsWith("APP"))
                    {
                        return AppCommand.Parse(type, rawData, instance);
                    }
                    else if (type.StartsWith("SYS"))
                    {
                        return SysCommand.Parse(type, rawData, instance);
                    }
                }
                throw new ParseException(input, "Unknown input");
            }
            catch (ParseException ex)
            {
                if (instance != null)
                {
                    var log = Logger.GetInstance();
                    log.Warning(String.Format(
                        "Failed to parse command from {0} for reason: {1}",
                        instance.InstanceId,
                        ex.Message
                    ));
                    log.Warning("Content received: " + input);
                }
                return new Msg.GeneralFailure(ex, instance);
            }
        }
Example #35
0
        private void ConversationWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ObservableCollection <ConversationsView> conversationviews = e.Result as ObservableCollection <ConversationsView>;

            bool isNew = false;

            if (conversationviews.Count == History.Count)
            {
                foreach (var i in conversationviews)
                {
                    ConversationsView cv = History.Where(x => x.Text == i.Text).FirstOrDefault();
                    if (cv == null)
                    {
                        isNew = true;
                        break;
                    }
                    cv = History.Where(x => x.Mess == i.Mess).FirstOrDefault();
                    if (cv == null)
                    {
                        if (History.Count != 0 && i.MessUserId != AppInstance.getInstance().GetUser().Id) //lúc start ko bold và là ng r ko bold
                        {
                            i.fontWeight = "Normal";                                                      //bold nhé
                        }
                        else
                        {
                            i.fontWeight = "Normal";
                        }
                        isNew = true;
                        break;
                    }
                }
            }
            else
            {
                isNew = true;
            }

            if (isNew /* && !SearchText.Equals("")*/) // và ko phải là đang search
            {
                History = conversationviews;
                lvHistory.ItemsSource = History;
            }

            ConversationWorker.RunWorkerAsync(6000);
        }
Example #36
0
        static void Main(string[] args)
        {
            _instances = AppInstance.GetInstances();

            if (_instances.Count == 0)
            {
                IsFirstInstance = true;
                ApplicationSettingsStore.Write("ActiveInstance", null);
            }

            IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

            if (activatedArgs is FileActivatedEventArgs)
            {
                AssignOrCreateInstance();
            }
            else if (activatedArgs is CommandLineActivatedEventArgs cmdActivatedArgs)
            {
                LoggingService.LogInfo($"[Main] [CommandActivated] CurrentDirectoryPath: {cmdActivatedArgs.Operation.CurrentDirectoryPath} Arguments: {cmdActivatedArgs.Operation.Arguments}");

                var file = FileSystemUtility.GetAbsolutePathFromCommandLine(
                    cmdActivatedArgs.Operation.CurrentDirectoryPath, cmdActivatedArgs.Operation.Arguments, App.ApplicationName);
                if (file != null)
                {
                    AssignOrCreateInstance();
                }
                else
                {
                    OpenNewInstance();
                }
            }
            else if (activatedArgs is ProtocolActivatedEventArgs protocolActivatedEventArgs)
            {
                LoggingService.LogInfo($"[Main] [ProtocolActivated] Protocol: {protocolActivatedEventArgs.Uri}");
                var protocol = NotepadsProtocolService.GetOperationProtocol(protocolActivatedEventArgs.Uri, out var context);
                if (protocol == NotepadsOperationProtocol.OpenNewInstance || protocol == NotepadsOperationProtocol.Unrecognized)
                {
                    OpenNewInstance();
                }
            }
            else
            {
                OpenNewInstance();
            }
        }
Example #37
0
 /// <summary>
 /// Parses JSON into message command objects
 /// </summary>
 /// <param name="messageType">The message type that determines the command to create</param>
 /// <param name="json">The JSON body of the message</param>
 /// <returns>Returns a command object for the parsed message</returns>
 public static Command Parse(String type, String rawData, AppInstance instance)
 {
     switch (type)
     {
         case "MSG_BROADCAST":
             return new Broadcast(rawData, instance);
         case "MSG_QUERY":
             return Query.Parse(rawData, instance);
         case "MSG_QUERY_SUCCESS":
             return new Reply(rawData, instance);
         case "MSG_QUERY_FAIL":
             return new QueryFail(rawData, instance);
         default:
             //TODO: notify if data does not meet format
             break;
     }
     return null;
 }
Example #38
0
        public async Task <InvokeResult <AppInstance> > CreateForUserAsync(string appUserId, AuthRequest authRequest)
        {
            authRequest.AppInstanceId = Guid.NewGuid().ToId();
            var appInstance = new AppInstance(authRequest.AppInstanceId, appUserId);

            appInstance.UserId     = appUserId;
            appInstance.AppId      = authRequest.AppId;
            appInstance.DeviceId   = authRequest.DeviceId;
            appInstance.ClientType = authRequest.ClientType;

            appInstance.CreationDate           = DateTime.UtcNow.ToJSONString();
            appInstance.LastAccessTokenRefresh = DateTime.UtcNow.ToJSONString();
            appInstance.LastLogin = DateTime.UtcNow.ToJSONString();

            await _appInstanceRepo.AddAppInstanceAsync(appInstance);

            return(InvokeResult <AppInstance> .Create(appInstance));
        }
Example #39
0
 /// <summary>
 /// Parses JSON into system command objects
 /// </summary>
 /// <param name="messageType">The message type that determines the command to create</param>
 /// <param name="json">The JSON body of the message</param>
 /// <returns>Returns a command object for the parsed message</returns>
 public static Command Parse(String type, String rawData, AppInstance instance)
 {
     switch (type)
     {
         case "SYS_KILLAPP":
             return new KillAll(rawData, instance);
         case "SYS_SHUTDOWN":
             return new ShutOff(rawData, instance);
         case "SYS_LOCKDOWN":
             return new Lockdown(rawData, instance);
         case "SYS_UNLOCK":
             return new SysUnlock(rawData, instance);
         default:
             //TODO: notify if data does not conform
             break;
     }
     return null;
 }
Example #40
0
 void queue_ReceiveCompleted(object message)
 {
     AppInstance.GetThreadPool().QueueWorkItem(() =>
     {
         if (false == (message is ILogEntry))
         {
             var filePath = string.Format("logs\\{0}-{1}.log", message.GetType().Name, DateTime.Now.ToString("yyyy-MM-dd-hh"));
             var content  = message.ToText();
             Console.WriteLine(content);
             FileHelper.WriteInfo(filePath, content);
         }
         else
         {
             SaveLogEntry(message as ILogEntry);
         }
     });
     queue.BeginReceive();
 }
Example #41
0
        private void BtnLogin_Click(object sender, RoutedEventArgs e)
        {
            WritePassword();
            LoginAsync().Wait();
            if (AppInstance.getInstance().GetUser().Id != 0)
            {
                MainChatWindown main = new MainChatWindown();
                main.Show();

                //ChatHub hub = new ChatHub();
                //hub.Show();

                Close();
            }

            //VideocallWindown windown = new VideocallWindown();
            //windown.Show();
        }
Example #42
0
 /// <summary>
 /// Parses JSON into App command objects
 /// </summary>
 /// <param name="messageType">The message type that determines the command to create</param>
 /// <param name="json">The JSON body of the message</param>
 /// <returns>Returns a command object for the parsed message</returns>
 public static Command Parse(String type, String json, AppInstance instance)
 {
     switch (type)
     {
         case "APP_UP":
             return new DependencyChange(instance, Status.up);
         case "APP_DOWN":
             return new DependencyChange(instance, Status.down);
         case "APP_IN_USE":
             return new DependencyChange(instance, Status.in_use);
         case "APP_MANIFEST":
             return Manifest.Parse(json, instance);
         default:
             //data is incorrect - can't do anything with it
             // TODO notify that is wrong
             break;
     }
     return null ;
 }
Example #43
0
        private async void LoadHub()
        {
            string url = Ultils.url + "callhub";

            connection = new HubConnectionBuilder()
                         .WithUrl(url)
                         .WithAutomaticReconnect()
                         .Build();
            connection.Closed += async(error) =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);

                await connection.StartAsync();
            };
            connection.Reconnecting += error =>
            {
                return(Task.CompletedTask);
            };

            connection.On <string>("ReceiveMessage", (message) =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    string id   = message.Split('\0')[0];
                    string mess = message.Split('\0')[1];
                    if (long.Parse(id) != AppInstance.getInstance().GetUser().Id)
                    {
                        mainCall.Source = ImageSupportInstance.getInstance().ConvertFromBaseString(mess);
                    }
                });
            });

            try
            {
                await connection.StartAsync();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }

            await connection.InvokeAsync("AddToGroup", ConversationId.ToString());
        }
Example #44
0
 public static AppCommand Parse(string json, AppInstance instance)
 {
     AppManifest mfst;
     try
     {
         mfst = AppManifest.Deserialize(json) as AppManifest;
     }
     catch (ParseException ex)
     {
         if (instance != null)
         {
             var log = Logger.GetInstance();
             log.Warning(String.Format(
                 "Invalid manifest was sent by app {0} reason: {1}",
                 instance.InstanceId,
                 ex.Message
             ));
         }
         return new ManifestFail(ex.ToString(), instance);
     }
     return new Create(mfst, instance);
 }
Example #45
0
 protected void Setup(string input)
 {
     console = new TestConsole(input);
     testInst = AppInstance.Get().ForTests((method, argTypes, args) => {
         var call = new object[] { console, console.In, console.Out }.Select(x => new { t = x, m = x.GetType().GetMethod(method, argTypes) }).Where(x => x.m != null).First();
         return call.m.Invoke(call.t, args);
     });
 }
Example #46
0
 private void sendQueryTo(AppInstance other)
 {
     var toSend = "MSG_QUERY " + this.query.Serialize();
     other.Send(toSend);
 }
Example #47
0
 public DirectedQuery(MsgQuery query, AppInstance instance)
     : base(query, instance)
 {
 }
Example #48
0
 public Lockdown(String rawData, AppInstance instance)
 {
     this.instance = instance;
 }
Example #49
0
 public QueryFail(string data, AppInstance instance)
 {
     Instance = instance;
 }
Example #50
0
 public KillAll(String rawData, AppInstance instance)
 {
     this.instance = instance;
 }
Example #51
0
 public AppPipeBind(AppInstance instance)
 {
     _appInstance = instance;
 }
Example #52
0
 /// <summary>
 /// Put a newly connected app in its own thread in the app thread pool
 /// </summary>
 /// <param name="connection"></param>
 private void HandleNewClientConnection(CommandConnection connection)
 {
     var instance = new AppInstance(connection, this);
     instance.Listen();
 }
Example #53
0
 /// <summary>
 /// Used to notify that an app instance has gone down
 /// </summary>
 /// <param name="instance"></param>
 public DependencyChange(AppInstance instance, Status status)
 {
     this.instance = instance;
     instance.AppStatus = status;
     Log = Logger.GetInstance();
 }
Example #54
0
 public Destroy(AppInstance instance)
 {
     this.instance = instance;
     this.Log = Logger.GetInstance();
 }
Example #55
0
 public virtual void VisitAppInstance(AppInstance appInstance)
 {
 }
Example #56
0
        /// <summary>
        /// Adds an instance to the registry
        /// </summary>
        /// <param name="instance"></param>
        /// <returns>Returns true if the instance has been registered,
        /// false if the instance is already in use</returns>
        public bool Register(AppInstance instance)
        {
            // Make sure the instance ID isn't already in use
            if(instances.ContainsKey(instance.InstanceId))
            {
                return false;
            }

            instances[instance.InstanceId] = instance;
            var capabilities = instance.Capabilities;
            foreach (var capability in capabilities)
            {
                // Add the capability if it isn't known
                if(!providers.ContainsKey(capability))
                {
                    providers[capability] = new SortedSet<string>();
                }
                providers[capability].Add(instance.InstanceId);
            }

            var dependencies = instance.Dependencies;
            foreach (var dependency in dependencies)
            {
                // Add the dependency if it isn't known
                if (!dependents.ContainsKey(dependency))
                {
                    dependents[dependency] = new SortedSet<string>();
                }
                dependents[dependency].Add(instance.InstanceId);
            }

            return true;
        }
Example #57
0
 /// <summary>
 /// Retrives an app instance with that ID
 /// </summary>
 /// <param name="instanceId"></param>
 /// <param name="outInstance"></param>
 /// <returns></returns>
 public bool TryGetInstance(string instanceId, out AppInstance outInstance)
 {
     return instances.TryGetValue(instanceId, out outInstance);
 }
Example #58
0
        /// <summary>
        /// Removes an app from the registry, used when an instance disconnects
        /// </summary>
        /// <param name="instance"></param>
        /// <return>Returns true if the instance was removed, and false
        /// if it was not found in the registry</return>
        public bool Remove(AppInstance instance)
        {
            foreach (var capability in instance.Capabilities)
            {
                if (providers[capability].Contains(instance.InstanceId))
                    providers[capability].Remove(instance.InstanceId);
            }
            foreach (var dependency in instance.Dependencies)
            {
                if (dependents[dependency].Contains(instance.InstanceId))
                    dependents[dependency].Remove(instance.InstanceId);
            }

            return instances.Remove(instance.InstanceId);
        }
Example #59
0
 public SysUnlock(String rawData, AppInstance instance)
 {
     this.instance = instance;
 }
Example #60
0
 public DependencyList(AppInstance instance)
 {
     this.instance = instance;
 }