Exemple #1
0
        //private void InitSocket()
        //{
        //    var business = ApplicationObject.App.Business;
        //    var ip = ConfigurationManager.AppSettings["OrderNotifyIp"];
        //    var port = int.Parse(ConfigurationManager.AppSettings["OrderNotifyPort"]);
        //    IPHostEntry ipHostInfo = Dns.GetHostEntry(ip);
        //    IPAddress ipAddress = ipHostInfo.AddressList[0];
        //    IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
        //    Socket = new Socket(remoteEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        //    Socket.BeginConnect(remoteEP,
        //        new AsyncCallback(ConnectCallback), Socket);
        //    connectDone.WaitOne();
        //    if (!InitSuccess) return;
        //    Send(Socket, business.ID.ToString());

        //    Receive(Socket);

        //}

        //private void ConnectCallback(IAsyncResult ar)
        //{
        //    try
        //    {
        //        Socket client = (Socket)ar.AsyncState;

        //        client.EndConnect(ar);
        //        connectDone.Set();
        //    }
        //    catch (Exception e)
        //    {
        //        MessageBox.Show("新订单提醒连接异常:" + e.Message);
        //        InitSuccess = false;
        //        connectDone.Set();
        //    }
        //}

        //private void Receive(Socket client)
        //{
        //    try
        //    {
        //        StateObject state = new StateObject();
        //        state.workSocket = client;

        //        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        //    }
        //    catch (Exception e)
        //    {
        //        MessageBox.Show("新订单消息监听异常:" + e.Message);
        //    }
        //}

        //private void ReceiveCallback(IAsyncResult ar)
        //{
        //    StateObject state = (StateObject)ar.AsyncState;
        //    Socket client = state.workSocket;
        //    try
        //    {
        //        var position = client.EndReceive(ar);
        //        string code = Encoding.UTF8.GetString(state.buffer, 0, position);
        //        var req = Request.GetOrder(code);
        //        var order = req.Result;
        //        if (order != null)
        //        {
        //            this.Dispatcher.Invoke(() =>
        //            {
        //                ApplicationObject.Print(order);
        //            });
        //            var filename = string.Empty;
        //            if (order.Status == Enum.OrderStatus.Payed)
        //            {
        //                filename = "1.mp3";
        //            }
        //            else if (order.Status == Enum.OrderStatus.Receipted)
        //            {
        //                filename = "2.mp3";
        //            }
        //            var player = new MediaPlayer();
        //            player.Open(new Uri("Assets/Video/" + filename, UriKind.Relative));
        //            player.Play();
        //            player.Volume = 1;
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        MessageBox.Show("新订单消息接收异常:" + e.Message);
        //    }
        //    finally
        //    {
        //        state.buffer = new byte[StateObject.BufferSize];
        //        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        //    }
        //}

        //private static void Send(Socket client, String data)
        //{
        //    byte[] byteData = Encoding.ASCII.GetBytes(data);

        //    client.BeginSend(byteData, 0, byteData.Length, 0,
        //        new AsyncCallback(SendCallback), client);
        //}

        //private static void SendCallback(IAsyncResult ar)
        //{
        //    try
        //    {
        //        Socket client = (Socket)ar.AsyncState;

        //        client.EndSend(ar);
        //    }
        //    catch (Exception e)
        //    {
        //        MessageBox.Show("新订单提示匹配异常:" + e.Message);
        //    }
        //}

        #endregion

        #region websocket连接
        /// <summary>
        /// 初始化Socket连接
        /// </summary>
        //private void InitWebSocket()
        //{
        //    socket = new WebSocket(socketLink);
        //    socket.Connect();
        //    socket.OnMessage += MessageHandler;
        //    socket.OnClose += (sender, e) =>
        //    {
        //        if (e.Code == 1000)
        //        {
        //            MessageBox.Show(e.Reason);
        //        }
        //        else
        //        {
        //            var isSuccess = Connect();
        //            if (!isSuccess)
        //            {
        //                IsConnect = false;
        //                PlayMedia("Assets/Video/4.mp3");
        //                //while (MessageBox.Show($"网络异常,新订单提醒已关闭,点击确定后重新连接", "通信异常", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
        //                //{
        //                //    if(Connect())
        //                //    {
        //                //        MessageBox.Show("已成功连接");
        //                //        break;
        //                //    }
        //                //}
        //                ThreadPool.QueueUserWorkItem(obj =>
        //                {
        //                    var index = 0;
        //                    var control = (MainWindow)obj;
        //                    while (!control.IsConnect)
        //                    {
        //                        if (InternetGetConnectedState(out index, 0))
        //                        {
        //                            ((Control)obj).Dispatcher.Invoke(() =>
        //                            {
        //                                var result = Connect();
        //                                if (result)
        //                                {
        //                                    MessageBox.Show("新订单提醒已恢复正常");
        //                                    control.IsConnect = true;
        //                                    return;
        //                                }
        //                            });
        //                        }
        //                    }
        //                }, this);
        //            }
        //        }
        //    };
        //}


        ///// <summary>
        ///// 连接断开后重新连接
        ///// </summary>
        ///// <returns></returns>
        //private bool Connect()
        //{
        //    // 尝试2次连接
        //    var times = 2;
        //    for (int i = 0; i < times; i++)
        //    {
        //        InitWebSocket();
        //        if (socket.ReadyState == WebSocketState.Open)
        //        {
        //            return true;
        //        }
        //        // 每次连接后等待10秒再连
        //        Thread.Sleep(10000);
        //    }
        //    return false;
        //}

        private async void MessageHandler(object sender, MessageEventArgs e)
        {
            try
            {
                var buffer = new byte[512];
                var code   = e.Data;
                code = code.Split('|')[0];
                var order = await Request.GetOrder(code);

                this.Dispatcher.Invoke(() =>
                {
                    var filename = string.Empty;
                    if (order.Status == Enum.OrderStatus.Payed)
                    {
                        filename = "1.mp3";
                    }
                    else
                    {
                        filename = "2.mp3";
                    }
                    PlayMedia("Assets/Video/" + filename);
                    ApplicationObject.Print(order);
                }, DispatcherPriority.Normal);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #2
0
        private static bool BackupApplication(ApplicationObject application)
        {
            var backupDirectory = Settings.My.BackupDirectory;

            var applicationBackupDirectory = Path.Combine(backupDirectory, application.Type, string.Format("{0}.{1:yyyyMMdd}", application.Name, DateTime.Now));

            if (Directory.Exists(applicationBackupDirectory))
            {
                return(false);
            }

            Directory2.CopyDirectory(application.FullPath, applicationBackupDirectory, true);

            LoadBackupVersions(backupDirectory, application);

            var deleteBackupVersions = application.Backups.Skip(Settings.My.ApplicationMaxBackups).ToArray();

            if (deleteBackupVersions.Any())
            {
                foreach (var backup in deleteBackupVersions)
                {
                    if (Directory.Exists(backup.FullPath))
                    {
                        Directory.Delete(backup.FullPath, true);
                    }
                    application.Backups.Remove(backup);
                }
            }

            return(true);
        }
Exemple #3
0
        /// <summary>
        /// Activates or deactivates the specified users
        /// </summary>
        /// <param name="users"></param>
        /// <param name="activate"></param>
        public static void ActivateUsers(IEnumerable<string> users, bool activate)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                StringBuilder args = new StringBuilder(512);
                args.Append("-users -activate:");
                if (activate)
                    args.Append("yes");
                else
                    args.Append("no");

                foreach (string user in users)
                {
                    args.Append(" \"");
                    args.Append(user);
                    args.Append('"');
                }

                ProcessStartInfo p = new ProcessStartInfo(a.Path, args.ToString());
                p.UseShellExecute = true;
                p.Verb = "runas";

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Deletes all gw2cache-{*} folders located in the specified folder
        /// </summary>
        /// <param name="roots">Folders containing gw2cache folders</param>
        public static void DeleteCacheFolders(IEnumerable <string> roots)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                StringBuilder args = new StringBuilder(512);

                args.Append("-pu -delgw2cache");

                foreach (string root in roots)
                {
                    args.Append(" \"");
                    args.Append(root);
                    args.Append('"');
                }

                ProcessStartInfo p = new ProcessStartInfo(a.Path, args.ToString());
                p.UseShellExecute = true;
                p.Verb            = "runas";

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Creates the user's home folders
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public static void InitializeAccount(string username, System.Security.SecureString password)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                try
                {
                    //other users will be using this
                    Util.FileUtil.AllowFileAccess(a.Path, System.Security.AccessControl.FileSystemRights.Modify);
                }
                catch (Exception ex)
                {
                    Util.Logging.Log(ex);
                }

                ProcessStartInfo p = new ProcessStartInfo(a.Path, "-pu -userinit");

                p.UseShellExecute  = false;
                p.UserName         = username;
                p.LoadUserProfile  = true;
                p.Password         = password;
                p.WorkingDirectory = DataPath.AppDataAccountData; //Path.GetPathRoot(a.Path);

                //creating the user's profile will be handled by Windows
                //the process doesn't actually do anything itself

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Creates the folder with all users modify rights
        /// </summary>
        public static bool CreateFolder(string path)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                StringBuilder args = new StringBuilder(512);

                args.Append("-pu -folder \"");
                args.Append(path);
                args.Append('"');

                ProcessStartInfo p = new ProcessStartInfo(a.Path, args.ToString());
                p.UseShellExecute = true;
                p.Verb            = "runas";

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();

                    return(proc.ExitCode == 0);
                }
                else
                {
                    return(false);
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Creates the scheduled tasks "gw2launcher-users-active-yes" and "gw2launcher-users-active-no"
        /// that start this program with the options -users:active:yes or -users:active:no as
        /// a high priviledge user
        /// </summary>
        public static bool CreateInactiveUsersTask()
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                string path1 = Path.GetTempFileName();
                string path2 = Path.GetTempFileName();

                try
                {
                    string _xml1, _xml2;

                    _xml1 = Properties.Resources.Task.Replace("{path}", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

                    _xml2 = _xml1.Replace("{args}", "-users:active:no");
                    _xml1 = _xml1.Replace("{args}", "-users:active:yes");

                    File.WriteAllText(path1, _xml1);
                    File.WriteAllText(path2, _xml2);

                    StringBuilder args = new StringBuilder(512);
                    args.Append("-pu -task -create \"gw2launcher-users-active-yes\" \"");
                    args.Append(path1);
                    args.Append("\" \"gw2launcher-users-active-no\" \"");
                    args.Append(path2);
                    args.Append('"');

                    ProcessStartInfo p = new ProcessStartInfo(a.Path, args.ToString());
                    p.UseShellExecute = true;
                    p.Verb            = "runas";

                    Process proc = Process.Start(p);
                    if (proc != null)
                    {
                        proc.WaitForExit();
                        return(proc.ExitCode == 0);
                    }

                    return(false);
                }
                finally
                {
                    try
                    {
                        File.Delete(path1);
                    }
                    catch (Exception ex)
                    {
                        Util.Logging.Log(ex);
                    }
                    try
                    {
                        File.Delete(path2);
                    }
                    catch (Exception ex)
                    {
                        Util.Logging.Log(ex);
                    }
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Activates or deactivates the specified users
        /// </summary>
        /// <param name="users"></param>
        /// <param name="activate"></param>
        public static void ActivateUsers(IEnumerable <string> users, bool activate)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                StringBuilder args = new StringBuilder(512);
                args.Append("-pu -users -activate:");
                if (activate)
                {
                    args.Append("yes");
                }
                else
                {
                    args.Append("no");
                }

                foreach (string user in users)
                {
                    args.Append(" \"");
                    args.Append(user);
                    args.Append('"');
                }

                ProcessStartInfo p = new ProcessStartInfo(a.Path, args.ToString());
                p.UseShellExecute = true;
                p.Verb            = "runas";

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }
Exemple #9
0
        protected override void Loaded(object sender, RoutedEventArgs e)
        {
            var applicationsDirectory = Settings.My.ApplicationsDirectory;
            var applicationTypes      = Settings.My.ApplicationTypes;
            var backupDirectory       = Settings.My.BackupDirectory;

            foreach (var applicationType in applicationTypes)
            {
                var applicationTypeDirectory = new DirectoryInfo(Path.Combine(applicationsDirectory, applicationType));
                if (!applicationTypeDirectory.Exists)
                {
                    continue;
                }

                var applicationDirectories = applicationTypeDirectory.GetDirectories("*", SearchOption.TopDirectoryOnly);
                foreach (var applicationDirectory in applicationDirectories)
                {
                    var application = new ApplicationObject()
                    {
                        Type           = applicationTypeDirectory.Name,
                        Name           = applicationDirectory.Name,
                        LastModifiedAt = applicationDirectory.LastWriteTime
                    };

                    application.FullPath = applicationDirectory.FullName;

                    LoadBackupVersions(backupDirectory, application);

                    _applications.Add(application);
                }
            }

            _applications = _applications.OrderBy(x => x.Type).ThenBy(x => x.Name).ToList();
            Search();
        }
        private void InsertPropertyField(ApplicationObject metaObject, SqlFieldInfo fieldInfo)
        {
            IApplicationObjectFactory factory = MetadataManager.GetFactory(metaObject.GetType());

            if (factory == null)
            {
                return;
            }

            string propertyName = factory.PropertyFactory.GetPropertyName(fieldInfo);

            if (string.IsNullOrEmpty(propertyName))
            {
                propertyName = fieldInfo.COLUMN_NAME;
            }

            // Проверка нужна для свойств, имеющих составной тип данных
            MetadataProperty property = metaObject.Properties.Where(p => p.Name == propertyName).FirstOrDefault();

            if (property == null)
            {
                property = factory.PropertyFactory.CreateProperty(metaObject, propertyName, fieldInfo);
                metaObject.Properties.Add(property);
            }
            else if (property.Fields.Where(f => f.Name == fieldInfo.COLUMN_NAME).FirstOrDefault() != null)
            {
                return; // поле добавлять не надо
            }

            property.Fields.Add(factory.PropertyFactory.CreateField(fieldInfo));
        }
Exemple #11
0
        private void ProcessEntry(InfoBase infoBase, Guid uuid, string token, int code)
        {
            if (token == MetadataTokens.Fld || token == MetadataTokens.LineNo)
            {
                _ = infoBase.Properties.TryAdd(uuid, Configurator.CreateProperty(uuid, token, code));
                return;
            }

            Type type = Configurator.GetTypeByToken(token);

            if (type == null)
            {
                return;               // unsupported type of metadata object
            }
            ApplicationObject metaObject = Configurator.CreateObject(uuid, token, code);

            if (metaObject == null)
            {
                return;                     // unsupported type of metadata object
            }
            if (token == MetadataTokens.VT)
            {
                _ = infoBase.TableParts.TryAdd(uuid, metaObject);
                return;
            }

            if (!infoBase.AllTypes.TryGetValue(type, out Dictionary <Guid, ApplicationObject> collection))
            {
                return; // unsupported collection of metadata objects
            }
            _ = collection.TryAdd(uuid, metaObject);
        }
Exemple #12
0
        /// <summary>
        ///  Loop over several files and write all tooltips to a tab-separated file.
        /// </summary>
        /// <param name="sourcePath">The directory where the text files are stored</param>
        /// <param name="sourcePattern">Specifies what files to process (e.g. MyObject.txt or *.txt)</param>
        /// <param name="fileName">The output file</param>
        /// <param name="generateTooltips">Generate a tooltip based on CaptionML and SourceExpr properties. </param>
        public static List <Tooltip> GetTooltips(ApplicationObject obj, bool generateTooltips)
        {
            List <Tooltip> tooltips = new List <Tooltip>();

            foreach (IElement element in obj.GetElements())
            {
                string value = null;
                try
                {
                    value = element.GetStringProperty(PropertyType.ToolTipML);
                    if (value != null)
                    {
                        var tooltip = new Tooltip(element.ElementTypeInfo.ElementType, element.Id, value);
                        if (tooltip.GetTooltipMLProperty(false) != "")
                        {
                            tooltips.Add(tooltip);
                        }
                    }
                    else if (generateTooltips)
                    {
                        var generatedTooltip = GenerateTooltip(element);
                        if (generatedTooltip.GetTooltipMLProperty(true) != "")
                        {
                            tooltips.Add(generatedTooltip);
                        }
                    }
                }
                catch (Exception) { }
            }
            return(tooltips);
        }
Exemple #13
0
        private void ValidateAndConfigureDatabaseInterface()
        {
            IDatabaseConfigurator configurator = Services.GetService <IDatabaseConfigurator>();

            configurator
            .UseDatabaseProvider(Settings.DatabaseSettings.DatabaseProvider)
            .UseConnectionString(Settings.DatabaseSettings.ConnectionString);

            if (!configurator.TryOpenInfoBase(out InfoBase infoBase, out string errorMessage))
            {
                throw new Exception($"Failed to load 1C metadata:\n{errorMessage}");
            }

            ApplicationObject queue = configurator.GetOutgoingQueueMetadata(infoBase);

            if (queue == null)
            {
                throw new Exception($"Failed to load 1C metadata for the incoming queue.");
            }

            if (!configurator.OutgoingQueueSequenceExists())
            {
                configurator.ConfigureOutgoingQueue(queue);
            }
        }
Exemple #14
0
        private void InitializeMetaDocument()
        {
            if (Document != null)
            {
                return;
            }

            Console.WriteLine($"Opening metadata: {Metadata.ConnectionString} ...");
            Stopwatch watch = new Stopwatch();

            watch.Start();
            InfoBase = Metadata.OpenInfoBase();
            watch.Stop();
            Console.WriteLine($"Metadata is opened successfully in {watch.ElapsedMilliseconds} ms");

            Document = InfoBase.Documents.Values.Where(c => c.Name == DOCUMENT_NAME).FirstOrDefault();

            if (Document == null)
            {
                Console.WriteLine($"Документ \"{DOCUMENT_NAME}\" не найден.");
            }
            else
            {
                Console.WriteLine($"Документ \"{DOCUMENT_NAME}\" найден.");
            }
        }
 public override void DoCheck(CodeClass codeClass)
 {
     //ApplicationObject.Find.FindWhat(codeClass.Name);
     ApplicationObject.Find.SearchPath = "Entire Solution";
     ApplicationObject.ExecuteCommand("Edit.FindinFiles", codeClass.Name);
     Window findSymbolResultWindow = ApplicationObject.Windows.Item(Constants.vsWindowKindFindResults1);
     string results = findSymbolResultWindow.Caption.ToString();
 }
        public void MergeProperties(ApplicationObject metaObject, List <SqlFieldInfo> fields)
        {
            SortedDictionary <string, MetadataProperty> lookup = PrepareMerging(metaObject.Properties);

            List <string> target_list = lookup.Keys.ToList();

            int source_count = fields.Count;
            int target_count = target_list.Count;

            if (target_count == 0 && source_count == 0)
            {
                return;
            }

            int target_index = 0;
            int source_index = 0;
            int compareResult;

            while (target_index < target_count)
            {
                if (source_index < source_count)
                {
                    compareResult = target_list[target_index].CompareTo(fields[source_index].COLUMN_NAME.ToLowerInvariant());
                    if (compareResult < 0) // target меньше source = delete
                    {
                        DeletePropertyField(metaObject.Properties, lookup[target_list[target_index]], target_list[target_index]);
                        target_index++;
                    }
                    else if (compareResult == 0) // target равен source = update
                    {
                        UpdatePropertyField(lookup[fields[source_index].COLUMN_NAME.ToLowerInvariant()], fields[source_index]);
                        target_index++;
                        source_index++;
                    }
                    else // target больше source = insert
                    {
                        // Добавлять элемент target в список delete мы пока не можем,
                        // так как элемент target возможно есть ниже в списке source.
                        // Элемент source больше не может встретиться в списке target.
                        InsertPropertyField(metaObject, fields[source_index]);
                        source_index++; // Берём следующий элемент source
                    }
                }
                else // достигли конца source списка
                {
                    // Удаляем все оставшиеся поля объекта метаданных
                    DeletePropertyField(metaObject.Properties, lookup[target_list[target_index]], target_list[target_index]);
                    target_index++;
                }
            }
            while (source_index < source_count)
            {
                // Добавляем все оставшиеся поля в свойства объекта метаданных
                InsertPropertyField(metaObject, fields[source_index]);
                source_index++; // Берём следующий элемент source
            }
        }
Exemple #17
0
        private static void SaveApplicationObjectToFile(string filePath, IMetadataService metadataService, string metadataName)
        {
            string[] names = metadataName.Split('.');
            if (names.Length != 2)
            {
                return;
            }
            string typeName   = names[0];
            string objectName = names[1];

            ApplicationObject metaObject = null;
            Dictionary <Guid, ApplicationObject> collection = null;
            InfoBase infoBase = metadataService.LoadInfoBase();

            if (typeName == "Справочник")
            {
                collection = infoBase.Catalogs;
            }
            else if (typeName == "Документ")
            {
                collection = infoBase.Documents;
            }
            else if (typeName == "ПланОбмена")
            {
                collection = infoBase.Publications;
            }
            else if (typeName == "РегистрСведений")
            {
                collection = infoBase.InformationRegisters;
            }
            else if (typeName == "РегистрНакопления")
            {
                collection = infoBase.AccumulationRegisters;
            }
            if (collection == null)
            {
                return;
            }

            metaObject = collection.Values.Where(o => o.Name == objectName).FirstOrDefault();
            if (metaObject == null)
            {
                return;
            }

            byte[] fileData = metadataService.ReadBytes(metaObject.FileName.ToString());
            if (fileData == null)
            {
                return;
            }

            using (StreamReader reader = metadataService.CreateReader(fileData))
                using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8))
                {
                    writer.Write(reader.ReadToEnd());
                }
        }
        private void PG_ConfigureIncomingQueue(ApplicationObject queue, Type template)
        {
            List <string> scripts = new List <string>();

            scripts.Add(PG_CREATE_INCOMING_SEQUENCE_SCRIPT);
            scripts.Add(ConfigureDatabaseScript(PG_ENUMERATE_INCOMING_QUEUE_SCRIPT, template, queue));

            TxExecuteNonQuery(scripts);
        }
Exemple #19
0
        private async void HandleOrder(object sender, EventArgs e)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    var res = await client.GetAsync(orderUrl);

                    res.EnsureSuccessStatusCode();
                    var content = await res.Content.ReadAsStringAsync();

                    var result = JsonConvert.DeserializeObject <JsonData>(content);
                    if (result.Data == null)
                    {
                        return;
                    }
                    var data   = (JArray)result.Data;
                    var orders = new List <Order>();
                    foreach (string item in data)
                    {
                        orders.Add(JsonConvert.DeserializeObject <Order>(item));
                    }
                    var firstOrder = orders[0];
                    this.Dispatcher.Invoke(() =>
                    {
                        var filename = string.Empty;
                        if (firstOrder.Status == Enum.OrderStatus.Payed)
                        {
                            filename = "1.mp3";
                        }
                        else
                        {
                            filename = "2.mp3";
                        }
                        PlayMedia("Assets/Video/" + filename);
                    }, DispatcherPriority.Normal);
                    orders.ForEach(order =>
                    {
                        ApplicationObject.Print(order);
                    });
                }
            }
            catch (Exception ex)
            {
                if (isError)
                {
                    return;
                }
                //isError = true;
                //var result = MessageBox.Show("读取新订单错误:" + ex.Message, "提示", MessageBoxButton.OK);
                //if (result == MessageBoxResult.OK)
                //{
                //    isError = false;
                //}
                AutoClosingMessageBox.Show("读取新订单错误:" + ex.Message, "提示", 3000);
            }
        }
