Example #1
0
        public static void Connect(string connectionString, AutoCreateOption autoCreateOption)
        {
            ConnectionString = connectionString;

            XpoDefault.DataLayer = XpoDefault.GetDataLayer(ConnectionString, autoCreateOption);
            XpoDefault.Session   = null;
        }
Example #2
0
        static void Main(string[] args)
        {
            XpoDefault.DataLayer = XpoDefault.GetDataLayer(
                MSSqlConnectionProvider.GetConnectionString("(localdb)\\mssqllocaldb", "ModifyXPQueryTest"),
                AutoCreateOption.DatabaseAndSchema);

            CreateTestData();

            using (var uow = new UnitOfWork()) {
                // This works - obviously
                //var data = CollectionData(uow);

                // This also works - returning data from an XPQuery, but without projection
                var data = QueryDataFullObjects(uow);

                // This wouldn't work - if the type is not Person, I couldn't modify it
                // var data = QueryDataPartialObjects(uow);

                ModifyObjects(data);

                uow.CommitChanges();
            }

            OutputData();
        }
Example #3
0
 public static void Initialize(string connectionString, Type sequenceObjectType)
 {
     _sequenceGenerator  = null;
     _sequenceObjectType = sequenceObjectType;
     _defaultDataLayer   = XpoDefault.GetDataLayer(connectionString, AutoCreateOption.None);
     RegisterSequences(ApplicationHelper.Instance.Application.TypesInfo.PersistentTypes);
 }
        private void GetSalesRate()
        {
            try
            {
                string sqlquery = "";
                sqlquery = " select top 1 price from billdet where prodcode='" + Product.Code + "' and Custcode='" + SalesInvoice.Customer.ERPCode + "' order by bill_date desc";
                //Initialize your data layer.
                //By default if you don't do this, XPO will try and use an access databse (jet)
                Session session = new Session();
                XpoDefault.DataLayer = XpoDefault.GetDataLayer(MSSqlConnectionProvider.GetConnectionString(SalesInvoice.Company.ServerName, SalesInvoice.Company.ERPMasterDB + SalesInvoice.Company.Initials), AutoCreateOption.None);
                //XpoDefault.DataLayer = XpoDefault.GetDataLayer(MSSqlConnectionProvider.GetConnectionString("ACC00", SalesInvoice.Company.ERPMasterDB + SalesInvoice.Company.Initials), AutoCreateOption.None);
                XpoDefault.Session = session;

                //Equivalent of SELECT * FROM TableName in SQL
                // YourClassName would be your XPO object (your persistent object)
                using (var uow = new UnitOfWork())
                {
                    SelectedData sd = uow.ExecuteQuery(sqlquery);


                    foreach (var item in sd.ResultSet)
                    {
                        Price = Convert.ToDecimal(item.Rows[0].Values[0]);
                    }
                }
            }
            catch (Exception ex) { }
        }
        public Form1()
        {
            XpoDefault.DataLayer = XpoDefault.GetDataLayer(AutoCreateOption.DatabaseAndSchema);
            CreateDefaultData();

            InitializeComponent();
        }
        static void Main(string[] args)
        {
            string cs = MSSqlConnectionProvider.GetConnectionString("localhost", "XpoSLExample");

            XpoDefault.DataLayer = XpoDefault.GetDataLayer(cs, AutoCreateOption.DatabaseAndSchema);
            XpoDefault.Session   = null;
            try {
                using (UnitOfWork uow = new UnitOfWork()) {
                    uow.UpdateSchema(typeof(Program).Assembly);
                    uow.CreateObjectTypeRecords(typeof(Program).Assembly);
                    Person p = uow.FindObject <Person>(null);
                    if (p == null)
                    {
                        new Person(uow)
                        {
                            FirstName = "Jake", LastName = "Smith", Birthdate = new DateTime(1990, 10, 1)
                        };
                        new Person(uow)
                        {
                            FirstName = "Bill", LastName = "Simpson", Birthdate = new DateTime(1982, 2, 20)
                        };
                        new Person(uow)
                        {
                            FirstName = "Harry", LastName = "Jonathan", Birthdate = new DateTime(1972, 5, 17)
                        };
                        uow.CommitChanges();
                    }
                    Console.WriteLine("Update successful.");
                }
            } catch (Exception) {
                Console.WriteLine("Update failed.");
            }
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
        static void Main()
        {
            string conn = MSSqlConnectionProvider.GetConnectionString("(local)", "Northwind");

            XpoDefault.DataLayer = XpoDefault.GetDataLayer(conn, AutoCreateOption.None);
            Application.Run(new Form1());
        }
Example #8
0
 private void Click_Edit(object sender, RoutedEventArgs e)
 {
     try
     {
         var inMemoryDAL = XpoDefault.GetDataLayer(connectionString, DevExpress.Xpo.DB.AutoCreateOption.DatabaseAndSchema);
         using (var uow = new UnitOfWork(inMemoryDAL))
         {
             XPQuery <Product_ProductReceive> items      = new XPQuery <Product_ProductReceive>(uow);
             Product_ProductReceive           searchItem = items.FirstOrDefault(i => i.ID == Convert.ToInt32(((Windows.UI.Xaml.Controls.ContentControl)sender).Content.ToString()));
             if (!String.IsNullOrEmpty(searchItem.ContainerNo))
             {
                 newContainer.Text = (searchItem.ContainerNo).ToString();
             }
             if (!String.IsNullOrEmpty(searchItem.DriverName))
             {
                 newDriver.Text = (searchItem.DriverName).ToString();
             }
             if (!String.IsNullOrEmpty(searchItem.TruckRegistration))
             {
                 newTruckReg.Text = (searchItem.TruckRegistration).ToString();
             }
             newWbTicket.Text = (searchItem.WBTicket).ToString();
         }
     }
     catch (Exception ex)
     {
         var msg = ex.Message;
     }
 }
Example #9
0
 public MainPage()
 {
     InitializeComponent();
     ThreadPool.QueueUserWorkItem(o => {
         XpoDefault.DataLayer = XpoDefault.GetDataLayer(
             "http://localhost:64466/Service1.svc",
             AutoCreateOption.SchemaAlreadyExists
             );
         session = new Session();
         //It is necessary to call UpdataSchema method for all persistent classes.
         session.UpdateSchema(typeof(Customer));
         if (session.FindObject(typeof(Customer), new BinaryOperator("ContactName", "Alex Smith", BinaryOperatorType.Equal)) == null)
         {
             Customer custAlex = new Customer(session)
             {
                 ContactName = "Alex Smith", CompanyName = "DevExpress"
             };
             custAlex.Save();
             Customer Tom = new Customer(session)
             {
                 ContactName = "Tom Jensen", CompanyName = "ExpressIT"
             };
             Tom.Save();
         }
         session.TypesManager.EnsureIsTypedObjectValid();
         Dispatcher.BeginInvoke(BeginInitializeDataSource);
     });
 }
Example #10
0
 /*
  * Creates a new DAL with the specified settings and initializes the XpoDefault.DataLayer property.
  * As a result, all the units of work (or sessions) will by default access the "Product" database
  * using the specified path.
  */
 private void InitDAL()
 {
     XpoDefault.DataLayer = XpoDefault.GetDataLayer(
         AccessConnectionProvider.GetConnectionString(@"c:\database\product.mdb"),
         AutoCreateOption.DatabaseAndSchema
         );
 }
        public static void InitDAL()
        {
            string cstr = AccessConnectionProvider.GetConnectionString("database.mdb");

            XpoDefault.DataLayer = XpoDefault.GetDataLayer(cstr, AutoCreateOption.DatabaseAndSchema);
            DevExpress.Xpo.XpoDefault.Session = null;
        }
        static IDataLayer SetupDB1()
        {
            string       connString = MSSqlConnectionProvider.GetConnectionString("(local)", "SampleDB1");
            XPDictionary dict       = new ReflectionDictionary();

            dict.CollectClassInfos(typeof(Contact));
            IDataLayer dal = XpoDefault.GetDataLayer(connString, dict, AutoCreateOption.DatabaseAndSchema);

            using (UnitOfWork uow = new UnitOfWork(dal)) {
                uow.UpdateSchema(typeof(Contact));
                if (uow.FindObject <Contact>(null) == null)
                {
                    Contact contact1 = new Contact(uow)
                    {
                        FirstName = "John", LastName = "Doe"
                    };
                    Contact contact2 = new Contact(uow)
                    {
                        FirstName = "Paul", LastName = "Smith"
                    };
                    uow.CommitChanges();
                }
            }
            return(dal);
        }
Example #13
0
        public void updateRecord(int id)
        {
            var inMemoryDAL = XpoDefault.GetDataLayer(connectionString, DevExpress.Xpo.DB.AutoCreateOption.DatabaseAndSchema);

            id = RecId;
            try
            {
                using (var uow = new UnitOfWork(inMemoryDAL))
                {
                    Order_OrderIn searchItem = new XPQuery <Order_OrderIn>(uow).FirstOrDefault(i => i.ID.Equals(lblOrderNo.Text));
                    //ExpectedTrucks searchTruck = new XPQuery<ExpectedTrucks>(uow).FirstOrDefault(i => i.ID == Convert.ToInt32(lblExpTruck.Text));
                    //Library_Supplier L_SearchItem = new XPQuery<Library_Supplier>(uow).FirstOrDefault(i => i.Name == (SupplierComboBox.SelectedValue.ToString()));
                    Library_Transporter    LT_SearchItem = new XPQuery <Library_Transporter>(uow).FirstOrDefault(i => i.Name == (TransComboBox.SelectedValue.ToString()));
                    Product_ProductReceive pr            = new XPQuery <Product_ProductReceive>(uow).FirstOrDefault(i => i.ID.Equals(id));
                    tar            = Convert.ToDouble(txtTar.Text);
                    gross          = Convert.ToDouble(txtGross.Text);
                    txtNett.Text   = calcNettWeight(tar, gross).ToString();
                    pr.TarWeight   = tar;
                    pr.GrossWeight = gross;
                    pr.NettWeight  = calcNettWeight(tar, gross);
                    //pr.SupplierID = L_SearchItem;
                    pr.RecOrderID = searchItem;
                    //pr.ExpectedID = searchTruck;
                    pr.TransporterID = LT_SearchItem;
                    //pr.DateModified = DateTime.Now;
                    pr.DriverName = newDriver.Text;
                    pr.NettWeight = calcNettWeight(Convert.ToDouble(txtGross.Text), Convert.ToDouble(txtNett.Text));
                    uow.CommitChanges();
                }
            }
            catch (Exception ex)
            {
            }
        }
Example #14
0
        public void PopulateTransCombobox()
        {
            var inMemoryDAL = XpoDefault.GetDataLayer(connectionString, DevExpress.Xpo.DB.AutoCreateOption.DatabaseAndSchema);

            try
            {
                using (var uow = new UnitOfWork(inMemoryDAL))
                {
                    XPCollection <Library_Transporter> Library_Transporters = new XPCollection <Library_Transporter>(uow);
                    //LookupEdit2.ItemsSource = new XPCollection<Order_OrderIn>(uow);
                    var list = Library_Transporters.Select(i => new { ID = (i.ID).ToString(), Name = i.Name }).ToList();
                    foreach (var item in list.Distinct())
                    {
                        ComboBoxItem comboItem = new ComboBoxItem();
                        comboItem.Content = item.Name;
                        comboItem.Tag     = item.ID;
                        TransComboBox.Items.Add(comboItem);
                    }
                }
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
            }
        }
Example #15
0
        public Form1()
        {
            InitializeComponent();



            try
            {
                SecurityUser user = new SecurityUser();
                user.ReadConnection("Nour", "Nour");

                XpoDefault.DataLayer     = XpoDefault.GetDataLayer(user.ConnectionString, DevExpress.Xpo.DB.AutoCreateOption.SchemaOnly);
                SecurityUser.CurrentUser = user;
                SecurityUser.IsConnected = true;


                Session            s   = new Session();
                List <XPClassInfo> lst = new List <XPClassInfo>()
                {
                    Session.DefaultSession.GetClassInfo(typeof(CoreLib.Grid.UserProfile.UIMaster)),
                    Session.DefaultSession.GetClassInfo(typeof(CoreLib.Grid.UserProfile.UIParams)),
                    Session.DefaultSession.GetClassInfo(typeof(CoreLib.Grid.UserProfile.UIProfile)),
                    Session.DefaultSession.GetClassInfo(typeof(CoreLib.Grid.UserProfile.UIProfileLine))
                };
                //s.UpdateSchema();
                Assembly a = Assembly.GetAssembly(typeof(CoreLib.MyForm));
                s.UpdateSchema(a);
                myGridView1.UnitOfWorkXpo = unitOfWork1;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        static void Main(string[] args)
        {
            byte[] data = new byte[5] {
                5, 4, 3, 2, 1
            };

            XpoDefault.DataLayer = XpoDefault.GetDataLayer(AutoCreateOption.DatabaseAndSchema);
            //new Session().ClearDatabase();

            using (UnitOfWork uof = new UnitOfWork()) {
                if (uof.FindObject <MyObject>(null) == null)
                {
                    Console.WriteLine("Creating a default object...");
                    MyObject obj = new MyObject(uof);
                    obj.Name             = "pict";
                    obj.DocumentInternal = data;
                    uof.CommitChanges();
                }
            }

            using (UnitOfWork uof = new UnitOfWork()) {
                Console.WriteLine("Loading MyObject...");
                MyObject obj = uof.FindObject <MyObject>(null);
                Console.WriteLine(obj.Name);
                byte[] loaded = obj.Document;
                Console.WriteLine(loaded.Length);
            }

            Console.WriteLine("Press <Enter> to exit.");
            Console.ReadLine();
        }
Example #17
0
        private void simpleAction1_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Password=;User ID=Admin;Data Source=TestProject.mdb;Mode=Share Deny None;";

            XpoDefault.DataLayer = XpoDefault.GetDataLayer(connectionString, AutoCreateOption.DatabaseAndSchema);
            Session session = new Session();

            for (int i = 1; i < 101; i++)
            {
                Airport a = new Airport(session);
                a.NameOfAirport = "Аэропорт" + i.ToString();
                Pilot b = new Pilot(session);
                b.FullName = "Пилот" + i.ToString();
                Pilot c = new Pilot(session);
                c.FullName = "Pilot" + i.ToString();
                Plane d = new Plane(session);
                d.NameOfPlane = "Самолет" + i.ToString();
                b.Planes.Add(d);
                c.Planes.Add(d);
                b.Airport = a;
                c.Airport = a;
                d.Airport = a;
                a.Save();
                b.Save();
                c.Save();
                d.Save();
            }
        }
Example #18
0
        public static IDataLayer GetDataLayer()
        {
            XpoDefault.Session = null;
            var uow           = XpoHelper.GetNewUnitOfWork();
            var sqlConnection = uow.FindObject <SQLConnection>(CriteriaOperator.Parse("Oid==?", 1));
            //string conn = MySqlConnectionProvider.GetConnectionString("localhost", "root", "", "CUFE");
            string sqlConnectionString = MSSqlConnectionProvider.GetConnectionString(sqlConnection.IP, sqlConnection.user, sqlConnection.password, sqlConnection.Datenbank);
            //string conn = System.Configuration.ConfigurationManager.ConnectionStrings[sqlConnectionString].ConnectionString;
            XPDictionary dict  = new ReflectionDictionary();
            IDataStore   store = XpoDefault.GetConnectionProvider(sqlConnectionString, AutoCreateOption.None);

            //DevExpress.Xpo.Metadata.ReflectionClassInfo.SuppressSuspiciousMemberInheritanceCheck = true;
            //dict.GetDataStoreSchema(typeof(Inscripcion).Assembly);
            //IDataLayer dl = new ThreadSafeDataLayer(dict, store);
            ////using (UnitOfWork uow = new UnitOfWork(dl))
            ////{
            ////    int cnt = (int)uow.Evaluate<CUFE.Models.Country>(CriteriaOperator.Parse("count"), null);
            ////    if (cnt == 0)
            ////    {
            ////        new CUFE.Models.Country(uow) { CountryName = "Germany" };
            ////        uow.CommitChanges();
            ////    }
            ////}
            //return dl;

            return(XpoDefault.GetDataLayer(sqlConnectionString, AutoCreateOption.SchemaAlreadyExists));
        }
        public static void Seed()
        {
            string connStr   = ConfigurationManager.ConnectionStrings["XpoTutorial"].ConnectionString;
            var    dataLayer = XpoDefault.GetDataLayer(connStr, DevExpress.Xpo.DB.AutoCreateOption.DatabaseAndSchema);

            using (UnitOfWork uow = new UnitOfWork(dataLayer)) {
                if (uow.Query <RevenueAnalysisDataItem>().Count() > 0)
                {
                    return;
                }
                int year = DateTime.Today.Year;
                for (int i = 0; i < 1000; i++)
                {
                    ProductCategory         category = productCategories[rnd.Next(productCategories.Length)];
                    RevenueAnalysisDataItem item     = new RevenueAnalysisDataItem(uow)
                    {
                        Category  = category.Category,
                        Product   = category.Products[rnd.Next(category.Products.Length)],
                        State     = states[rnd.Next(states.Length)],
                        UnitsSold = rnd.Next(5, 100),
                        Revenue   = rnd.Next(5, 100),
                        Year      = rnd.Next(year - 5, year + 1)
                    };
                }
                uow.CommitChanges();
            }
        }
Example #20
0
        static void Main(params string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            try
            {
                var config  = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal);
                var sqlConn = config.ConnectionStrings.ConnectionStrings["Model22"].ConnectionString;

                XpoDefault.DataLayer = XpoDefault.GetDataLayer(sqlConn, AutoCreateOption.None);

                if (XpoDefault.DataLayer != null)
                {
                    XpoDefault.Session.ExecuteNonQuery(@" ALTER SESSION SET NLS_LANGUAGE= 'AMERICAN' NLS_TERRITORY= 'AMERICA' NLS_ISO_CURRENCY= 'AMERICA' NLS_DATE_FORMAT= 'DD/MM/RRRR' NLS_DATE_LANGUAGE= 'AMERICAN' NLS_SORT= 'BINARY' ");

                    Login.USUARIO_ID      = ObterUsuario(args);
                    Login.FILIALCONECTADA = new FILIAL().GetFilialConectada(Login.USUARIO_ID, Environment.MachineName);
                    Login.CONECTADO       = true;
                }

                Application.Run(new MainForm());
            }
            catch (Exception ex)
            {
                Util.ShowMessageError(ex);
            }
        }
Example #21
0
        public static void Tests(string dbName, string connectionString) => Describe($"{nameof(XPUserStore<IdentityUser, string, IdentityUserClaim<string>, IdentityUserLogin<string>, IdentityUserToken<string>, XpoIdentityUser, XpoIdentityRole, XpoIdentityUserClaim, XpoIdentityUserLogin, XpoIdentityUserToken>)} using {dbName}", () =>
        {
            var dataLayer = XpoDefault.GetDataLayer(connectionString, DevExpress.Xpo.DB.AutoCreateOption.DatabaseAndSchema);

            UnitOfWork unitOfWorkFactory() => new UnitOfWork(dataLayer);

            (XPUserStore <IdentityUser, string, IdentityUserClaim <string>, IdentityUserLogin <string>, IdentityUserToken <string>, XpoIdentityUser, XpoIdentityRole, XpoIdentityUserClaim, XpoIdentityUserLogin, XpoIdentityUserToken> store, UnitOfWork uow)CreateStore()
            {
                var uow   = new UnitOfWork(dataLayer);
                var store = new XPUserStore <
                    IdentityUser,
                    string,
                    IdentityUserClaim <string>,
                    IdentityUserLogin <string>,
                    IdentityUserToken <string>,
                    XpoIdentityUser,
                    XpoIdentityRole,
                    XpoIdentityUserClaim,
                    XpoIdentityUserLogin,
                    XpoIdentityUserToken
                    >(
                    uow,
                    new FakeLogger <XPUserStore <IdentityUser, string, IdentityUserClaim <string>, IdentityUserLogin <string>, IdentityUserToken <string>, XpoIdentityUser, XpoIdentityRole, XpoIdentityUserClaim, XpoIdentityUserLogin, XpoIdentityUserToken> >(),
                    new IdentityErrorDescriber()
                    );
                return(store, uow);
            }
            XpoIdentityUser CreateUser(UnitOfWork uow, string id = null) => new XpoIdentityUser(uow)
        private static IDataLayer GetDataLayer()
        {
            return(XpoDefault.GetDataLayer(_connectionString, AutoCreateOption.DatabaseAndSchema));

            //Use below code when want to use WCF service for cache data store.
            //return XpoDefault.GetDataLayer("http://localhost:59370/DataService.svc", AutoCreateOption.DatabaseAndSchema);
        }
Example #23
0
        protected void Session_Start(Object sender, EventArgs e)
        {
            Tracing.Initialize();
            WebApplication.SetInstance(Session, new DoSoReportingAspNetApplication());
            DevExpress.ExpressApp.Web.Templates.DefaultVerticalTemplateContentNew.ClearSizeLimit();
            WebApplication.Instance.SwitchToNewStyle();
            if (ConfigurationManager.ConnectionStrings["ConnectionString"] != null)
            {
                WebApplication.Instance.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            }

            XpoDefault.DataLayer = XpoDefault.GetDataLayer(WebApplication.Instance.ConnectionString, DevExpress.Xpo.DB.AutoCreateOption.SchemaAlreadyExists);

#if EASYTEST
            if (ConfigurationManager.ConnectionStrings["EasyTestConnectionString"] != null)
            {
                WebApplication.Instance.ConnectionString = ConfigurationManager.ConnectionStrings["EasyTestConnectionString"].ConnectionString;
            }
#endif
            if (System.Diagnostics.Debugger.IsAttached && WebApplication.Instance.CheckCompatibilityType == CheckCompatibilityType.DatabaseSchema)
            {
                WebApplication.Instance.DatabaseUpdateMode = DatabaseUpdateMode.UpdateDatabaseAlways;
            }
            WebApplication.Instance.Setup();
            WebApplication.Instance.Start();
        }
Example #24
0
        public static void Tests(string name, string connectionString) => Describe($"{nameof(TrialRequestCommandHandler)} using {name}", () =>
        {
            var dataLayer        = XpoDefault.GetDataLayer(connectionString, DevExpress.Xpo.DB.AutoCreateOption.DatabaseAndSchema);
            using var unitOfWork = new UnitOfWork(dataLayer);
            var settings         = unitOfWork.CreateDefaultSettings();

            unitOfWork.UpdateSchema();
            unitOfWork.Save(settings);
            unitOfWork.CommitChanges();

            async Task <TrialRequestResult> ExecuteCommand(TrialRequestCommand command)
            {
                using var uow = new UnitOfWork(dataLayer);
                return(await new TrialRequestCommandHandler(uow).ExecuteAsync(command));
            }

            Describe("can request a trial", () =>
            {
                It("With normal user", async() =>
                {
                    var trial = await ExecuteCommand(new TrialRequestCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, null));

                    trial.ShouldSatisfyAllConditions(
                        () => trial.ShouldNotBeNull(),
                        () => trial.Id.ShouldNotBe(default),
                        () => trial.ExpiresAt.Date.ShouldBe(DateTime.Today.AddDays(settings.DefaultTrialPeriod)),
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            XpoDefault.TrackPropertiesModifications = true;
            SafePostgreSqlConnectionProvider.Register();

            XpoDefault.DataLayer = XpoDefault.GetDataLayer(Configuration.GetConnectionString("DXConnection"), DevExpress.Xpo.DB.AutoCreateOption.None);

            services.AddScoped <UnitOfWork>();

            var result = typeof(BlBase <>).Assembly
                         .GetTypes()
                         .Where(t => t.ParentTypes().Any(p => p.IsGenericType && p.GetGenericTypeDefinition() == typeof(BlBase <>)));

            foreach (var type in result)
            {
                services.AddScoped(type);
            }

            services.AddScoped <IApiService, ApiService>();
            services.AddScoped(typeof(IRepositoryID <>), typeof(DBRepository <>));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "My API", Version = "v1"
                });
            });
        }
        static void Main(string[] args)
        {
            XpoDefault.DataLayer = XpoDefault.GetDataLayer("http://localhost:55777/Service1.svc", AutoCreateOption.DatabaseAndSchema);

            XpoDefault.Session = null;

            using (UnitOfWork uow = new UnitOfWork()) {
                if (uow.FindObject(typeof(Customer), new BinaryOperator("ContactName", "Alex Smith", BinaryOperatorType.Equal)) == null)
                {
                    Customer custAlex = new Customer(uow);
                    custAlex.ContactName = "Alex Smith";
                    custAlex.CompanyName = "DevExpress";
                    custAlex.Save();

                    Customer Tom = new Customer(uow);
                    Tom.ContactName = "Tom Jensen";
                    Tom.CompanyName = "ExpressIT";
                    Tom.Save();
                    uow.CommitChanges();
                }
                using (XPCollection <Customer> customers = new XPCollection <Customer>(uow)) {
                    foreach (Customer customer in customers)
                    {
                        Console.WriteLine("Company Name = {0}; ContactName = {1}", customer.CompanyName, customer.ContactName);
                    }
                }
            }

            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
Example #27
0
 private static void InitDAL()
 {
     XpoDefault.DataLayer = XpoDefault.GetDataLayer(
         @"XpoProvider=MSSqlServer;data source=(local);integrated security=SSPI;initial catalog=E771",
         DevExpress.Xpo.DB.AutoCreateOption.DatabaseAndSchema);
     XpoDefault.Session = null;
 }
            //Dennis: It is important to set the SequenceGenerator.DefaultDataLayer property to the main application data layer.
            //If you use a custom IObjectSpaceProvider implementation, ensure that it exposes a working IDataLayer.
            public static void Initialize()
            {
                Guard.ArgumentNotNull(Application, "Application");
                XPObjectSpaceProvider provider = Application.ObjectSpaceProvider as XPObjectSpaceProvider;

                if (provider != null)
                {
                    Guard.ArgumentNotNull(provider, "provider");
                    if (provider.DataLayer == null)
                    {
                        provider.CreateObjectSpace();
                    }
                    if (provider.DataLayer is ThreadSafeDataLayer)
                    {
                        SequenceGenerator.DefaultDataLayer = XpoDefault.GetDataLayer(
                            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString,
                            XpoTypesInfoHelper.GetXpoTypeInfoSource().XPDictionary,
                            DevExpress.Xpo.DB.AutoCreateOption.None);
                    }
                    else
                    {
                        SequenceGenerator.DefaultDataLayer = provider.DataLayer;
                    }
                }
            }
Example #29
0
        private static void ConxionBaseDeDatos()
        {
            //Bases de datos soportadas
            //https://documentation.devexpress.com/#CoreLibraries/CustomDocument2114

            //Ejemplos de conexion para todas las bases de XPO
            //https://www.devexpress.com/Support/Center/Question/Details/K18445



            //Conexion a access, el provedor esta en el namspace DevExpress.Xpo.DB, alli estan los demas proveedores, como OracleConnectionProvider o MSSqlConnectionProvider
            //estos proveedores son clases estaticas que tiene un metodo para crear la cadena de conexion, esta cadena tambien se puede crear a mano segun los ejemplos de el link
            //https://www.devexpress.com/Support/Center/Question/Details/K18445 o con la clase estatica segun los ejemplos de este link
https:      //documentation.devexpress.com/#CoreLibraries/CustomDocument3243


            //TODO quitar el comentario para usar access o mysql

            //Access
            //string conn = AccessConnectionProvider.GetConnectionString(@"EjemplosXPO.mdb");

            //MySQL
            string conn = MySqlConnectionProvider.GetConnectionString("localhost", "root", "JoseManuel16", "EjemplosXPO");


            //TIP # 3. Explicitly set the XpoDefault.DataLayer property in the entry point of your application.
            //https://www.devexpress.com/Support/Center/Question/Details/A2944
            XpoDefault.DataLayer = XpoDefault.GetDataLayer(conn, AutoCreateOption.DatabaseAndSchema);
        }
Example #30
0
        /// <summary>
        /// It does load database connection.
        /// </summary>
        public static void LoadingDatabaseConnection()
        {
            try {
                // Database connection string properties.
                var server     = @"ALBERTO-PC\SQL";
                var dbUser     = "******";
                var dbPassword = "******";
                var dbName     = "XpoTestDatabase";

                // It does create the database connection and bring back the unit of work that will be used.
                var connection     = MSSqlConnectionProvider.GetConnectionString(server, dbUser, dbPassword, dbName);
                var dataLayerLocal = XpoDefault.GetDataLayer(connection, AutoCreateOption.DatabaseAndSchema);
                var unitOfWork     = new UnitOfWork(dataLayerLocal);

                unitOfWork.Connect();

                // It does update database structure.
                unitOfWork.UpdateSchema();

                // It does create a new user.
                var user = new User(unitOfWork);
                user.UserName = "******";
                user.Password = "******";

                // It does persist new user data in datbase.
                unitOfWork.CommitChanges();
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }