コード例 #1
0
        public void SqlQuerySingleEntity()
        {
            var session = new DataSession("Tracker").Log(Console.WriteLine);
            session.Should().NotBeNull();

            string email = "*****@*****.**";
            string sql = "select * from [User] where EmailAddress = @EmailAddress";

            var user = session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .QuerySingle(r => new User
                {
                    Id = r.GetInt32("Id"),
                    EmailAddress = r.GetString("EmailAddress"),
                    FirstName = r.GetString("FirstName"),
                    LastName = r.GetString("LastName"),
                    Avatar = (Byte[])r.GetValue("Avatar"),
                    CreatedDate = r.GetDateTime("CreatedDate"),
                    ModifiedDate = r.GetDateTime("ModifiedDate"),
                    RowVersion = (Byte[])r.GetValue("RowVersion"),
                    PasswordHash = r.GetString("PasswordHash"),
                    PasswordSalt = r.GetString("PasswordSalt"),
                    Comment = r.GetString("Comment"),
                    IsApproved = r.GetBoolean("IsApproved"),
                    LastLoginDate = r.GetDateTime("LastLoginDate"),
                    LastActivityDate = r.GetDateTime("LastActivityDate"),
                    LastPasswordChangeDate = r.GetDateTime("LastPasswordChangeDate"),
                    AvatarType = r.GetString("AvatarType"),
                });

            user.Should().NotBeNull();
            user.EmailAddress.Should().Be(email);
        }
コード例 #2
0
ファイル: PayeeMethods.cs プロジェクト: Meracord/DotNetSDK
        /// <summary>
        /// Execute sample method calls
        /// </summary>
        public static string Perform()
        {
            try
            {
                var groupNumber = Settings.GroupNumber;
                var referenceId = Helper.RandomAlphaNumericString(15);

                _session = SessionFactory.Create();

                var transportPayee = GetTransportPayee(groupNumber, referenceId);

                var result = _session.Payee.Create(transportPayee);
                var newAccountNumber = result.AccountNumber;
                Helper.ShowResults("Payee.Create()", result);

                var documentPath = Settings.DocumentPath;
                var document = DocumentFactory.Create(documentPath, DocumentType.PayeeAccountAuthorizationAgreement);
                Helper.ShowResults("Payee.CreateDocument()", CreateDocument(_session, newAccountNumber, document));

                var transportPayeeContact = GetTransportPayeeContact(newAccountNumber, transportPayee);
                result = _session.Payee.EditContact(transportPayeeContact);
                Helper.ShowResults("Payee.EditContact()", result);
            }
            catch (Exception ex)
            {
                Helper.DisplayException(ex);
            }

            return null;
        }
コード例 #3
0
ファイル: AccountMethods.cs プロジェクト: Meracord/DotNetSDK
        /// <summary>
        /// Execute sample method calls
        /// </summary>
        public static string Perform()
        {
            try
            {
                var groupNumber = Settings.GroupNumber;
                var newCustomerId = Helper.RandomAlphaNumericString(15);

                _session = SessionFactory.Create();

                var transportAccount = GetTransportAccount(groupNumber, newCustomerId);

                var newAccountNumber = AccountCreate(transportAccount);

                AccountPlaceHold(newAccountNumber);

                AccountReleaseHold(newAccountNumber);

                AccountEdit(transportAccount, newAccountNumber);

                AccountEditError(transportAccount);

                AccountFindByCustomerId(groupNumber, newCustomerId);

                return newAccountNumber;
            }
            catch (Exception ex)
            {
                Helper.DisplayException(ex);
            }

            return null;
        }
コード例 #4
0
 private void cboProject_SelectedIndexChanged(object sender, EventArgs e)
 {
     Application.DoEvents();
     dApp = new DataApplication((string)cboProject.SelectedItem, AppInMeta.Name);
     dSess = dApp.CreateSession();
     bt_OK.Enabled = true;
 }
コード例 #5
0
 public void CreateConnectionName()
 {
     var session = new DataSession("Tracker");
     session.Should().NotBeNull();
     session.Connection.Should().NotBeNull();
     session.Connection.State.Should().Be(ConnectionState.Closed);
 }
コード例 #6
0
        public void SqlQuerySingleEntityFactoryCache()
        {
            var session = new DataSession("Tracker").Log(Console.WriteLine);
            session.Should().NotBeNull();

            string email = "*****@*****.**";
            string sql = "select * from [User] where EmailAddress = @EmailAddress";

            var policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(5) };

            var user = session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .UseCache(policy)
                .QuerySingle<User>();

            user.Should().NotBeNull();
            user.EmailAddress.Should().Be(email);

            var cachedUser = session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .UseCache(policy)
                .QuerySingle<User>();

            cachedUser.Should().NotBeNull();
            cachedUser.EmailAddress.Should().Be(email);

        }
コード例 #7
0
 public void CreateConnection()
 {
     var sqlConnection = new SqlConnection("Data Source=(local);Initial Catalog=Tracker;Integrated Security=True;");
     var session = new DataSession(sqlConnection);
     session.Should().NotBeNull();
     session.Connection.Should().NotBeNull();
     session.Connection.State.Should().Be(ConnectionState.Closed);
 }
コード例 #8
0
        public void WriteServer()
        {
            var session = new DataSession("Tracker").Log(Console.WriteLine);
            session.Should().NotBeNull();

            string email = "*****@*****.**";
            string sql = "select * from [User] where EmailAddress like @EmailAddress";

            var users = session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .Query(r => new User
                {
                    Id = r.GetInt32("Id"),
                    EmailAddress = r.GetString("EmailAddress"),
                    FirstName = r.GetString("FirstName"),
                    LastName = r.GetString("LastName"),
                    Avatar = (Byte[])r.GetValue("Avatar"),
                    CreatedDate = r.GetDateTime("CreatedDate"),
                    ModifiedDate = r.GetDateTime("ModifiedDate"),
                    RowVersion = (Byte[])r.GetValue("RowVersion"),
                    PasswordHash = r.GetStringNull("PasswordHash"),
                    PasswordSalt = r.GetStringNull("PasswordSalt"),
                    Comment = r.GetStringNull("Comment"),
                    IsApproved = r.GetBoolean("IsApproved"),
                    LastLoginDate = r.GetDateTimeNull("LastLoginDate"),
                    LastActivityDate = r.GetDateTime("LastActivityDate"),
                    LastPasswordChangeDate = r.GetDateTimeNull("LastPasswordChangeDate"),
                    AvatarType = r.GetStringNull("AvatarType"),
                })
                .ToList();

            users.Should().NotBeNull();
            users.Should().NotBeEmpty();

            long ticks = DateTime.Now.Ticks;

            foreach (var u in users)
                u.EmailAddress = u.EmailAddress.Replace("@battlestar", "@u" + ticks);

            session.BulkCopy("[User]")
                .Mapping("EmailAddress", "EmailAddress")
                .Mapping("FirstName", "FirstName")
                .Mapping("LastName", "LastName")
                .Mapping("CreatedDate", "CreatedDate")
                .Mapping("ModifiedDate", "ModifiedDate")
                .Mapping("PasswordHash", "PasswordHash")
                .Mapping("PasswordSalt", "PasswordSalt")
                .Mapping("Comment", "Comment")
                .Mapping("IsApproved", "IsApproved")
                .Mapping("LastLoginDate", "LastLoginDate")
                .Mapping("LastActivityDate", "LastActivityDate")
                .Mapping("LastPasswordChangeDate", "LastPasswordChangeDate")
                .Mapping("AvatarType", "AvatarType")
                .WriteToServer(users);
        }