Exemple #20
0
        public void EnrichFromDatabase(ApplicationObject metaObject)
        {
            List <SqlFieldInfo> sqlFields = SqlMetadataReader.GetSqlFieldsOrderedByName(metaObject.TableName);

            if (sqlFields.Count == 0)
            {
                return;
            }
            CompareMergeService.MergeProperties(metaObject, sqlFields);
        }
Exemple #21
0
        private static void LoadBackupVersions(string backupDirectory, ApplicationObject application)
        {
            var applicationTypeBackupDirectory = new DirectoryInfo(Path.Combine(backupDirectory, application.Type));

            if (applicationTypeBackupDirectory.Exists)
            {
                var applicationBackupDirectories = applicationTypeBackupDirectory.GetDirectories(application.Name + ".*", SearchOption.TopDirectoryOnly);
                application.Backups = applicationBackupDirectories.Select(x => new ApplicationBackupObject(x.Name.Substring(application.Name.Length + 1), x.FullName)).OrderByDescending(x => x.Version).ToList();
            }
        }
Exemple #22
0
        [TestMethod("MS-01 Обычный")] public void MS_01()
        {
            ApplicationObject document = Test.MS_InfoBase
                                         .Documents.Values
                                         .Where(r => r.Name == "ОбычныйДокумент")
                                         .FirstOrDefault();

            Assert.IsNotNull(document);

            Test.EnrichAndCompareWithDatabase(DatabaseProvider.SQLServer, document);
        }
