示例#1
0
        public void TestMethod1()
        {
            var unityContainer = UnityBootstrapper.Container;

            unityContainer.RegisterType(typeof(IRepository<>), typeof(RepositoryImpl<>));
            unityContainer.RegisterType<IRepositoryConfig, RepositoryConfig>(new InjectionConstructor(true, true, true));

            unityContainer.RegisterType<IUnitOfWork, UnitOfWorkImpl>();

            var db = Effort.DbConnectionFactory.CreateTransient();
            var ctx = new MyDataContext(db, new MyDataContextConfiguration("", true));
            ctx.Database.CreateIfNotExists();
            ctx.Database.Initialize(true);

            //unityContainer.RegisterType<MyDataContextConfiguration>(new InjectionConstructor("", true));
            unityContainer.RegisterType<DbContext>(new InjectionFactory(con => ctx));

            unityContainer.RegisterType<IOUService, OUService>();

            var ouService = unityContainer.Resolve<IOUService>();

            var x = ouService.First(o => o.Id > 0);

            int y = 0;
        }
示例#2
0
 public async Task <List <ActiveSubstance> > GetAllActiveSubstance()
 {
     using (var activeSubstanceDbContext = new MyDataContext())
     {
         return(await activeSubstanceDbContext.ActiveSubstances.ToListAsync());
     }
 }