コード例 #9
0
        public void EnsureConnectionByName()
        {
            var session = new DataSession("Tracker");
            session.Should().NotBeNull();
            session.Connection.Should().NotBeNull();
            session.Connection.State.Should().Be(ConnectionState.Closed);

            session.EnsureConnection();
            session.Connection.State.Should().Be(ConnectionState.Open);

            session.ReleaseConnection();
            session.Connection.State.Should().Be(ConnectionState.Closed);
        }
コード例 #10
0
        public void SqlQuerySingleEntityFactory()
        {
            var session = new DataSession("Tracker").Log(Console.WriteLine);
            session.Should().NotBeNull();

            string email = "*****@*****.**";
            string sql = "select * from [User] where EmailAddress = @EmailAddress";

            var user = session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .QuerySingle<User>();

            user.Should().NotBeNull();
            user.EmailAddress.Should().Be(email);
        }
コード例 #11
0
ファイル: TransferMethods.cs プロジェクト: Meracord/DotNetSDK
        /// <summary>
        /// Execute sample method calls
        /// </summary>
        public static void Perform(string accountNumber)
        {
            try
            {
                _session = SessionFactory.Create();

                var sourceAccountNumber = GetAdministrativeAccount();

                CreateTransfer(sourceAccountNumber, accountNumber);

            }
            catch (Exception ex)
            {
                Helper.DisplayException(ex);
            }
        }
コード例 #12
0
        /// <summary>
        /// Get refresh token using user and audience
        /// </summary>
        /// <param name="user">User</param>
        /// <param name="audience">Audience</param>
        /// <returns>Returns refresh token or null</returns>
        private RefreshToken GetRefreshToken(User user, Audience audience)
        {
            //Validazione argomenti
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (audience == null)
            {
                throw new ArgumentNullException(nameof(audience));
            }

            //Esecuzione in transazione
            using (var t = DataSession.BeginTransaction())
            {
                //Estrazione dati e commit
                var result = _RefreshTokenRepository.GetSingle(a =>
                                                               a.UserName == user.UserName && a.ClientId == audience.ClientId);
                t.Commit();
                return(result);
            }
        }
コード例 #13
0
 public DepartmentModel[] Post([FromBody] DepartmentModel model)
 {
     if (model.DepartmentID > 0)
     {
         //update existing
         var entity = DataSession.Single <Department>(model.DepartmentID);
         entity.DepartmentName = model.DepartmentName;
         DataSession.SaveOrUpdate(entity);
         return(new DepartmentModel[] { GetModel(entity) });
     }
     else
     {
         //add new
         var entity = new Department()
         {
             DepartmentName = model.DepartmentName,
             Org            = DataSession.Single <Org>(model.OrgID)
         };
         DataSession.SaveOrUpdate(entity);
         return(Get(model.OrgID));
     }
 }
コード例 #14
0
        private IEnumerable <Approver> CreateApprovers(IQueryable <Ordering.Approver> query)
        {
            var join = query.Join(DataSession.Query <Data.ClientInfo>(),
                                  o => o.ApproverID,
                                  i => i.ClientID,
                                  (o, i) => new { Approver = o, ClientInfo = i });

            var result = join.Select(x => new Approver()
            {
                ClientID   = x.Approver.ClientID,
                UserName   = x.ClientInfo.UserName,
                ApproverID = x.Approver.ApproverID,
                LName      = x.ClientInfo.LName,
                FName      = x.ClientInfo.FName,
                Email      = x.ClientInfo.Email,
                Phone      = x.ClientInfo.Phone,
                IsPrimary  = x.Approver.IsPrimary,
                Active     = x.Approver.Active
            }).ToList();

            return(result);
        }
コード例 #15
0
ファイル: UtilityModel.cs プロジェクト: lurienanofab/data
        public ActiveLog[] GetLastActiveLogs(int currentUserClientId)
        {
            List <ActiveLog> list = new List <ActiveLog>();

            string tableName = !string.IsNullOrEmpty(TableName) ? TableName.ToLower() : "client";
            int    id        = Record != 0 ? Record : currentUserClientId;

            var current = DataSession.Query <ActiveLog>().Where(x => x.TableName.ToLower() == tableName && x.Record == id).OrderByDescending(x => x.LogID).FirstOrDefault();

            list.Add(current);

            switch (tableName)
            {
            case "clientaccount":
                var ca = DataSession.Single <ClientAccount>(Record);
                list.Add(DataSession.Query <ActiveLog>().Where(x => x.TableName == "ClientOrg" && x.Record == ca.ClientOrg.ClientOrgID).OrderByDescending(x => x.LogID).FirstOrDefault());
                list.Add(DataSession.Query <ActiveLog>().Where(x => x.TableName == "Client" && x.Record == ca.ClientOrg.Client.ClientID).OrderByDescending(x => x.LogID).FirstOrDefault());
                list.Add(DataSession.Query <ActiveLog>().Where(x => x.TableName == "Account" && x.Record == ca.Account.AccountID).OrderByDescending(x => x.LogID).FirstOrDefault());
                list.Add(DataSession.Query <ActiveLog>().Where(x => x.TableName == "Org" && x.Record == ca.ClientOrg.Org.OrgID).OrderByDescending(x => x.LogID).FirstOrDefault());
                break;

            case "clientorg":
                var co = DataSession.Single <ClientOrg>(Record);
                list.Add(DataSession.Query <ActiveLog>().Where(x => x.TableName == "Client" && x.Record == co.Client.ClientID).OrderByDescending(x => x.LogID).FirstOrDefault());
                list.Add(DataSession.Query <ActiveLog>().Where(x => x.TableName == "Org" && x.Record == co.Org.OrgID).OrderByDescending(x => x.LogID).FirstOrDefault());
                break;

            case "clientmanager":
                var cm = DataSession.Single <ClientManager>(Record);
                list.Add(CopyActiveLog(DataSession.Query <ActiveLog>().Where(x => x.TableName == "ClientOrg" && x.Record == cm.ClientOrg.ClientOrgID).OrderByDescending(x => x.LogID).FirstOrDefault(), "{0} (User)"));
                list.Add(CopyActiveLog(DataSession.Query <ActiveLog>().Where(x => x.TableName == "ClientOrg" && x.Record == cm.ManagerOrg.ClientOrgID).OrderByDescending(x => x.LogID).FirstOrDefault(), "{0} (Manager)"));
                list.Add(CopyActiveLog(DataSession.Query <ActiveLog>().Where(x => x.TableName == "Client" && x.Record == cm.ClientOrg.Client.ClientID).OrderByDescending(x => x.LogID).FirstOrDefault(), "{0} (User)"));
                list.Add(CopyActiveLog(DataSession.Query <ActiveLog>().Where(x => x.TableName == "Client" && x.Record == cm.ManagerOrg.Client.ClientID).OrderByDescending(x => x.LogID).FirstOrDefault(), "{0} (Manager)"));
                list.Add(CopyActiveLog(DataSession.Query <ActiveLog>().Where(x => x.TableName == "Org" && x.Record == cm.ClientOrg.Org.OrgID).OrderByDescending(x => x.LogID).FirstOrDefault(), "{0} (Both)"));
                break;
            }

            return(list.ToArray());
        }
コード例 #16
0
        public void ModifyCategory(int categoryId, string categoryName, string categoryNumber)
        {
            var cat = Require <Ordering.PurchaseOrderCategory>(x => x.CatID, categoryId);

            var existing = DataSession.Query <Ordering.PurchaseOrderCategory>().FirstOrDefault(x => x.ParentID == cat.ParentID && x.CatNo == categoryNumber && x.CatID != categoryId);

            if (existing != null)
            {
                if (existing.Active)
                {
                    throw new Exception($"A category already exists with category number: {categoryNumber}");
                }
                else
                {
                    existing.Active = true;
                    return;
                }
            }

            cat.CatName = categoryName;
            cat.CatNo   = categoryNumber;
        }
コード例 #17
0
        private IEnumerable <Purchaser> CreatePurchasers(IQueryable <Ordering.Purchaser> query)
        {
            var join = query.Join(DataSession.Query <Data.ClientInfo>(),
                                  o => o.Client.ClientID,
                                  i => i.ClientID,
                                  (o, i) => new { Purchaser = o, ClientInfo = i });

            var result = join.Select(x => new Purchaser()
            {
                PurchaserID = x.Purchaser.PurchaserID,
                ClientID    = x.ClientInfo.ClientID,
                UserName    = x.ClientInfo.UserName,
                LName       = x.ClientInfo.LName,
                FName       = x.ClientInfo.FName,
                Email       = x.ClientInfo.Email,
                Phone       = x.ClientInfo.Phone,
                Active      = x.Purchaser.Active,
                Deleted     = x.Purchaser.Deleted
            }).ToList();

            return(result);
        }
コード例 #18
0
        public Account AddOrUpdate(int clientId, int accountId)
        {
            var acct = new Ordering.PurchaseOrderAccount {
                AccountID = accountId, ClientID = clientId
            };

            var existing = DataSession.Single <Ordering.PurchaseOrderAccount>(acct);

            if (existing == null)
            {
                //insert new
                acct.Active = true;
                DataSession.Insert(acct);
                return(CreateAccount(acct));
            }
            else
            {
                //update existing
                existing.Active = true;
                return(CreateAccount(existing));
            }
        }
コード例 #19
0
        public void ProcedureExecuteTransaction()
        {
            var session = new DataSession("AspNet").Log(Console.WriteLine);

            session.Should().NotBeNull();

            var transaction = session.BeginTransaction(IsolationLevel.Unspecified);

            transaction.Should().NotBeNull();

            Guid userId    = Guid.Empty;
            int  errorCode = -1;

            var username = "******" + DateTime.Now.Ticks;
            var email    = username + "@email.com";

            var result = session.StoredProcedure("[dbo].[aspnet_Membership_CreateUser]")
                         .Parameter("@ApplicationName", "/")
                         .Parameter("@UserName", username)
                         .Parameter("@Password", "T@est" + DateTime.Now.Ticks)
                         .Parameter("@Email", email)
                         .Parameter("@PasswordSalt", "test salt")
                         .Parameter <string>("@PasswordQuestion", null)
                         .Parameter <string>("@PasswordAnswer", null)
                         .Parameter("@IsApproved", true)
                         .Parameter("@CurrentTimeUtc", DateTime.UtcNow)
                         .Parameter("@UniqueEmail", 1)
                         .Parameter("@PasswordFormat", 1)
                         .ParameterOut <Guid>("@UserId", p => userId = p)
                         .Return <int>(p => errorCode = p)
                         .Execute();

            result.Should().BeGreaterOrEqualTo(1);
            userId.Should().NotBe(Guid.Empty);
            errorCode.Should().Be(0);

            transaction.Commit();
        }
コード例 #20
0
ファイル: HomeModel.cs プロジェクト: lurienanofab/data
        public ClientOrg[] ClientOrgSearch()
        {
            IList <ClientOrg> query = new List <ClientOrg>();

            if (string.IsNullOrEmpty(Search))
            {
                query = DataSession.Query <ClientOrg>().ToList();
            }
            else
            {
                if (GetSingle <ClientOrg>("co", query))
                {
                    return(query.ToArray());
                }
                else if (GetMultiple <ClientOrg>("client", query, id => x => x.Client.ClientID == id))
                {
                    return(query.ToArray());
                }
                else if (GetMultiple <ClientOrg>("org", query, id => x => x.Org.OrgID == id))
                {
                    return(query.ToArray());
                }
                else
                {
                    query = DataSession.Query <ClientOrg>().Where(x =>
                                                                  x.ClientOrgID.ToString() == Search ||
                                                                  x.Client.UserName.ToLower().Contains(Search.ToLower()) ||
                                                                  x.Client.LName.ToLower().Contains(Search.ToLower()) ||
                                                                  x.Client.FName.ToLower().Contains(Search.ToLower()) ||
                                                                  (x.Client.LName + ", " + x.Client.FName).ToLower().Contains(Search.ToLower()) ||
                                                                  (x.Client.FName + " " + x.Client.LName).ToLower().Contains(Search.ToLower()) ||
                                                                  x.Email.ToLower().Contains(Search.ToLower()) ||
                                                                  x.Org.OrgName.ToLower().Contains(Search.ToLower())).ToList();
                }
            }

            return(query.ToArray());
        }