Exemple #23
0
        [TestMethod("MS-01 Строка")] public void MS_01()
        {
            ApplicationObject constant = Test.MS_InfoBase
                                         .Constants.Values
                                         .Where(r => r.Name == "Константа1")
                                         .FirstOrDefault();

            Assert.IsNotNull(constant);

            Test.EnrichAndCompareWithDatabase(DatabaseProvider.SQLServer, constant);
        }
Exemple #24
0
 public static void EnrichAndCompareWithDatabase(DatabaseProvider provider, ApplicationObject metaObject)
 {
     if (provider == DatabaseProvider.SQLServer)
     {
         EnrichAndCompareWithDatabasePrivate(MS_MetadataService, metaObject);
     }
     else
     {
         EnrichAndCompareWithDatabasePrivate(PG_MetadataService, metaObject);
     }
 }
Exemple #25
0
 public static void ShowProperties(ApplicationObject metaObject)
 {
     Console.WriteLine(metaObject.Name + " (" + metaObject.TableName + "):");
     Console.WriteLine("---");
     foreach (MetadataProperty property in metaObject.Properties)
     {
         Console.WriteLine("   - " + property.Name + " (" + property.DbName + ")");
         ShowFields(property);
     }
     Console.WriteLine();
 }
        [TestMethod("MS-01")] public void MS_01()
        {
            ApplicationObject enumeration = Test.MS_InfoBase
                                            .Enumerations.Values
                                            .Where(r => r.Name == "Перечисление1")
                                            .FirstOrDefault();

            Assert.IsNotNull(enumeration);

            Test.EnrichAndCompareWithDatabase(DatabaseProvider.SQLServer, enumeration);
        }