示例#3
0
        public bool WriteUserToDB(User user)
        {
            MyDataContext dataContext = new MyDataContext();
            var           context     = (IDataContextFactory <HealthDataContext>)dataContext.GetMyDataContextContext(_configuration);

            using (var db = context.Create())
            {
                var lastidquery = (from u in db.Users
                                   //where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
                                   orderby u.Id descending
                                   select u).Take(1);
                int id = 0;

                foreach (var u in lastidquery)
                {
                    id = u.Id + 1;
                }
                if (id != 0)
                {
                    user.Id = id;
                    if (db.Insert(user) > 0)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
示例#4
0
    ResolveFieldContext ResolveFieldContext(
        MyDataContext ctx,
        CancellationToken token,
        Document document,
        ISchema schema)
    {
        var operation        = document.Operations.FirstOrDefault();
        var variableValues   = ExecutionHelper.GetVariableValues(document, schema, operation?.Variables, null);
        var executionContext = new ExecutionContext
        {
            Document                  = document,
            Schema                    = schema,
            UserContext               = ctx,
            Variables                 = variableValues,
            Fragments                 = document.Fragments,
            CancellationToken         = token,
            Listeners                 = new IDocumentExecutionListener[0],
            Operation                 = operation,
            ThrowOnUnhandledException = true // DEBUG
        };

        var operationRootType = ExecutionHelper.GetOperationRootType(
            executionContext.Document,
            executionContext.Schema,
            executionContext.Operation);

        var node = ExecutionStrategy.BuildExecutionRootNode(executionContext, operationRootType);

        return(GetContext(executionContext, node.SubFields["companies"]));
    }
示例#5
0
        public PersonEntryViewModel(INavigationService navigationService, MyDataContext dataContext)
            : base(navigationService)
        {
            this.dataContext = dataContext ?? throw new ArgumentNullException(nameof(dataContext));

            Person = new Person();
        }
示例#6
0
    public static List <MyModel> AutoComplete(string term, string SearchBy)
    {
        using (var repository = new MyDataContext())
        {
            if (SearchBy == "Tag")
            {
                var tech      = repository.AllFindTechnolog(term.Trim()).ToList();
                var resources = repository.GetResources(tech.Select(a => a.IT360ID.Value).ToArray(), false).ToList();
                var query     = from techItems in tech
                                join resourcesItems in resources
                                on techItems.IT360ID.Value equals resourcesItems.RESOURCEID // join based on db2ID
                                orderby techItems.PartialTag
                                select new MyModel {
                    extra = true, label = techItems.Tag.ToString(), techtype = techItems.TechnologyType.Name, status = resourcesItems.ResourceState.DISPLAYSTATE, customername = resourcesItems.ResourceLocation.SiteDefinition.AccountDefinition.ORG_NAME.ToString(), resourcename = resourcesItems.RESOURCENAME.ToString(), sitename = resourcesItems.ResourceLocation.SiteDefinition.SDOrganization.NAME
                };

                return(query.ToList());
            }
            else
            {
                var activeResources = repository.FindActiveResourceByName(term.Trim(), true).ToList();    //.OrderBy(p => p.RESOURCENAME).Select(a => new { label = a.RESOURCENAME }).ToList();
                var resources       = repository.GetResources(activeResources.Select(a => a.RESOURCEID).ToArray(), false).ToList();
                var tech            = repository.getTechnologiesByIT360ids(activeResources.Select(a => a.RESOURCEID).ToArray()).ToList();
                var query           = from techItems in tech
                                      join resourcesItems in resources
                                      on techItems.IT360ID.Value equals resourcesItems.RESOURCEID // join based on db2ID
                                      orderby techItems.Tag
                                      select new MyModel {
                    extra = true, label = resourcesItems.RESOURCENAME.ToString(), techtype = techItems.TechnologyType.Name, status = resourcesItems.ResourceState.DISPLAYSTATE, customername = resourcesItems.ResourceLocation.SiteDefinition.AccountDefinition.ORG_NAME.ToString(), resourcename = techItems.Tag.ToString(), sitename = resourcesItems.ResourceLocation.SiteDefinition.SDOrganization.NAME
                };

                return(query.ToList());
            }
        }
    }
示例#7
0
        public static int UpdateEntryByProperty <T>(this MyDataContext _db, T entity, string EntityKey) where T : class
        {
            DbSet <T> dbSet = _db.Set <T>();

            dbSet.Attach(entity);
            MemberInfo[]             members    = entity.GetType().GetMembers();
            IEnumerable <MemberInfo> properties = members.Where(m => m.MemberType == MemberTypes.Property && m.Name != EntityKey);

            foreach (MemberInfo mInfo in properties)
            {
                object o = entity.GetType().InvokeMember(mInfo.Name, BindingFlags.GetProperty, null, entity, null);
                if (o != null)
                {
                    if (o.GetType().IsPrimitive || o.GetType().IsPublic)
                    {
                        try
                        {
                            DbEntityEntry entry = _db.Entry <T>(entity);
                            entry.Property(mInfo.Name).IsModified = true;
                        }
                        catch
                        {
                        }
                    }
                }
            }

            return(_db.SaveChanges());
        }
示例#8
0
    static void Main()
    {
        MyDataContext ctx   = new MyDataContext();
        BindingSource custs = new BindingSource()
        {
            DataSource = ctx.Customers
        };

        BindingSource orders = new BindingSource {
            DataMember = "Orders", DataSource = custs
        };

        Button btn;

        using (Form form = new Form
        {
            Controls =
            {
                new DataGridView()
                {
                    DataSource = orders, DataMember = "Order_Details",
                    Dock = DockStyle.Fill
                },
                new ComboBox()
                {
                    DataSource = orders, DisplayMember = "OrderID",
                    Dock = DockStyle.Top
                },
                new ComboBox()
                {
                    DataSource = custs, DisplayMember = "CompanyName",
                    Dock = DockStyle.Top
                },
                (btn = new Button()
                {
                    Text = "Save", Dock = DockStyle.Bottom
                }),     // **edit here re textbox etc**
                new TextBox {
                    DataBindings ={        { "Text", orders, "ShipAddress"  } },
                    Dock = DockStyle.Bottom
                },
                new Label   {
                    DataBindings ={        { "Text", custs,  "ContactName"  } },
                    Dock = DockStyle.Top
                },
                new Label   {
                    DataBindings ={        { "Text", orders, "RequiredDate" } },
                    Dock = DockStyle.Bottom
                }
            }
        })
        {
            btn.Click += delegate {
                form.Text = "Saving...";
                ctx.SubmitChanges();
                form.Text = "Saved";
            };
            Application.Run(form);
        }
    }
示例#9
0
        public override void Render(TextWriter writer)
        {
            object value = GetVariableValue();

            if (MyDataContext.HasVariable(VariableKey))
            {
                MyDataContext.RemoveLocalValue(VariableKey);
            }
            if (string.IsNullOrEmpty(ScopeVariableKey))
            {
                this.MyDataContext.RegisterDataItem(VariableKey, value);
            }
            else
            {
                Dictionary <string, object> scopeDictionary = null;
                if (!MyDataContext.MasterData.ContainsKey(ScopeVariableKey))
                {
                    scopeDictionary = new Dictionary <string, object>();
                    MyDataContext.RegisterLocalValue(ScopeVariableKey, scopeDictionary);
                }
                else
                {
                    scopeDictionary = MyDataContext.GetVariableObject(ScopeVariableKey) as Dictionary <string, object>;
                }
                if (scopeDictionary != null)
                {
                    scopeDictionary.Add(VariableKey, value);
                }
                else
                {
                    //TODO: REGISTER ERROR
                }
            }
        }
示例#10
0
        public void TestMethod1()
        {
            var unityContainer = UnityBootstrapper.Container;

            unityContainer.RegisterType(typeof(IRepository <>), typeof(RepositoryImpl <>));
            unityContainer.RegisterType <IRepositoryConfig, RepositoryConfig>(new InjectionConstructor(true, true, true));

            unityContainer.RegisterType <IUnitOfWork, UnitOfWorkImpl>();


            var db  = Effort.DbConnectionFactory.CreateTransient();
            var ctx = new MyDataContext(db, new MyDataContextConfiguration("", true));

            ctx.Database.CreateIfNotExists();
            ctx.Database.Initialize(true);

            //unityContainer.RegisterType<MyDataContextConfiguration>(new InjectionConstructor("", true));
            unityContainer.RegisterType <DbContext>(new InjectionFactory(con => ctx));


            unityContainer.RegisterType <IOUService, OUService>();

            var ouService = unityContainer.Resolve <IOUService>();

            var x = ouService.First(o => o.Id > 0);

            int y = 0;
        }
        public void AssociationToFilteredEntityFunc([IncludeDataSources(false, TestProvName.AllSQLite)] string context)
        {
            var testData = GenerateTestData();

            Expression <Func <ISoftDelete, MyDataContext, bool> > softDeleteCheck = (e, dc) => !dc.IsSoftDeleteFilterEnabled || !e.IsDeleted;
            var builder = new MappingSchema().GetFluentMappingBuilder();

            builder.Entity <MasterClass>().HasQueryFilter <MyDataContext>((q, dc) => q.Where(e => softDeleteCheck.Compile()(e, dc)));
            builder.Entity <DetailClass>().HasQueryFilter <MyDataContext>((q, dc) => q.Where(e => softDeleteCheck.Compile()(e, dc)));

            var ms = builder.MappingSchema;

            using (new AllowMultipleQuery())
                using (var db = new MyDataContext(context, ms))
                    using (db.CreateLocalTable(testData.Item1))
                        using (db.CreateLocalTable(testData.Item2))
                            using (db.CreateLocalTable(testData.Item3))
                            {
                                var query = from m in db.GetTable <MasterClass>().IgnoreFilters()
                                            from d in m.Details
                                            select d;

                                CheckFiltersForQuery(db, query);
                            }
        }
示例#12
0
 public MainWindow()
 {
     InitializeComponent();
     dataContext = new MyDataContext();
     timer       = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.ApplicationIdle,
                                       TimerElapsed, Dispatcher.CurrentDispatcher);
 }
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult m = MessageBox.Show("Удалить?", "", MessageBoxButton.OKCancel);

            if (m == MessageBoxResult.OK)
            {
                Action a = null;
                if (listBox1.SelectedIndex >= 0)
                {
                    a = l[listBox1.SelectedIndex];
                }
                if (listBox2.SelectedIndex >= 0)
                {
                    a = l[listBox1.SelectedIndex];
                }

                using (MyDataContext Db = new MyDataContext(MainPage.strConnectionString))
                {
                    if (a != null)
                    {
                        var s1 = from Action in Db.Actions
                                 where Action.ActionID == a.ActionID
                                 select Action;
                        Db.Actions.DeleteOnSubmit(s1.FirstOrDefault());
                        Db.SubmitChanges();
                    }
                }
                init();
            }
        }
示例#14
0
        public override void Render(System.IO.TextWriter writer)
        {
            if (string.IsNullOrEmpty(this.Group))
            {
                return;
            }

            IEnumerable friendList = MyDataContext.GetEnumerableVariableObject(this.Group);

            if (null == friendList)
            {
                return;
            }

            string output = string.Empty;

            if (!MultiSelect)
            {
                output = singleSelectDropDown(friendList);
            }
            else
            {
                output = multiSelectDropDown(friendList);
            }

            writer.Write(output);
        }
        public async Task <List <GetStorageMedicineDto> > GetByStorageCode(string storageCode)
        {
            using (var storageDbContext = new MyDataContext())
            {
                var queryableStroges = storageDbContext.Storages.Include(i => i.Medicines).ThenInclude(i => i.MedicineActiveSubstances).ThenInclude(i => i.ActiveSubstance);
                var storage          = await queryableStroges.FirstOrDefaultAsync(i => i.Code == storageCode);

                var temp = new List <GetStorageMedicineDto>();

                foreach (var medicine in storage.Medicines)
                {
                    var model = new GetStorageMedicineDto();

                    model.adi  = medicine.Name;
                    model.kod  = medicine.Code;
                    model.skt  = medicine.ExpireDate.ToString("dd/MMMM/yyyy");
                    model.turu = medicine.Type;

                    foreach (var item in medicine.MedicineActiveSubstances)
                    {
                        model.etkenler.Add(new GetActiveSubtanceDto {
                            etkenadi = item.ActiveSubstance.SubstanceName
                        });
                    }

                    temp.Add(model);
                }

                return(temp);
            }
        }
示例#16
0
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
                using (MyDataContext Db = new MyDataContext(MainPage.strConnectionString))
                {
                    Db.DeleteDatabase();
                }
            }
        }
 public async Task <Storage> GetStorageById(int id)
 {
     using (var storageDbContext = new MyDataContext())
     {
         return(await storageDbContext.Storages.FindAsync(id));
     }
 }
 public async Task <List <Storage> > GetAllStorage()
 {
     using (var storageDbContext = new MyDataContext())
     {
         return(await storageDbContext.Storages.ToListAsync());
     }
 }