コード例 #21
0
        public SelectListItem[] GetDemographicSelectListItems(DemographicType type)
        {
            switch (type)
            {
            case DemographicType.Citizen:
                return(DataSession.Query <DemCitizen>().Select(x => new SelectListItem()
                {
                    Text = x.DemCitizenValue, Value = x.DemCitizenID.ToString()
                }).ToArray());

            case DemographicType.Gender:
                return(DataSession.Query <DemGender>().Select(x => new SelectListItem()
                {
                    Text = x.DemGenderValue, Value = x.DemGenderID.ToString()
                }).ToArray());

            case DemographicType.Race:
                return(DataSession.Query <DemRace>().Select(x => new SelectListItem()
                {
                    Text = x.DemRaceValue, Value = x.DemRaceID.ToString()
                }).ToArray());

            case DemographicType.Ethnic:
                return(DataSession.Query <DemEthnic>().Select(x => new SelectListItem()
                {
                    Text = x.DemEthnicValue, Value = x.DemEthnicID.ToString()
                }).ToArray());

            case DemographicType.Disability:
                return(DataSession.Query <DemDisability>().Select(x => new SelectListItem()
                {
                    Text = x.DemDisabilityValue, Value = x.DemDisabilityID.ToString()
                }).ToArray());

            default:
                throw new ArgumentException("type");
            }
        }
コード例 #22
0
ファイル: PaymentMethods.cs プロジェクト: Meracord/DotNetSDK
        /// <summary>
        /// Execute sample method calls
        /// </summary>
        public static void Perform(string accountNumber, Guid paymentProfileToken)
        {
            try
            {
                var groupNumber = Settings.GroupNumber;
                var bankProfile = BankProfileMethods.GetBankProfile(Helper.RandomNumericString(17));

                _session = SessionFactory.Create();

                var paymentToken = SchedulePaymentWithToken(accountNumber, paymentProfileToken);

                SchedulePaymentWithNewBankProfile(accountNumber, bankProfile);

                FindByToken(accountNumber, paymentToken);

                CancelAllPayment(accountNumber);

            }
            catch (Exception ex)
            {
                Helper.DisplayException(ex);
            }
        }
コード例 #23
0
        private Task EndSession(DataSession <DataSessionState> session)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }

            return(Task.Run(
                       () =>
            {
                var state = session.State;

                WriteOperationTrace(state, "endSession");

                if (!state.ConnectionClosedByReader)
                {
                    WriteOperationTrace(state, "closeConnection");

                    state.Connection.Close();
                    state.Connection.Dispose();
                }
            }));
        }
コード例 #24
0
        public Vendor Copy(int toClientId, int fromVendorId)
        {
            var vend = Require <Ordering.Vendor>(x => x.VendorID, fromVendorId);

            var copy = new Ordering.Vendor()
            {
                ClientID   = toClientId,
                VendorName = vend.VendorName,
                Address1   = vend.Address1,
                Address2   = vend.Address2,
                Address3   = vend.Address3,
                Contact    = vend.Contact,
                Phone      = vend.Phone,
                Fax        = vend.Fax,
                URL        = vend.URL,
                Email      = vend.Email,
                Active     = vend.Active
            };

            DataSession.Insert(copy);

            return(CreateVendor(copy));
        }
コード例 #25
0
        public ActionResult Index(int orgId = 0)
        {
            var model = new AccountModel();

            var allOrgs    = DataSession.Query <Org>().OrderBy(x => x.OrgName).ToList();
            var activeOrgs = allOrgs.Where(x => x.Active).OrderBy(x => x.OrgName).ToList();
            var currentOrg = allOrgs.FirstOrDefault(x => x.OrgID == orgId);

            if (currentOrg == null)
            {
                currentOrg = allOrgs.First(x => x.PrimaryOrg); // throw an error if there isn't one
            }
            model.ActiveOrgs = activeOrgs.CreateModels <IOrg>();
            model.CurrentOrg = currentOrg.CreateModel <IOrg>();

            var activeAccounts = DataSession.Query <Account>().Where(x => x.Active && x.Org.OrgID == currentOrg.OrgID).OrderBy(x => x.Name).ToList();

            model.ActiveAccounts = activeAccounts.CreateModels <IAccount>();

            model.IsChartFieldOrg = AccountChartFields.IsChartFieldOrg(currentOrg.CreateModel <IOrg>());

            return(View(model));
        }
コード例 #26
0
        public OrgDepartmentModel Post([FromBody] OrgDepartmentModel model, int orgId)
        {
            Department entity;

            if (model.DepartmentID > 0)
            {
                //update existing
                entity = DataSession.Single <Department>(model.DepartmentID);
                entity.DepartmentName = model.DepartmentName;
            }
            else
            {
                //add new
                entity = new Department()
                {
                    DepartmentName = model.DepartmentName,
                    Org            = DataSession.Single <Org>(orgId)
                };
            }

            DataSession.SaveOrUpdate(entity);
            return(GetModel(entity));
        }
コード例 #27
0
ファイル: Connect.aspx.cs プロジェクト: laszlo-kiss/Dataphor
        private void AdvanceToApplication()
        {
            DataSession session = new DataSession();

            session.Alias  = _configuration.Aliases[_configuration.DefaultAliasName];
            session.Active = true;
            session.SessionInfo.Environment = "WindowsClient";

            Web.Session webSession = new Web.Session(session, true);
            Session["WebSession"] = webSession;

            string applicationID = (string)Session["ApplicationID"];

            if ((applicationID != null) && (applicationID != String.Empty))
            {
                webSession.SetApplication(applicationID);
                Response.Redirect((string)Session["DefaultPage"]);
            }
            else
            {
                Response.Redirect((string)Session["ApplicationsPage"]);
            }
        }
コード例 #28
0
        public bool Delete([FromUri] string option, [FromBody] AccountModel model, int id = 0)
        {
            bool result = false;

            switch (option)
            {
            case "current":
                ClientAccount ca = DataSession.Query <ClientAccount>().FirstOrDefault(x => x.ClientOrg.ClientOrgID == id && x.Account.AccountID == model.AccountID);
                if (ca != null)
                {
                    Provider.Data.ActiveLog.Disable(ca);

                    //may not have physical access any more if there are no more active accounts
                    IClient c = DataSession.Single <ClientInfo>(ca.ClientOrg.Client.ClientID);
                    Provider.Data.Client.UpdatePhysicalAccess(c, out string alert);

                    return(true);
                }
                break;
            }

            return(result);
        }
コード例 #29
0
        public ActionResult Edit(Post post)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var listOfTags = SeparateTags(post.Tags);

                    post.InternalTags = listOfTags;

                    DataSession.Store(post, "posts/" + post.Id);
                    DataSession.SaveChanges();
                    TempData["success"] = string.Format("Uppdaterade posten {0}", post.Title);
                    UpdateModel("Index");
                    return(RedirectToAction("Index"));
                }
                catch (Exception)
                {
                    TempData["error"] = string.Format("Misslyckades att uppdatera {0}", post.Title);
                }
            }
            return(View(post));
        }