Exemple #27
0
        [TestMethod("PG-02 Без номера")] public void PG_02()
        {
            ApplicationObject document = Test.PG_InfoBase
                                         .Documents.Values
                                         .Where(r => r.Name == "ДокументБезНомера")
                                         .FirstOrDefault();

            Assert.IsNotNull(document);

            Test.EnrichAndCompareWithDatabase(DatabaseProvider.PostgreSQL, document);
        }
        [TestMethod("PG-02 Обороты")] public void PG_Turnover()
        {
            ApplicationObject register = Test.PG_InfoBase
                                         .AccumulationRegisters.Values
                                         .Where(r => r.Name == "РегистрНакопленияОбороты")
                                         .FirstOrDefault();

            Assert.IsNotNull(register);

            Test.EnrichAndCompareWithDatabase(DatabaseProvider.PostgreSQL, register);
        }
        [TestMethod("MS-01 Остатки")] public void MS_Balance()
        {
            ApplicationObject register = Test.MS_InfoBase
                                         .AccumulationRegisters.Values
                                         .Where(r => r.Name == "РегистрНакопленияОстатки")
                                         .FirstOrDefault();

            Assert.IsNotNull(register);

            Test.EnrichAndCompareWithDatabase(DatabaseProvider.SQLServer, register);
        }
Exemple #30
0
        protected void AddObjectToLinkCache(ApplicationObject appObject)
        {
            IElement        rootElement = appObject.RootElement;
            ObjectLinkCache objLink     = new ObjectLinkCache();

            objLink.Type = appObject.ElementTypeInfo.Name;
            objLink.Id   = objLink.Type + rootElement.Id.ToString();
            objLink.Uid  = UidHelpers.GetObjectUid(this.ProjectUid, objLink.Type, objLink.Id);
            objLink.Name = rootElement.GetStringProperty(PropertyType.Name);
            objectLinks.Add(objLink.Id, objLink);
        }
Exemple #31
0
        private async void Upload_Click(object obj, RoutedEventArgs e)
        {
            if (!ApplicationObject.App.ClientData.IsHost)
            {
                MessageBox.Show("只有主收银机才能上传数据");
                return;
            }
            await ApplicationObject.UploadDataAsync();

            MainSnackbar.MessageQueue.Enqueue("上传成功");
        }
        public static string GetFormattedMessage(ApplicationObject Value)
        {
            string Name = "";
            switch (Value.UIMessageType)
            {
                case Web.Admin.Logic.UIMessageType.Information: Name = "information-white.png"; break;
                case Web.Admin.Logic.UIMessageType.Success: Name = "tick-circle.png"; break;
                case Web.Admin.Logic.UIMessageType.Warning: Name = "exclamation-octagon.png"; break;
                case Web.Admin.Logic.UIMessageType.ErrorOrDanger: Name = "exclamation-red.png"; break;
            }

            return String.Format("<img src=\"{0}content/images/{1}\"/> {2}", HttpRuntime.AppDomainAppVirtualPath, Name, Value.UIMessage);
        }
Exemple #33
0
        /// <summary>
        /// Attempts to create the user account and initialize its user directory
        /// Runs as an administrator
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        public static void CreateAccount(string name, string password)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                ProcessStartInfo p = new ProcessStartInfo(a.Path, "-user -u \"" + name + "\" -p \"" + password + "\"");
                p.UseShellExecute = true;
                p.Verb = "runas";

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }
        /// <summary>
        /// Get application biz object by id. Returns null if the application id is invalid.
        /// </summary>
        /// <param name="applicationId"></param>
        /// <returns>returns null if the application id is invalid.</returns>
        public ApplicationObject Get(Guid applicationId)
        {
            ApplicationObject applicationObject = base.GetCacheObject<ApplicationObject>(applicationId);
            if (applicationObject != null) return applicationObject.Clone();

            using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>())
            {
                Application application = ctx.Applications.FirstOrDefault(app => app.ApplicationId == applicationId);
                if (application == null) return null;

                applicationObject = new ApplicationObject
                {
                    Id = application.ApplicationId,
                    Name = application.ApplicationName,
                    Description = application.Description
                };

                applicationObject.ParseExtensionPropertiesFrom(application);
                base.AddCache(applicationObject.Id, applicationObject);
                return applicationObject;
            }
        }
Exemple #35
0
        /// <summary>
        /// Deletes the specified scheduled tasks
        /// </summary>
        /// <param name="names">The name of the task</param>
        public static void DeleteTask(IEnumerable<string> names)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                StringBuilder args = new StringBuilder(512);
                args.Append("-task -delete");
                foreach (string name in names)
                {
                    args.Append(" \"");
                    args.Append(name);
                    args.Append('"');
                }

                ProcessStartInfo p = new ProcessStartInfo(a.Path, args.ToString());
                p.UseShellExecute = true;
                p.Verb = "runas";

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }
        private static Application CreateApplication(ApplicationObject applicationObject)
        {
            Application application = new Application { ExtensionDataTypeId = applicationObject.ExtensionDataTypeId };
            IEnumerator<KeyValuePair<string, object>> properties = applicationObject.GetFieldEnumerator();
            while (properties.MoveNext())
                application[properties.Current.Key] = properties.Current.Value;

            return application;
        }