示例#19
0
        public void EntityFilterTestsCache([IncludeDataSources(false, TestProvName.AllSQLite)] string context, [Values(1, 2, 3)] int iteration, [Values] bool filtered)
        {
            var testData = GenerateTestData();

            using (var db = new MyDataContext(context, _filterMappingSchema))
                using (db.CreateLocalTable(testData.Item1))
                {
                    var currentMissCount = Query <MasterClass> .CacheMissCount;

                    var query = from m in db.GetTable <MasterClass>()
                                select m;

                    ((DcParams)db.Params).IsSoftDeleteFilterEnabled = filtered;

                    var result = query.ToList();

                    if (filtered)
                    {
                        result.Count.Should().BeLessThan(testData.Item1.Length);
                    }
                    else
                    {
                        result.Count.Should().Be(testData.Item1.Length);
                    }

                    if (iteration > 1)
                    {
                        Query <MasterClass> .CacheMissCount.Should().Be(currentMissCount);
                    }
                }
        }
示例#20
0
 public async Task <Medicine> GetMedicineById(int id)
 {
     using (var medicineDbContext = new MyDataContext())
     {
         return(await medicineDbContext.Medicines.FindAsync(id));
     }
 }
示例#21
0
 public async Task <List <Medicine> > GetAllMedicine()
 {
     using (var medicineDbContext = new MyDataContext())
     {
         return(await medicineDbContext.Medicines.ToListAsync());
     }
 }