コード例 #30
0
        /// <summary>
        /// Check user password
        /// </summary>
        /// <param name="user">User</param>
        /// <param name="newPassword">New password</param>
        /// <returns>Returns signed in user or null</returns>
        public IList <ValidationResult> UpdateUserPassword(Shooter user, string newPassword)
        {
            //Validazione argomenti
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (string.IsNullOrEmpty(newPassword))
            {
                throw new ArgumentNullException(nameof(newPassword));
            }

            //aggiorno la password
            user.Password = _identityClient.EncryptPassword(newPassword);

            IList <ValidationResult> validations = new List <ValidationResult>();

            //Esecuzione in transazione
            using (var t = DataSession.BeginTransaction())
            {
                //Validazione argomenti
                validations = _userRepository.Validate(user);

                //Se ho validazioni fallite, esco
                if (validations.Count > 0)
                {
                    //Rollback ed uscita
                    t.Rollback();
                    return(validations);
                }

                //Salvataggio
                _userRepository.Save(user);
                t.Commit();
            }
            return(validations);
        }
コード例 #31
0
        public AccountModel Post([FromUri] string option, [FromBody] AccountModel model, int id)
        {
            AccountModel result = null;

            switch (option)
            {
            case "current":
                var ca = DataSession.Query <ClientAccount>().FirstOrDefault(x => x.ClientOrg.ClientOrgID == id && x.Account.AccountID == model.AccountID);

                if (ca == null)
                {
                    //no existing ClientAccount record so create a new one
                    ca = new ClientAccount()
                    {
                        ClientOrg = DataSession.Single <ClientOrg>(id),
                        Account   = DataSession.Single <Account>(model.AccountID),
                        IsDefault = false,
                        Manager   = false
                    };

                    DataSession.Insert(ca);
                }

                Provider.Data.ActiveLog.Enable(ca);

                //may need to restore physical access because there is now an active acct and other requirements are met
                string  alert;
                IClient c = DataSession.Single <ClientInfo>(ca.ClientOrg.Client.ClientID);
                Provider.Data.Client.UpdatePhysicalAccess(c, out alert);

                result = ApiUtility.CreateAccountModel(ca.Account);

                break;
            }

            return(result);
        }
コード例 #32
0
        private void SetPrimary(Ordering.Approver appr, bool isPrimary)
        {
            if (appr.IsPrimary != isPrimary)
            {
                if (isPrimary)
                {
                    // get the current primary approver, if any
                    var currentPrimary = DataSession.Query <Ordering.Approver>().Where(x => x.ClientID == appr.ClientID && x.ApproverID != appr.ApproverID && x.IsPrimary);

                    // set any found to false
                    foreach (var cp in currentPrimary)
                    {
                        cp.IsPrimary = false;
                    }

                    // set this approver to primary
                    appr.IsPrimary = true;
                }
                else
                {
                    appr.IsPrimary = false;
                }
            }
        }
コード例 #33
0
        public void SqlQuerySingleEntity()
        {
            string email = "*****@*****.**";
            string sql   = "select * from [User] where EmailAddress = @EmailAddress";

            User user;

            using (var session = new DataSession("Tracker").Log(Console.WriteLine))
            {
                session.Should().NotBeNull();

                user = session.Sql(sql)
                       .Parameter("@EmailAddress", email)
                       .QuerySingle(r => new User
                {
                    Id                     = r.GetInt32("Id"),
                    EmailAddress           = r.GetString("EmailAddress"),
                    FirstName              = r.GetString("FirstName"),
                    LastName               = r.GetString("LastName"),
                    Avatar                 = (Byte[])r.GetValue("Avatar"),
                    CreatedDate            = r.GetDateTime("CreatedDate"),
                    ModifiedDate           = r.GetDateTime("ModifiedDate"),
                    PasswordHash           = r.GetString("PasswordHash"),
                    PasswordSalt           = r.GetString("PasswordSalt"),
                    Comment                = r.GetString("Comment"),
                    IsApproved             = r.GetBoolean("IsApproved"),
                    LastLoginDate          = r.GetDateTime("LastLoginDate"),
                    LastActivityDate       = r.GetDateTime("LastActivityDate"),
                    LastPasswordChangeDate = r.GetDateTime("LastPasswordChangeDate"),
                    AvatarType             = r.GetString("AvatarType"),
                });
            }

            user.Should().NotBeNull();
            user.EmailAddress.Should().Be(email);
        }
コード例 #34
0
ファイル: AjaxController.cs プロジェクト: lurienanofab/data
        public ActionResult AccountManagerAdd()
        {
            try
            {
                var acctEdit = GetAccountEdit();

                int clientOrgId = Convert.ToInt32(Request.Form["client-org-id"]);

                var managers = acctEdit.Managers.ToList();

                var mgr = DataSession.Single <ClientOrgInfo>(clientOrgId);

                if (mgr != null)
                {
                    managers.Add(new AccountManagerEdit()
                    {
                        ClientOrgID = mgr.ClientOrgID,
                        LName       = mgr.LName,
                        FName       = mgr.FName
                    });

                    acctEdit.Managers = managers.OrderBy(x => x.LName).ThenBy(x => x.FName).ToList();
                    var available = AccountEditUtility.GetAvailableManagers(acctEdit);
                    return(Json(new { add = true, managers = acctEdit.Managers, available }));
                }
                else
                {
                    return(Json(new { add = false }));
                }
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                return(Json(new { error = ex.Message }));
            }
        }
コード例 #35
0
 private void SetShowDisclaimerSetting(bool value)
 {
     ShowDisclaimerSetting.SettingValue = value ? "true" : "false";
     DataSession.SaveOrUpdate(ShowDisclaimerSetting);
 }
コード例 #36
0
 public SponsorshipRepository(DataSession dataSession) : base(dataSession)
 {
     _dataSession = dataSession;
 }
コード例 #37
0
        public IDbTransaction GetTransaction(string dataSourceName, IDbConnection con)
        {
            IDbTransaction tran = null;

            //first get the current ***controlling*** context
            TransactionContext trCtx = TransactionContextFactory.GetCurrentContext();
            TransactionContext contrTrCtx = null;
            if(trCtx != null)
                contrTrCtx = trCtx.GetControllingContext();
            //if it's not null
            if(contrTrCtx != null)
            {
                DataSession ds = null;
                //get the Hashtable with DataSessions per DataSource
                Hashtable transactionsByDataSource = dataSourceTransactionsByTrCtx[contrTrCtx] as Hashtable;
                //if not existing create :(
                if(transactionsByDataSource == null)
                {
                    //add it to it
                    transactionsByDataSource = new Hashtable();
                    dataSourceTransactionsByTrCtx.Add(contrTrCtx, transactionsByDataSource);
                    //and subscribe for it's events
                    contrTrCtx.StateChanged += new TCStateChangedEventHandler(HandleTCStateChangedEvent);
                }
                else
                {
                    ds = transactionsByDataSource[dataSourceName] as DataSession;
                }

                //if not existing create new and add it
                if(ds == null)
                {
                    //IDbConnection con = ds.CreateConnection();
                    con.Open();
                    IsolationLevel isolationLevel =
                        (IsolationLevel)Enum.Parse(typeof(IsolationLevel), contrTrCtx.IsolationLevel.ToString());
                    tran = con.BeginTransaction(isolationLevel);
                    ds = new DataSession(con, tran);
                    transactionsByDataSource.Add(dataSourceName, ds);
                }
                else
                {
                    tran = ds.Transaction;
                }
            }

            return tran;
        }