Exemple #37
0
        /// <summary>
        /// Deletes all gw2cache-{*} folders located in the specified folder
        /// </summary>
        /// <param name="roots">Folders containing gw2cache folders</param>
        public static void DeleteCacheFolders(IEnumerable<string> roots)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                StringBuilder args = new StringBuilder(512);

                args.Append("-delgw2cache");

                foreach (string root in roots)
                {
                    args.Append(" \"");
                    args.Append(root);
                    args.Append('"');
                }

                ProcessStartInfo p = new ProcessStartInfo(a.Path, args.ToString());
                p.UseShellExecute = true;
                p.Verb = "runas";

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }
        public void ExistApplication()
        {
            _story = new Story("Judge if the Application exists");

            _story.AsA("User")
              .IWant("to be able to Judge if the Application exists")
              .SoThat("I can decide to create the application or not");

            _story.WithScenario("Judge the application ")
                .Given("an unexisting application Name ", () =>
                {
                    _ApplicationObject = new ApplicationObject() { Description = "Haha", Name = "App" };
                })
                .When("I get this Application", () =>
                {
                    _applicationApi.Exists("App").ShouldBeFalse();
                })
                .Then(" I can create the object and judge if it exists ", () =>
                {
                    _applicationApi.Save(_ApplicationObject);

                    createdApplicationIds.Add(_ApplicationObject.Id);

                    _applicationApi.Exists("App").ShouldBeTrue();
                });
            this.CleanUp();
        }
Exemple #39
0
        /// <summary>
        /// Runs the specified scheduled task
        /// </summary>
        /// <param name="name">The name of the task</param>
        public static void RunTask(string name)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                ProcessStartInfo p = new ProcessStartInfo(a.Path, "-task -run \"" + name + "\"");
                p.UseShellExecute = true;

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }
Exemple #40
0
        /// <summary>
        /// Creates the scheduled tasks "gw2launcher-users-active-yes" and "gw2launcher-users-active-no"
        /// that start this program with the options -users:active:yes or -users:active:no as
        /// a high priviledge user
        /// </summary>
        public static bool CreateInactiveUsersTask()
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                string path1 = Path.GetTempFileName();
                string path2 = Path.GetTempFileName();

                try
                {
                    string _xml1, _xml2;

                    _xml1 = Properties.Resources.Task.Replace("{path}", Assembly.GetEntryAssembly().Location /*Process.GetCurrentProcess().MainModule.FileName*/);

                    _xml2 = _xml1.Replace("{args}", "-users:active:no");
                    _xml1 = _xml1.Replace("{args}", "-users:active:yes");

                    File.WriteAllText(path1, _xml1);
                    File.WriteAllText(path2, _xml2);

                    StringBuilder args = new StringBuilder(512);
                    args.Append("-task -create \"gw2launcher-users-active-yes\" \"");
                    args.Append(path1);
                    args.Append("\" \"gw2launcher-users-active-no\" \"");
                    args.Append(path2);
                    args.Append('"');

                    ProcessStartInfo p = new ProcessStartInfo(a.Path, args.ToString());
                    p.UseShellExecute = true;
                    p.Verb = "runas";

                    Process proc = Process.Start(p);
                    if (proc != null)
                    {
                        proc.WaitForExit();
                        return proc.ExitCode == 0;
                    }

                    return false;
                }
                finally
                {
                    try
                    {
                        File.Delete(path1);
                    }
                    catch { }
                    try
                    {
                        File.Delete(path2);
                    }
                    catch { }
                }
            }
        }
        /// <summary>
        /// Save application. Empty application id of application object means that the specified application object is new created. 
        /// And after it's inserted into database, the database generated id will be set back to property id.
        /// Non-empty application id means to update an existed application. 
        /// If the non-empty application id is not available in database, it throws exception ValidationException.
        /// </summary>
        /// <param name="applicationObject"></param>
        /// <exception cref="ValidationException">If the non-empty application id is not available in database, it throws exception ValidationException.</exception>
        public void Save(ApplicationObject applicationObject)
        {
            Kit.NotNull(applicationObject, "applicationObject");

            using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>())
            {
                Application application = null;
                if (applicationObject.Id != Guid.Empty)
                {
                    application = ctx.Applications.FirstOrDefault(app => app.ApplicationId == applicationObject.Id);
                    if (application == null)
                        throw new ValidationException(string.Format(Resources.InvalidApplicationID, applicationObject.Id));
                }
                else
                {
                    application = CreateApplication(applicationObject);
                    ctx.Applications.InsertOnSubmit(application);
                }

                string originalApplicationName = application.ApplicationName;
                application.ApplicationName = applicationObject.Name;
                application.LoweredApplicationName = applicationObject.Name.ToLowerInvariant();
                application.Description = applicationObject.Description;
                application.ParseExtensionPropertiesFrom(applicationObject);
                ctx.SubmitChanges();

                applicationObject.Id = application.ApplicationId;
                base.RemoveCache(originalApplicationName);
                base.RemoveCache(applicationObject.Id);
            }
        }
        public void GetApplication()
        {
            _story = new Story("Get the Application");

            _story.AsA("User")
              .IWant("to be able to get an existing Application")
              .SoThat("I can modify the object");

            _story.WithScenario("Get the Application By correct application Name or application Id")
                .Given("an existing application Name or application Id",
                    () =>
                     {
                         _ApplicationObject = new ApplicationObject() { Description = "Application", Name = "App" };
                         _applicationApi.Save(_ApplicationObject);

                         createdApplicationIds.Add(_ApplicationObject.Id);
                     })
                .When("I get this Application",
                    () =>
                        {
                            _ApplicationObject1 = _applicationApi.Get(_ApplicationObject.Id);

                            _ApplicationObject2 = _applicationApi.Get(_ApplicationObject.Name);
                        })
                .Then("The Objects I get should be equal", () =>
                                                              {
                                                                  _ApplicationObject.Id.ShouldEqual(_ApplicationObject1.Id);
                                                                  //_ApplicationObject.Id.ShouldEqual(_ApplicationObject2.Id);

                                                              });

            this.CleanUp();
        }
        public void GetApplicationWithError()
        {
            _story = new Story("Get the Application");

            _story.AsA("User")
                .IWant("to be able to get an existing Application")
                .SoThat("I can modify the object");
            Guid _temp = new Guid();
            _story.WithScenario("Get the Application By correct application Name or application Id")
                .Given("an existing application Name or application Id", () =>
                                                                             {

                                                                             })
                .When("I get this Application", () =>
                                                    {
                                                        _ApplicationObject1 = _applicationApi.Get(_temp);

                                                        _ApplicationObject2 = _applicationApi.Get("");
                                                    })
                .Then("The Objects I get should be equal", () =>
                                                               {
                                                                   _ApplicationObject1.ShouldBeNull();
                                                                   _ApplicationObject2.ShouldBeNull();
                                                                   ;

                                                               });

            this.CleanUp();
        }