示例#22
0
        public void AttributeLicense1()
        {
            DataContext context;
            var         mapping = XmlMappingSource.FromXml(
                @"<Database Name=""Northwind"" Provider=""ALinq.Firebird.FirebirdProvider, ALinq.Firebird, Version=1.2.7.0, Culture=Neutral, PublicKeyToken=2b23f34316d38f3a"" xmlns=""http://schemas.microsoft.com/linqtosql/mapping/2007"">
</Database>
");

            context = new MyDataContext("", mapping);
            Assert.IsNotNull(((SqlProvider)context.Provider).License);
            var license = (ALinqLicenseProvider.LicFileLicense)((SqlProvider)context.Provider).License;

            Assert.IsFalse(license.IsTrial);

            mapping = XmlMappingSource.FromXml(
                @"<Database Name=""Northwind"" Provider=""ALinq.Access.AccessDbProvider, ALinq.Access, Version=1.7.9.0, Culture=neutral, PublicKeyToken=2b23f34316d38f3a"" xmlns=""http://schemas.microsoft.com/linqtosql/mapping/2007"">
</Database>
");
            context = new MyDataContext("", mapping);
            Assert.IsNotNull(((SqlProvider)context.Provider).License);
            license = (ALinqLicenseProvider.LicFileLicense)((SqlProvider)context.Provider).License;
            Assert.IsFalse(license.IsTrial);

            mapping = XmlMappingSource.FromXml(
                @"<Database Name=""Northwind"" Provider=""ALinq.SQLite.SQLiteProvider, ALinq.SQLite, Version=1.7.9.0, Culture=neutral, PublicKeyToken=2b23f34316d38f3a"" xmlns=""http://schemas.microsoft.com/linqtosql/mapping/2007"">
</Database>
");
            context = new MyDataContext("", mapping);
            Assert.IsNotNull(((SqlProvider)context.Provider).License);
            license = (ALinqLicenseProvider.LicFileLicense)((SqlProvider)context.Provider).License;
            Assert.IsFalse(license.IsTrial);
        }
 public Task <ExecutionResult> Post(
     [BindRequired, FromBody] PostBody body,
     [FromServices] MyDataContext dataContext,
     CancellationToken cancellation)
 {
     return(Execute(dataContext, body.Query, body.OperationName, body.Variables, cancellation));
 }
示例#24
0
        private async void btnLogout_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确定要注销吗?", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
            {
                return;
            }
            using (new WaitPopup("正在注销中", this))
            {
                await Task.Run(() =>
                {
                    try
                    {
                        clearNotebooks();

                        clearNotes();

                        clearPicCache();

                        clearLocalLog();

                        ConstantPool.AccessToken = "";
                        Util.SaveLastSelectedNotebook(null);

                        MyDataContext.DeleteDatabaseIfExists();
                    }
                    catch (Exception ex)
                    {
                        LoggerFactory.GetLogger().Error("注销发生错误", ex);
                        Toast.Prompt("额,注销发生错误,请稍后重试!");
                    }
                });
            }
            showCacheSize();
            navigateAuth();
        }
    async Task <ExecutionResult> Execute(
        MyDataContext dataContext,
        string query,
        string operationName,
        JObject variables,
        CancellationToken cancellation)
    {
        var executionOptions = new ExecutionOptions
        {
            Schema            = schema,
            Query             = query,
            OperationName     = operationName,
            Inputs            = variables?.ToInputs(),
            UserContext       = dataContext,
            CancellationToken = cancellation,
#if (DEBUG)
            ExposeExceptions = true,
            EnableMetrics    = true,
#endif
        };

        var result = await executer.ExecuteAsync(executionOptions)
                     .ConfigureAwait(false);

        if (result.Errors?.Count > 0)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
        }

        return(result);
    }
示例#26
0
 public static Customer GetCustomer(Int64 custID)
 {
     using (var db = new MyDataContext(Settings.MyConnectionString))
     {
         return(db.Customers.SingleOrDefault(c => c.ID == custID));
     }
 }
示例#27
0
 public async Task <ActiveSubstance> GetActiveSubstanceById(int id)
 {
     using (var activeSubstanceDbContext = new MyDataContext())
     {
         return(await activeSubstanceDbContext.ActiveSubstances.FindAsync(id));
     }
 }
示例#28
0
        public int Post(User user)
        {
            var result = 0;

            using (var db = new MyDataContext())
            {
                try
                {
                    List <User> userMatches = db.Users.Where(x => x.EmailAddress == user.EmailAddress).ToList();
                    User        validUser   = userMatches.Single();

                    if (validUser.Password == user.Password)
                    {
                        result = validUser.UserId;
                    }
                }
                catch (Exception e)
                {
                    throw new ArgumentException("Username and Password do not match", e);
                }



                return(result);
            }
        }
示例#29
0
        private void webBrowser_LoadCompleted(object sender, NavigationEventArgs e)
        {
            // 此处填写 access token callback 地址
            if (e.Uri.ToString().Contains(""))
            {
                var splits = e.Uri.Query.Split('=');
                if (splits.Length <= 1)
                {
                    return;
                }
                ConstantPool.AccessToken = splits[1];
                MyDataContext.CreatetDatabaseIfNeeded();
                SyncCore.GetInst().InitializeSyncCore(ConstantPool.AccessToken, ConstantPool.ScreenWidth);
                btnGoHome.Visibility = Visibility.Visible;
                logout();
            }
#if DEBUG
            else if (e.Uri.ToString().Contains("https://note.youdao.com/oauth/login_mobile.html"))
            {
                const string username = ""; // 填写测试用户名
                const string password = ""; // 填写测试用户密码
                webBrowser.InvokeScript("eval", "document.getElementById('user').value = '" + username + "';document.getElementById('pass').value = '" + password + "';");
            }
#endif
        }
        void CheckFiltersForQuery <T>(MyDataContext db, IQueryable <T> query)
        {
            db.IsSoftDeleteFilterEnabled = true;
            var resultFiltered1 = query.ToArray();

            db.IsSoftDeleteFilterEnabled = false;
            var resultNotFiltered1 = query.ToArray();

            Assert.That(resultFiltered1.Length, Is.LessThan(resultNotFiltered1.Length));

            var currentMissCount = Query <T> .CacheMissCount;

            db.IsSoftDeleteFilterEnabled = true;
            var resultFiltered2 = query.ToArray();

            db.IsSoftDeleteFilterEnabled = false;
            var resultNotFiltered2 = query.ToArray();

            Assert.That(resultFiltered2.Length, Is.LessThan(resultNotFiltered2.Length));

            AreEqualWithComparer(resultFiltered1, resultFiltered2);
            AreEqualWithComparer(resultNotFiltered1, resultNotFiltered2);

            Assert.That(currentMissCount, Is.EqualTo(Query <T> .CacheMissCount), () => "Caching is wrong.");
        }
示例#31
0
        static void Main(string[] args)
        {
            using (var context = new MyDataContext())
            {
                var cat = new Category {
                    Name = "Gifts"
                };
                for (var x = 0; x < 10; x++)
                {
                    Console.WriteLine("Creating 'Product {0}'", x);

                    var prod = new Product
                    {
                        Name     = "Product " + x,
                        Price    = x * 100,
                        Category = cat      // will be created as a child record
                                            // in the same command. Scary but powerful.
                    };

                    context.Products.Add(prod);
                    context.SaveChanges();
                }
            }
            Console.ReadLine();
        }
示例#32
0
        protected bool IsChanged; // что-то было изменено

        protected AppBarViewModel()
        {
            _navigationService = GetService<INavigationService>();
            Message = GetService<IMessageBoxService>();
            LoadedCommand = new RelayCommand(PageLoaded);
            BackKeyPressCommand = new RelayCommand(OnBackKeyPress);

            var app = Application.Current as App;
            if (app != null) MyDataContextBase = app.ActiveBase;
        }
示例#33
0
        public ToursViewModel(ContextMenu test)
        {
            StartTapCommand = new RelayCommand(StartTap);
            EditTapCommand = new RelayCommand(EditTap);
            RemoveTapCommand = new RelayCommand(RemoveTap);
            DeleteTapCommand = new RelayCommand(DeleteTap);
            ItemTapCommand = new RelayCommand<object>(item_tap);
            LoadedCommand = new RelayCommand(PageLoaded);
            BackKeyPressCommand = new RelayCommand(OnBackKeyPress);

            _navigationService = GetService<INavigationService>();
            _message = GetService<IMessageBoxService>();
            _myDataContextBase = GetService<IDataBaseService>().GetDataBase();
            _testContextMenu = test; 

            OnNavigatedTo();
        }
示例#34
0
        public SettingsGeneralViewModel(ContextMenu playerMenu)
        {
            _playerMenu = playerMenu;

            DefaultTapCommand = new RelayCommand(Default_OnTap);
            PivotCommand = new RelayCommand<object>(Pivot_SelectionChanged);
            LoadedCommand = new RelayCommand(PageLoaded);
            PlayerTapCommand = new RelayCommand<object>(PlayerTap);
            RenamePlayerCommand = new RelayCommand(RenameClick);
            DeletePlayerCommand = new RelayCommand(DeleteClick);
            MenuClosedCommand = new RelayCommand(_playerMenu_Closed);

            _navigationService = GetService<INavigationService>();
            _messageBoxService = GetService<IMessageBoxService>();
            SettingsApp = new Settings();

            var app = Application.Current as App;
            if (app != null) _myDataContextBase = app.ActiveBase;

            Players = new ObservableCollection<IPlayer>(from x in _myDataContextBase.Players orderby x.Name select x);
        }
示例#35
0
        private static void Main(string[] args) {
//            Control window = ConsoleApplication.LoadFromXaml( "ConsoleFramework.Layout.xml", null );
////            window.FindChildByName< TextBlock >( "text" ).MouseDown += ( sender, eventArgs ) => {
////                window.FindChildByName< TextBlock >( "text" ).Text = "F";
////                eventArgs.Handled = true;
////            };
////            window.MouseDown += ( sender, eventArgs ) => {
////                window.Width = window.ActualWidth + 3;
////                window.Invalidate(  );
////            };
//            ConsoleApplication.Instance.Run( window );
//            return;

            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = "Examples.GridTest.xml";
            Window createdFromXaml;
            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            using (StreamReader reader = new StreamReader(stream))
            {
                string result = reader.ReadToEnd();
                MyDataContext dataContext = new MyDataContext( );
                dataContext.Str = "Введите заголовок";
                createdFromXaml = XamlParser.CreateFromXaml<Window>(result, dataContext, new List<string>()
                    {
                        "clr-namespace:Xaml;assembly=Xaml",
                        "clr-namespace:ConsoleFramework.Xaml;assembly=ConsoleFramework",
                        "clr-namespace:ConsoleFramework.Controls;assembly=ConsoleFramework",
                    });
            }
//            ConsoleApplication.Instance.Run(createdFromXaml);
//            return;

            using (ConsoleApplication application = ConsoleApplication.Instance) {
                Panel panel = new Panel();
                panel.Name = "panel1";
                panel.HorizontalAlignment =  HorizontalAlignment.Center;
                panel.VerticalAlignment = VerticalAlignment.Stretch;
                panel.XChildren.Add(new TextBlock() {
                    Name = "label1",
                    Text = "Label1",
                    Margin = new Thickness(1,2,1,0)
                    //,Visibility = Visibility.Collapsed
                });
                panel.XChildren.Add(new TextBlock() {
                    Name = "label2",
                    Text = "Label2_____",
                    HorizontalAlignment = HorizontalAlignment.Right
                });
                TextBox textBox = new TextBox() {
                    MaxWidth = 10,
                    Margin = new Thickness(1),
                    HorizontalAlignment = HorizontalAlignment.Center,
                    Size = 15
                };
                Button button = new Button() {
                    Name = "button1",
                    Caption = "Button!",
                    Margin = new Thickness(1),
                    HorizontalAlignment = HorizontalAlignment.Center
                };
                button.OnClick += (sender, eventArgs) => {
                    Debug.WriteLine("Click");
                    MessageBox.Show( "Окно сообщения", "Внимание ! Тестовое сообщение", delegate( MessageBoxResult result ) {  } );
                    Control label = panel.FindDirectChildByName("label1");
                    if (label.Visibility == Visibility.Visible) {
                        label.Visibility = Visibility.Collapsed;
                    } else if (label.Visibility == Visibility.Collapsed) {
                        label.Visibility = Visibility.Hidden;
                    } else {
                        label.Visibility = Visibility.Visible;
                    }
                    label.Invalidate();
                };
                ComboBox comboBox = new ComboBox(  )
                    {
//                        Width = 14
//HorizontalAlignment = HorizontalAlignment.Stretch
                    };
                comboBox.Items.Add( "Сделать одно" );
                comboBox.Items.Add("Сделать второе");
                comboBox.Items.Add("Ничего не делать");
                ListBox listbox = new ListBox(  );
                listbox.Items.Add( "First item" );
                listbox.Items.Add( "second item1!!!!!!1fff" );
                listbox.HorizontalAlignment = HorizontalAlignment.Stretch;
                //listbox.Width = 10;

                panel.XChildren.Add(comboBox);
                panel.XChildren.Add(button);
                panel.XChildren.Add(textBox);
                panel.XChildren.Add(listbox);
                
                //application.Run(panel);
                WindowsHost windowsHost = new WindowsHost()
                                              {
                                                  Name = "WindowsHost"
                                              };
                Window window1 = new Window {
                    X = 5,
                    Y = 4,
                    //MinHeight = 100,
                    //MaxWidth = 30,
                    //Width = 10,
                    Height = 20,
                    Name = "Window1",
                    Title = "Window1",
                    Content = panel
                };
                GroupBox groupBox = new GroupBox(  );
                groupBox.Title = "Группа";
                ScrollViewer scrollViewer = new ScrollViewer(  );
                ListBox listBox = new ListBox(  );
                listBox.Items.Add( "Длинный элемент" );
                listBox.Items.Add("Длинный элемент 2");
                listBox.Items.Add("Длинный элемент 3");
                listBox.Items.Add("Длинный элемент 4");
                listBox.Items.Add("Длинный элемент 5");
                listBox.Items.Add("Длинный элемент 6");
                listBox.Items.Add("Длинный элемент 700");
                listBox.HorizontalAlignment = HorizontalAlignment.Stretch;
                listBox.VerticalAlignment = VerticalAlignment.Stretch;
                scrollViewer.Content = listBox;
//                scrollViewer.HorizontalAlignment = HorizontalAlignment.Stretch;
                scrollViewer.VerticalAlignment = VerticalAlignment.Stretch;
                scrollViewer.HorizontalScrollEnabled = false;

                groupBox.Content = scrollViewer;
                groupBox.HorizontalAlignment = HorizontalAlignment.Stretch;

                windowsHost.Show(new Window() {
                    X = 30,
                    Y = 6,
                    //MinHeight = 10,
                    //MinWidth = 10,
                    Name = "LongTitleWindow",
                    Title = "Очень длинное название окна",
                    Content = groupBox
                });
                windowsHost.Show(window1);
                windowsHost.Show(createdFromXaml);
                //textBox.SetFocus(); todo : научиться задавать фокусный элемент до добавления в визуальное дерево
                //application.TerminalSizeChanged += ( sender, eventArgs ) => {
                //    application.CanvasSize = new Size(eventArgs.Width, eventArgs.Height);
                //   application.RootElementRect = new Rect(new Size(eventArgs.Width, eventArgs.Height));
               // };
				//windowsHost.Width = 80;
				//windowsHost.Height = 20;
				application.Run(windowsHost);//, new Size(80, 30), Rect.Empty);
            }
        }
        public Example()
        {
            InitializeComponent();

            DataContext = new MyDataContext();
        }