コード例 #38
0
        public void SqlQueryTable()
        {
            var session = new DataSession("Tracker").Log(Console.WriteLine);
            session.Should().NotBeNull();

            string email = "*****@*****.**";
            string sql = "select * from [User] where EmailAddress like @EmailAddress";

            var users = session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .QueryTable();

            users.Should().NotBeNull();
        }
コード例 #39
0
 /// <summary>
 /// Конструктор класса
 /// </summary>
 /// <param name="session"></param>
 public BusinessObjectClasses(DataSession session)
 {
     this.session = session;
 }
コード例 #40
0
 public CampaignRepository(DataSession dataSession) : base(dataSession)
 {
     _dataSession = dataSession;
 }
コード例 #41
0
 public AccountRepository(DataSession dataSession) : base(dataSession)
 {
 }
コード例 #42
0
        public void ProcedureExecuteOutDuplicate()
        {

            Guid? userId = null;
            int errorCode = -1;

            var username = "******" + DateTime.Now.Ticks;
            var email = username + "@email.com";
            int result;

            using (var session = new DataSession("AspNet").Log(Console.WriteLine))
            {
                session.Should().NotBeNull();

                result = session.StoredProcedure("[dbo].[aspnet_Membership_CreateUser]")
                    .Parameter("@ApplicationName", "/")
                    .Parameter("@UserName", "paul.welter")
                    .Parameter("@Password", "T@est" + DateTime.Now.Ticks)
                    .Parameter("@Email", email)
                    .Parameter("@PasswordSalt", "test salt")
                    .Parameter<string>("@PasswordQuestion", null)
                    .Parameter<string>("@PasswordAnswer", null)
                    .Parameter("@IsApproved", true)
                    .Parameter("@CurrentTimeUtc", DateTime.UtcNow)
                    .Parameter("@UniqueEmail", 1)
                    .Parameter("@PasswordFormat", 1)
                    .Parameter<Guid?>(parameter => parameter
                        .Name("@UserId")
                        .Type(DbType.Guid)
                        .Output(p => userId = p)
                        .Direction(ParameterDirection.Output)
                    )
                    .Return<int>(p => errorCode = p)
                    .Execute();

                // Duplicate
                result = session.StoredProcedure("[dbo].[aspnet_Membership_CreateUser]")
                    .Parameter("@ApplicationName", "/")
                    .Parameter("@UserName", "paul.welter")
                    .Parameter("@Password", "T@est" + DateTime.Now.Ticks)
                    .Parameter("@Email", email)
                    .Parameter("@PasswordSalt", "test salt")
                    .Parameter<string>("@PasswordQuestion", null)
                    .Parameter<string>("@PasswordAnswer", null)
                    .Parameter("@IsApproved", true)
                    .Parameter("@CurrentTimeUtc", DateTime.UtcNow)
                    .Parameter("@UniqueEmail", 1)
                    .Parameter("@PasswordFormat", 1)
                    .Parameter<Guid?>(parameter => parameter
                        .Name("@UserId")
                        .Type(DbType.Guid)
                        .Output(p => userId = p)
                        .Direction(ParameterDirection.Output)
                    )
                    .Return<int>(p => errorCode = p)
                    .Execute();
            }

            result.Should().Be(-1);
            errorCode.Should().BeGreaterThan(0);

        }
コード例 #43
0
        public void ProcedureQueryDynamicOut()
        {
            int totalRecords = -1;
            int result = 0;

            Guid userId = Guid.Empty;
            int errorCode = -1;

            var username = "******" + DateTime.Now.Ticks;
            var email = username + "@email.com";

            List<dynamic> results;
            using (var session = new DataSession("AspNet").Log(Console.WriteLine))
            {
                session.Should().NotBeNull();

                result = session.StoredProcedure("[dbo].[aspnet_Membership_CreateUser]")
                    .Parameter("@ApplicationName", "/")
                    .Parameter("@UserName", username)
                    .Parameter("@Password", "T@est" + DateTime.Now.Ticks)
                    .Parameter("@Email", email)
                    .Parameter("@PasswordSalt", "test salt")
                    .Parameter<string>("@PasswordQuestion", null)
                    .Parameter<string>("@PasswordAnswer", null)
                    .Parameter("@IsApproved", true)
                    .Parameter("@CurrentTimeUtc", DateTime.UtcNow)
                    .Parameter("@UniqueEmail", 1)
                    .Parameter("@PasswordFormat", 1)
                    .ParameterOut<Guid>("@UserId", p => userId = p)
                    .Return<int>(p => errorCode = p)
                    .Execute();

                results = session.StoredProcedure("[dbo].[aspnet_Membership_FindUsersByEmail]")
                    .Parameter("@ApplicationName", "/")
                    .Parameter("@EmailToMatch", "*****@*****.**")
                    .Parameter("@PageIndex", 0)
                    .Parameter("@PageSize", 10)
                    .Return<int>(p => totalRecords = p)
                    .Query()
                    .ToList();
            }

            results.Should().NotBeNull();
            results.Count.Should().BeGreaterThan(0);
            totalRecords.Should().BeGreaterThan(0);
        }
コード例 #44
0
        public void SqlReader()
        {
            var session = new DataSession("Tracker").Log(Console.WriteLine);
            session.Should().NotBeNull();

            string email = "*****@*****.**";
            string sql = "select * from [User] where EmailAddress like @EmailAddress";

            var users = new List<dynamic>();

            session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .Read(reader =>
                {
                    while (reader.Read())
                    {
                        var user = DataFactory.DynamicFactory(reader);
                        users.Add(user);
                    }
                });

            users.Should().NotBeNull();
            users.Should().NotBeEmpty();
        }
コード例 #45
0
        public void SqlQueryMultiple()
        {

            string email = "*****@*****.**";
            string sql = "select * from [User] where EmailAddress = @EmailAddress; " +
                         "select * from [Role]; " +
                         "select * from [Priority]; ";

            User user = null;
            List<Role> roles = null;
            List<Priority> priorities = null;

            using (var session = new DataSession("Tracker").Log(Console.WriteLine))
            {
                session.Should().NotBeNull();
                session.Sql(sql)
                    .Parameter("@EmailAddress", email)
                    .QueryMultiple(q =>
                    {
                        user = q.QuerySingle<User>();
                        roles = q.Query<Role>().ToList();
                        priorities = q.Query<Priority>().ToList();
                    });
            }

            user.Should().NotBeNull();
            user.EmailAddress.Should().NotBeEmpty();

            roles.Should().NotBeNull();
            roles.Should().NotBeEmpty();

            priorities.Should().NotBeNull();
            priorities.Should().NotBeEmpty();

        }