Exemple #44
0
        /// <summary>
        /// Finds all processes that match the name and attempts to kill "AN-Mutex-Window-Guild Wars 2"
        /// Runs as an administrator
        /// </summary>
        /// <param name="name"></param>
        public static void KillMutexWindowByProcessName(string name)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                ProcessStartInfo p = new ProcessStartInfo(a.Path, "-handle -n \"" + name + "\" \"AN-Mutex-Window-Guild Wars 2\" 0");
                p.UseShellExecute = true;
                p.Verb = "runas";

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }
 /// <summary>
 /// Save application. Empty application id of application object means that the specified application object is new created. 
 /// And after it's inserted into database, the database generated id will be set back to property id.
 /// Non-empty application id means to update an existed application. 
 /// If the non-empty application id is not available in database, it throws exception ValidationException.
 /// </summary>
 /// <param name="applicationObject"></param>
 /// <exception cref="RapidWebDev.Common.Validation.ValidationException">If the non-empty application id is not available in database, it throws exception ValidationException.</exception>
 public string SaveJson(ApplicationObject applicationObject)
 {
     if (applicationObject == null) throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidApplicationID + "{0}", "applicationObject cannot be null"));
     try
     {
         applicationApi.Save(applicationObject);
         return applicationObject.Id.ToString();
     }
     catch (ArgumentException ex)
     {
         throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, ex.Message));
     }
     catch (BadRequestException bad)
     {
         throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, bad.Message));
     }
     catch (FormatException formatEx)
     {
         throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, formatEx.Message));
     }
     catch (Exception exp)
     {
         Logger.Instance(this).Error(exp);
         throw new InternalServerErrorException();
     }
 }
Exemple #46
0
        /// <summary>
        /// Finds the process with the ID and attempts to kill "AN-Mutex-Window-Guild Wars 2"
        /// Specify a null username to run as an administrator
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="username"></param>
        /// <param name="password">The password for the username or null to run as the current user</param>
        public static void KillMutexWindow(int pid, string username, System.Security.SecureString password)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                ProcessStartInfo p = new ProcessStartInfo(a.Path, "-handle -pid " + pid + " \"AN-Mutex-Window-Guild Wars 2\" 0");
                if (username != null)
                {
                    p.UseShellExecute = false;
                    if (password != null)
                    {
                        try
                        {
                            //other users will be using this
                            Util.FileUtil.AllowFileAccess(a.Path, System.Security.AccessControl.FileSystemRights.Modify);
                        }
                        catch { }

                        p.UserName = username;
                        p.LoadUserProfile = true;
                        p.Password = password;
                        p.WorkingDirectory = Path.GetPathRoot(a.Path);
                    }
                }
                else
                {
                    p.UseShellExecute = true;
                    p.Verb = "runas";
                }

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }
        public void UpdateApplication()
        {
            _story = new Story("Save the object ");

            _story.AsA("User")
              .IWant("to be able to save the Application ")
              .SoThat("I can get  the application ");

            _story.WithScenario("Judge the application ")
                .Given("an unexisting application Name ", () =>
                {
                    _ApplicationObject = new ApplicationObject() { Description = "Haha", Name = "App" };
                })
                .When("I save this Application", () =>
                {
                    _applicationApi.Save(_ApplicationObject);

                    _ApplicationObject1 = _applicationApi.Get(_ApplicationObject.Id);

                    _ApplicationObject.Name = " ";

                    _applicationApi.Save(_ApplicationObject);

                    createdApplicationIds.Add(_ApplicationObject.Id);

                })
                .Then(" I can get the object and it's name be changed ", () =>
                {
                    _ApplicationObject.Name.ShouldEqual(" ");
                });
            this.CleanUp();
        }
Exemple #48
0
        /// <summary>
        /// Creates the user's home folders
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public static void InitializeAccount(string username, System.Security.SecureString password)
        {
            using (ApplicationObject a = new ApplicationObject())
            {
                try
                {
                    //other users will be using this
                    Util.FileUtil.AllowFileAccess(a.Path, System.Security.AccessControl.FileSystemRights.Modify);
                }
                catch { }

                ProcessStartInfo p = new ProcessStartInfo(a.Path, "-userinit");

                p.UseShellExecute = false;
                p.UserName = username;
                p.LoadUserProfile = true;
                p.Password = password;
                p.WorkingDirectory = Path.GetPathRoot(a.Path);

                //creating the user's profile will be handled by Windows
                //the process doesn't actually do anything itself

                Process proc = Process.Start(p);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
            }
        }