コード例 #46
0
        public void ProcedureExecuteTransaction()
        {
            var session = new DataSession("AspNet").Log(Console.WriteLine);
            session.Should().NotBeNull();

            var transaction = session.BeginTransaction(IsolationLevel.Unspecified);
            transaction.Should().NotBeNull();

            Guid userId = Guid.Empty;
            int errorCode = -1;

            var username = "******" + DateTime.Now.Ticks;
            var email = username + "@email.com";

            var result = session.StoredProcedure("[dbo].[aspnet_Membership_CreateUser]")
                .Parameter("@ApplicationName", "/")
                .Parameter("@UserName", username)
                .Parameter("@Password", "T@est" + DateTime.Now.Ticks)
                .Parameter("@Email", email)
                .Parameter("@PasswordSalt", "test salt")
                .Parameter<string>("@PasswordQuestion", null)
                .Parameter<string>("@PasswordAnswer", null)
                .Parameter("@IsApproved", true)
                .Parameter("@CurrentTimeUtc", DateTime.UtcNow)
                .Parameter("@UniqueEmail", 1)
                .Parameter("@PasswordFormat", 1)
                .ParameterOut<Guid>("@UserId", p => userId = p)
                .Return<int>(p => errorCode = p)
                .Execute();

            result.Should().BeGreaterOrEqualTo(1);
            userId.Should().NotBe(Guid.Empty);
            errorCode.Should().Be(0);

            transaction.Commit();
        }
コード例 #47
0
        private IEnumerable<DataMergeOutputRow> Merge(DataMergeDefinition mergeDefinition, DataTable dataTable, string connectionName)
        {
            Logger.Debug()
                .Message("Executing batch merge to: '{0}'", mergeDefinition.TargetTable)
                .Write();

            List<DataMergeOutputRow> result;
            using (var session = new DataSession(connectionName))
            {
                result = session
                    .MergeData(mergeDefinition)
                    .MergeOutput(dataTable)
                    .ToList();
            }
            return result;
        }
コード例 #48
0
        public void SqlQueryValue()
        {
            var session = new DataSession("Tracker").Log(Console.WriteLine);
            session.Should().NotBeNull();

            string email = "*****@*****.**";
            string sql = "select Count(*) from [User] where EmailAddress like @EmailAddress";

            var count = session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .QueryValue<int>();

            count.Should().BeGreaterThan(0);
        }
コード例 #49
0
 public void Inicializar()
 {
     DataSession = new DataSession(SQLiteConfiguration.Standard.InMemory());
     Session = DataSession.SessionFactory.OpenSession();
     BuildSchema(Session, DataSession.Configuration);
 }
コード例 #50
0
ファイル: PayeeMethods.cs プロジェクト: Meracord/DotNetSDK
        private static DocumentResult CreateDocument(DataSession session, string accountNumber, Document document)
        {
            Console.WriteLine("Going to sleep for 5 seconds...");
            Console.WriteLine("The Payee.Create method performs an asynchronous operation with an ancillary system,\r\nso give the process a moment to complete before attempting to\r\nassociate an PayeeAccountAuthorizationAgreement");
            Console.WriteLine();
            System.Threading.Thread.Sleep(5000); // wait 5 seconds

            var tries = 4;
            while (tries > 0)
            {
                var response = session.Payee.AddDocument(accountNumber, document);
                if (response.Success)
                {
                    return response;
                }
                var exception = response.Exceptions.FirstOrDefault();

                if (exception.ExceptionType != DataServiceExceptionType.AccountCustomerIdNotFound)
                {
                    throw new ApplicationException(exception.Message);
                }

                Console.WriteLine("Associated Payee Account has not been created yet.  Retry in 10 seconds...");
                System.Threading.Thread.Sleep(10000); // wait 10 seconds
                tries--;
            }

            throw new ApplicationException("Timeout reached waiting for Payee Account to be created.");
        }
コード例 #51
0
        public void SqlQueryEntityDynamicCache()
        {
            var session = new DataSession("Tracker").Log(Console.WriteLine);

            session.Should().NotBeNull();

            string email = "*****@*****.**";
            string sql = "select * from [User] where EmailAddress like @EmailAddress";

            var policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(5) };

            var users = session
                .Sql(sql)
                .Parameter("@EmailAddress", email)
                .UseCache(policy)
                .Query()
                .ToList();

            users.Should().NotBeNull();
            users.Should().NotBeEmpty();

            var cachedUsers = session
                .Sql(sql)
                .Parameter("@EmailAddress", email)
                .UseCache(policy)
                .Query()
                .ToList();

            cachedUsers.Should().NotBeNull();
            cachedUsers.Should().NotBeEmpty();
        }
コード例 #52
0
        public CreateControlsProperty(
                                        DataSession session,
                                        String NameClass,
                                        String NameProp,
                                        String PropertyCaption,
                                        Int32 Id,
                                        Int32 IdClass,
                                        List<object> items,
                                        Boolean[] checkSettingHtml
                                     )
        {
            this.session = session;
            this.Id = Id;
            this.NameClass = NameClass;
            if (NameProp.IndexOf("-") == -1)
                this.NameProperty = NameProp;
            else
                this.NameProperty = NameProp.Substring(0, NameProp.IndexOf("-"));

            this.HTMLPropertyCaption = PropertyCaption;
            this.NamePropertyItems = items;
            this.IdClass = IdClass;
            this.NameTable = session[NameClass].Class.DataTable;
            checkSettingHtml.CopyTo(this.checkSettingHtml, 0);
            if (!this.checkSettingHtml[9])
                this.type = session[NameClass].Class.AllProperties.Need(this.NameProperty).DataTypeName;
            else
            {
                this.type = "string";
                if (NameProp.IndexOf("-") == -1)
                    AssocClass = session[NameClass].Class.AllProperties.Need(NameProperty).Association.Refs[0].RefClass.Name;
                else
                {
                    AssocClass = session[NameClass].Class.AllProperties.Need(NameProperty).Association.Refs.Need(session[NameProp.Substring(NameProp.IndexOf("-") + 1)].Class).RefClass.Name;
                }
            }
        }
コード例 #53
0
ファイル: StudentTest.cs プロジェクト: brandon7596/team51
        public void DataInsert()
        {
            var dataSession = new DataSession();
            var uowFactory  = new UnitOfWorkFactory(dataSession);
            var uow         = uowFactory.CreateUnitOfWork();

            var testUser = new BursifyUser()
            {
                //ID = 51,
                Email              = "*****@*****.**",
                PasswordHash       = "password123",
                PasswordSalt       = "passwordSalt",
                AccountStatus      = "Active",
                UserType           = "Student",
                RegistrationDate   = DateTime.Today,
                Biography          = "Bio stuff",
                CellphoneNumber    = "0840924299",
                TelephoneNumber    = "0123456789",
                ProfilePicturePath = "somewhereSafe"
            };

            var school = new Institution()
            {
                //ID = 25,
                Name    = "University of Johannesburg",
                Type    = "Tertiary",
                Website = "www.uj.ac.za",
            };



            var Students = //new List<Student>()
                           //{
                           new Student()
            {
                ID            = testUser.ID,
                InstitutionID = school.ID,
                AgreeTandC    = true,
                AverageMark   = 75,
                Age           = 20,
                Firstname     = "Brandon",
                Gender        = "Male",
            };

            //};

            school.Students.Add(Students); //= Students;

            var StudentReports =           //new List<StudentReport>()
                                           //{
                                 new StudentReport()
            {
                StudentId         = Students.ID,
                Average           = 75,
                ReportInstitution = "UJ",
                ReportLevel       = "Tertiary",
                ReportPeriod      = "Semester 1",

                //}
            };

            var Subjects = new List <Subject>()
            {
                new Subject()
                {
                    //ID = 12,
                    RequirementId = StudentReports.ID,
                    Name          = "CSC 1A10",
                    MarkAcquired  = 12
                },

                new Subject()
                {
                    //ID = 12,
                    RequirementId = StudentReports.ID,
                    Name          = "CSC 2A10",
                    MarkAcquired  = 21
                }
            };

            StudentReports.Subjects = Subjects;
            Students.StudentReports.Add(StudentReports);
            school.Students.Add(Students);
            //testUser.Student = Students;

            uow.Context.Set <BursifyUser>().Add(testUser);
            uow.Context.Set <Institution>().Add(school);
//            uow.Context.Set<Student>().Add(Students);
//            uow.Context.Set<StudentReport>().Add(StudentReports);
//            uow.Context.Set<Subject>().Add(Subjects[1]);

            uow.Context.SaveChanges();
            uow.Commit();
        }
コード例 #54
0
 // GET: Blogs
 public ActionResult Index()
 {
     return(View(DataSession.Query <Blog>().ToList()));
 }
コード例 #55
0
 internal EntitySet(DataSession session)
     : base(session, DataRecord <T> .Table)
 {
 }
コード例 #56
0
ファイル: OrgModel.cs プロジェクト: lurienanofab/data
        public override bool Save()
        {
            int errors = 0;

            Message = string.Empty;

            if (string.IsNullOrEmpty(OrgName))
            {
                Message += GetAlert("Name is required.");
                errors++;
            }

            Org existingOrg = DataSession.Query <Org>().Where(x => x.OrgName == OrgName).FirstOrDefault();

            //three possibilities: 1) no org with this name exists, 2) existing is the same as this org, 3) existing is different
            if (existingOrg != null && existingOrg.OrgID != OrgID)
            {
                //there is an existing (and different) org with the same name
                Message += GetAlert("This name is already used by an {0} org.", existingOrg.Active ? "active" : "inactive");
                errors++;
            }

            OrgType orgType = null;

            if (OrgTypeID == 0)
            {
                Message += GetAlert("Type is required.");
                errors++;
            }
            else
            {
                orgType = DataSession.Single <OrgType>(OrgTypeID);
                if (orgType == null)
                {
                    Message += GetAlert("No record found for OrgTypeID {0}", OrgTypeID);
                    errors++;
                }
            }

            Org primary = null;

            if (CanEditPrimaryOrg())
            {
                primary = GetPrimaryOrg();
                if (PrimaryOrg)
                {
                    if (!Active)
                    {
                        Message += GetAlert("The primary org must be active.");
                        errors++;
                    }
                }
                else
                {
                    //make sure there is a primary org
                    if (primary == null)
                    {
                        Message += GetAlert("There must be at least one primary org.");
                        errors++;
                    }
                }
            }

            if (errors > 0)
            {
                return(false);
            }

            Org  org;
            bool originalActive = false;

            if (OrgID == 0)
            {
                //new record
                org = new Org()
                {
                    DefBillAddressID   = 0,
                    DefClientAddressID = 0,
                    DefShipAddressID   = 0,
                    NNINOrg            = NNINOrg,
                    OrgName            = OrgName,
                    OrgType            = orgType,
                    PrimaryOrg         = CanEditPrimaryOrg() && PrimaryOrg
                };

                DataSession.Insert(org); // gets a new OrgID
            }
            else
            {
                org = DataSession.Single <Org>(OrgID);

                if (org == null)
                {
                    Message += GetAlert("No record found for OrgID {0}", OrgID);
                    return(false);
                }

                originalActive = org.Active;

                org.NNINOrg    = NNINOrg;
                org.OrgName    = OrgName;
                org.OrgType    = orgType;
                org.PrimaryOrg = CanEditPrimaryOrg() ? PrimaryOrg : org.PrimaryOrg;
            }

            if (originalActive != Active)
            {
                if (Active)
                {
                    Provider.Data.ActiveLog.Enable(org);
                }
                else
                {
                    Provider.Data.ActiveLog.Disable(org);

                    //need to disable any clients where this was the only active org
                    var clientOrgs = Provider.Data.Client.GetClientOrgs(org.OrgID).Where(x => x.ClientActive);

                    foreach (var co in clientOrgs)
                    {
                        //does this ClientOrg have any other active associations?
                        bool hasAnotherActiveClientOrg = DataSession.Query <ClientOrg>().Any(x => x.Active && x.Client.ClientID == co.ClientID && x.Org.OrgID != co.OrgID);
                        if (!hasAnotherActiveClientOrg)
                        {
                            //no other active ClientOrgs so disable the Client record also
                            var c = DataSession.Single <Client>(co.ClientID);
                            Provider.Data.ActiveLog.Disable(c);
                        }
                    }
                }
            }

            if (CanEditPrimaryOrg() && PrimaryOrg && primary != null)
            {
                primary.PrimaryOrg = false;
                DataSession.SaveOrUpdate(primary);
            }

            OrgID = org.OrgID;

            return(true);
        }
コード例 #57
0
        public void SqlQuerySingleEntityDynamic()
        {
            var session = new DataSession("Tracker").Log(Console.WriteLine);
            session.Should().NotBeNull();

            string email = "*****@*****.**";
            string sql = "select * from [User] where EmailAddress = @EmailAddress";

            dynamic user = session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .QuerySingle();

            Assert.NotNull(user);
            Assert.Equal<string>(user.EmailAddress, email);
        }