Exemplo n.º 1
0
 private static void LogLastQuery(IEntitySession session)
 {
     //Debug.WriteLine("---------------------------------------------------------------------------------------");
     var command = session.GetLastCommand();
     //if(command != null)
     // Debug.WriteLine("SQL:" + command.CommandText);
 }
Exemplo n.º 2
0
        /// <summary>从数据库中删除指定条件的实体对象。</summary>
        /// <param name="session">实体会话</param>
        /// <param name="whereClause">限制条件</param>
        /// <returns></returns>
        public virtual Int32 Delete(IEntitySession session, String whereClause)
        {
            var sql = $"Delete From {session.FormatedTableName}";

            if (!whereClause.IsNullOrEmpty())
            {
                sql += " Where " + whereClause;
            }
            //return session.Execute(sql);

            // MySql 支持分批删除
            if (session.Dal.DbType == DatabaseType.MySql)
            {
                var rs = 0;
                while (true)
                {
                    var rows = session.Dal.Execute(sql + " limit 100000", 5 * 60);
                    rs += rows;

                    if (rows < 100000)
                    {
                        break;
                    }
                }

                return(rs);
            }

            // 加大超时时间
            return(session.Dal.Execute(sql, 5 * 60));
        }
Exemplo n.º 3
0
        private static OAuthClientSettings GetOAuthSettings(this IEntitySession session)
        {
            var stt = session.Context.App.GetConfig <OAuthClientSettings>();

            Util.Check(stt != null, "OAuthClientSettings object is not registered in the entity app. Most likely OAuthClientModule is not part of the app.");
            return(stt);
        }
Exemplo n.º 4
0
        public static IPublisher NewPublisher(this IEntitySession session, string name)
        {
            var pub = session.NewEntity <IPublisher>();

            pub.Name = name;
            return(pub);
        }
Exemplo n.º 5
0
 public static IEncryptedData NewEncryptedData(IEntitySession session, byte[] data, string channelName = null)
 {
     var encrService = GetService(session);
       var ent = session.NewEntity<IEncryptedData>();
       ent.Data = encrService.Encrypt(data, ent.Id.ToString(), channelName);
       return ent;
 }
Exemplo n.º 6
0
        private String Join(IEntitySession session, String[] names, Object[] values, String split)
        {
            var factory = Factory;
            var db      = session.Dal.Db;
            var fs      = new Dictionary <String, FieldItem>(StringComparer.OrdinalIgnoreCase);

            foreach (var fi in factory.Fields)
            {
                fs.Add(fi.Name, fi);
            }

            var sb = Pool.StringBuilder.Get();

            for (var i = 0; i < names.Length; i++)
            {
                if (!fs.ContainsKey(names[i]))
                {
                    throw new ArgumentException("类[" + factory.EntityType.FullName + "]中不存在[" + names[i] + "]属性");
                }

                if (i > 0)
                {
                    sb.AppendFormat(" {0} ", split);
                }

                var column = fs[names[i]].Field;
                sb.Append(db.FormatName(column));
                sb.Append('=');
                sb.Append(db.FormatValue(column, values[i]));
            }

            return(sb.Put(true));
        }
Exemplo n.º 7
0
        public static IUser NewUser(this IEntitySession session, string name)
        {
            var user = session.NewEntity <IUser>();

            user.Name = name;
            return(user);
        }
        private void UpdateFailedJobRun(IEntitySession session, IJobRun jobRun, JobRunContext jobContext, Exception exception)
        {
            var utcNow = session.Context.App.TimeService.UtcNow;

            jobRun.EndedOn = utcNow;
            // current run failed; mark as error
            jobRun.Status = jobContext.Status = JobRunStatus.Error;
            string customNote = null;
            // if exception is soft exc (validation failure) - do not retry
            bool isOpAbort = exception is OperationAbortException;

            if (isOpAbort)
            {
                //This will apear in log
                customNote = "Attempt resulted in OperationAbort exception, no retries are scheduled.";
            }
            var hasRetries = !isOpAbort;

            if (hasRetries)
            {
                // get wait time for next attempt
                var waitMinutes = GetWaitInterval(jobRun.Job.RetryIntervals, jobRun.AttemptNumber + 1);
                hasRetries &= waitMinutes > 0;
                if (hasRetries)
                {
                    // create job run for retry
                    var nextTry = CreateRetryRun(jobRun, waitMinutes);
                }
            }
            ReportJobRunFailure(jobRun, exception, hasRetries, customNote);
        }
Exemplo n.º 9
0
        public static IEvent NewEvent(this IEntitySession session, EventData data)
        {
            var ev = session.NewEntity <IEvent>();

            ev.Id          = data.Id;
            ev.EventType   = data.EventType;
            ev.StartedOn   = data.StartedOn ?? session.Context.App.TimeService.UtcNow;
            ev.Duration    = data.Duration;
            ev.Location    = data.Location;
            ev.UserId      = data.UserId;
            ev.SessionId   = data.SessionId;
            ev.TenantId    = data.TenantId;
            ev.Value       = data.Value;
            ev.StringValue = data.StringValue ?? data.Value + string.Empty;
            if (data.Parameters != null && data.Parameters.Count > 0)
            {
                foreach (var de in data.Parameters)
                {
                    var prm = session.NewEntity <IEventParameter>();
                    prm.Event = ev;
                    prm.Name  = de.Key;
                    prm.Value = de.Value;
                }
            }
            return(ev);
        } //method
Exemplo n.º 10
0
        public ILoginProcess GetActiveProcess(IEntitySession session, LoginProcessType processType, string token)
        {
            Util.Check(!string.IsNullOrWhiteSpace(token), "Process token may not be null");
            var context = session.Context;
            //get process without expiration checking, we check it later
            var query = from p in session.EntitySet <ILoginProcess>()
                        where p.ProcessType == processType && p.Token == token
                        select p;
            var process = query.FirstOrDefault();

            context.ThrowIfNull(process, ClientFaultCodes.ObjectNotFound, "Process", "Login process not found.");
            if (process.Status != LoginProcessStatus.Active)
            {
                return(null);
            }
            if (process.FailCount >= _settings.MaxFailCount)
            {
                process.Status = LoginProcessStatus.AbortedAsFraud;
                OnLoginEvent(context, LoginEventType.ProcessAborted, process.Login, "Aborted - too many failures.");
                session.SaveChanges();
                return(null);
            }
            var userName = process.Login.UserName;

            if (process.ExpiresOn < App.TimeService.UtcNow)
            {
                process.Status = LoginProcessStatus.Expired;
                OnLoginEvent(context, LoginEventType.ProcessAborted, process.Login, "Expired.");
                session.SaveChanges();
                return(null);
            }
            return(process);
        }
Exemplo n.º 11
0
        /// <summary>Executes a SQL delete statement based on LINQ query. </summary>
        /// <typeparam name="TEntity">Entity type for entity(ies) to delete.</typeparam>
        /// <param name="session">Entity session.</param>
        /// <param name="baseQuery">Base LINQ query.</param>
        /// <returns>Number of entities deleted.</returns>
        /// <remarks>
        /// <para>The base query must return an anonymous type with a single property matching the primary key.
        /// </para>
        /// <para>For simple deletes (not using values from other tables/entities) the output key value is ignored and DELETE statement
        /// simply includes the WHERE clause from the base query.
        /// For complex deletes thtat use values from other entities/tables the primary key values identify the records to be deleted.
        /// </para>
        /// </remarks>
        public static int ExecuteDelete <TEntity>(this IEntitySession session, IQueryable baseQuery)
        {
            Util.CheckParam(session, nameof(session));
            var entSession = (EntitySession)session;

            return(entSession.ExecuteLinqNonQuery <TEntity>(baseQuery, LinqOperation.Delete));
        }
Exemplo n.º 12
0
        public static void ScheduleDelete <TEntity>(this IEntitySession session, IQueryable query,
                                                    CommandSchedule schedule = CommandSchedule.TransactionEnd)
        {
            var entSession = (EntitySession)session;

            entSession.ScheduleLinqNonQuery <TEntity>(query, LinqOperation.Delete, schedule);
        }
Exemplo n.º 13
0
        //Utility
        private static IEncryptionService GetService(IEntitySession session)
        {
            var encrService = session.Context.App.GetService <IEncryptionService>();

            Util.Check(encrService != null, "Failed to retrieve IEncryptionService.");
            return(encrService);
        }
Exemplo n.º 14
0
        /// <summary>Checks if an entity is registered with entity model.
        /// For use in customizable models when several versions might exist for different environments,
        /// and some entities are excluded in some models.</summary>
        /// <param name="session">Entity session.</param>
        /// <param name="entityType">The type of entity to check.</param>
        /// <returns>True if the entity is part of the model; otherwise, false.</returns>
        public static bool IsRegisteredEntity(this IEntitySession session, Type entityType)
        {
            var entSession = (EntitySession)session;
            var metaInfo   = entSession.Context.App.Model.GetEntityInfo(entityType);

            return(metaInfo != null);
        }
Exemplo n.º 15
0
        public static T GetSequenceNextValue <T>(this IEntitySession session, string sequenceName) where T : struct
        {
            var seq = session.Context.App.Model.FindSequence(sequenceName);

            Util.Check(seq != null, "Sequence {0} not found.", sequenceName);
            return(GetSequenceNextValue <T>(session, seq));
        }
Exemplo n.º 16
0
        private ILogin GetCurrentLogin(IEntitySession session)
        {
            var login = _loginManager.GetLogin(session);

            Context.ThrowIfNull(login, ClientFaultCodes.ObjectNotFound, "Login", "Login not found for user: {0}.", Context.User.UserName);
            return(login);
        }
Exemplo n.º 17
0
        private void WriteLog(IEntitySession session)
        {
            var log = Environment.NewLine + session.Context.LocalLog.GetAllAsText() + Environment.NewLine;

            lock (_lock)
                File.AppendAllText(_logFileName, log);
        }
Exemplo n.º 18
0
        public void SaveObjects(IEntitySession session, IList <object> items)
        {
            //Group by WebCallId, SessionId, UserName
            var entries          = items.OfType <LogEntry>().ToList();
            var groupedByWebCall = entries.GroupBy(e => e.WebCallId);

            foreach (var wg in groupedByWebCall)
            {
                if (wg.Key == null)
                {
                    var groupedBySessionId = wg.GroupBy(e => e.UserSessionId);
                    foreach (var sg in groupedBySessionId)
                    {
                        if (sg.Key == null)
                        {
                            var groupedByUserName = sg.GroupBy(e => e.UserName);
                            foreach (var ug in groupedByUserName)
                            {
                                SaveEntries(session, ug);
                            }
                        }
                        else
                        {
                            SaveEntries(session, sg);
                        }
                    } // foreach sg
                }     //if wg.Key
                else
                {
                    SaveEntries(session, wg);
                }
            }//foreach wg
        }
Exemplo n.º 19
0
 internal DirtiedEntitySession(IEntitySession session, Int32 executeCount, Int32 updateCount, Int32 directExecuteSQLCount)
 {
     Session               = session;
     ExecuteCount          = executeCount;
     UpdateCount           = updateCount;
     DirectExecuteSQLCount = directExecuteSQLCount;
 }
Exemplo n.º 20
0
        /// <summary>从实体对象创建参数</summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">实体对象</param>
        /// <param name="session">指定会话,分表分库时必用</param>
        /// <returns></returns>
        public static IDataParameter[] CreateParameter <T>(this T entity, IEntitySession session) where T : IEntity
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }

            var dps = new List <IDataParameter>();

            if (entity == null)
            {
                return(dps.ToArray());
            }

            var fact = entity.GetType().AsFactory();
            //session ??= fact.Session;
            var db = session.Dal.Db;

            foreach (var item in fact.Fields)
            {
                dps.Add(db.CreateParameter(item.ColumnName ?? item.Name, entity[item.Name], item.Field));
            }

            return(dps.ToArray());
        }
Exemplo n.º 21
0
        //Low-level methods
        public ILogin FindLogin(IEntitySession session, string userName, string password, Guid?tenantId)
        {
            var context = session.Context;

            context.ValidateNotEmpty(userName, ClientFaultCodes.ValueMissing, "UserName", null, "UserName may not be empty");
            context.ValidateNotEmpty(password, ClientFaultCodes.ValueMissing, "Password", null, "Password may not be empty");
            context.ThrowValidation();
            userName = CheckUserName(context, userName);
            var userNameHash  = Util.StableHash(userName);
            var weakPwdHash   = GetWeakPasswordHash(password);
            var tenantIdValue = tenantId == null ? Guid.Empty : tenantId.Value;
            // Note: we do not compare usernames, only UserNameHash values; UserName might be null if we don't save them
            var qryLogins = from lg in session.EntitySet <ILogin>()
                            where lg.UserNameHash == userNameHash && lg.WeakPasswordHash == weakPwdHash &&
                            lg.TenantId == tenantIdValue
                            select lg;

            //Query logins table
            using (session.WithElevateRead()) {
                var logins = qryLogins.ToList(); //these are candidates, but most often will be just one
                var login  = logins.FirstOrDefault(lg => VerifyPassword(lg, password));
                if (login != null)
                {
                    VerifyExpirationSuspensionDates(login);
                }
                return(login);
            }
        }
Exemplo n.º 22
0
        // Note: modified for 1.3, Aug 2016 - added setting READ_COMMITTED_SNAPSHOT
        public void EnableSnapshotIsolation(IEntitySession session)
        {
            var dbConn = session.GetDirectDbConnector(admin: true);

            dbConn.OpenConnection();
            // First get current DB name
            var cmdGetDb = dbConn.DbConnection.CreateCommand();

            cmdGetDb.CommandText = "SELECT DB_NAME()";
            var dbName = dbConn.ExecuteScalar <string>(cmdGetDb);
            var cmd    = dbConn.DbConnection.CreateCommand();

            cmd.CommandText = string.Format("ALTER DATABASE {0} SET ALLOW_SNAPSHOT_ISOLATION ON;", dbName);
            dbConn.ExecuteNonQuery(cmd);
            //The following command enables special option that requires single-user mode -
            // otherwise it can hang forever
            cmd             = dbConn.DbConnection.CreateCommand();
            cmd.CommandText = string.Format(@"
ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE {0} SET READ_COMMITTED_SNAPSHOT ON;
ALTER DATABASE {0} SET MULTI_USER;
", dbName);
            dbConn.ExecuteNonQuery(cmd);
            dbConn.CloseConnection();
        }
Exemplo n.º 23
0
        /// <summary>更新</summary>
        /// <param name="session">实体会话</param>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public virtual async Task <Int32> UpdateAsync(IEntitySession session, IEntity entity)
        {
            // 没有脏数据,不需要更新
            if (!entity.HasDirty)
            {
                return(0);
            }

            IDataParameter[] dps = null;
            var sql = "";

            // 双锁判断脏数据
            lock (entity)
            {
                if (!entity.HasDirty)
                {
                    return(0);
                }

                sql = SQL(session, entity, DataObjectMethodType.Update, ref dps);
                if (sql.IsNullOrEmpty())
                {
                    return(0);
                }

                //清除脏数据,避免重复提交
                entity.Dirtys.Clear();
            }

            var rs = await session.ExecuteAsync(sql, CommandType.Text, dps);

            //EntityAddition.ClearValues(entity as EntityBase);

            return(rs);
        }
Exemplo n.º 24
0
 public static void RunIncludeQueries(IEntitySession session, LinqCommand command, object mainQueryResult)
 {
     // initial checks if there's anything to run
       var resultShape = command.Info.ResultShape;
       if (mainQueryResult == null || resultShape == QueryResultShape.Object)
     return;
       var allIncludes = session.Context.GetMergedIncludes(command.Info.Includes);
       if (allIncludes.Count == 0)
     return;
       // Get records from query result
       var records = new List<EntityRecord>();
       switch (resultShape) {
     case QueryResultShape.Entity:
       records.Add(EntityHelper.GetRecord(mainQueryResult));
       break;
     case QueryResultShape.EntityList:
       var list = mainQueryResult as IList;
       if (list.Count == 0)
     return;
       foreach (var ent in list)
     records.Add(EntityHelper.GetRecord(ent));
       break;
       }//switch;
       // actually run the includes
       var entityType = records[0].EntityInfo.EntityType;
       var helper = new IncludeQueryHelper(session, allIncludes);
       helper.RunIncludeQueries(entityType, records);
 }
Exemplo n.º 25
0
        public IOAuthClientFlow GetOAuthFlow(IEntitySession session, Guid flowId)
        {
            // Limit to logged in user, to avoid authorizatio exception
            var query = session.EntitySet <IOAuthClientFlow>().Where(f => f.Id == flowId);
            var user  = session.Context.User;

            if (user.Kind == UserKind.AuthenticatedUser)
            {
                query = query.Where(f => f.UserId == user.UserId);
            }
            var flow = query.FirstOrDefault();

            if (flow == null)
            {
                return(null);
            }
            if (flow.UserId != null)
            {
                var currUserId = session.Context.User.UserId;
                if (currUserId != flow.UserId.Value)
                {
                    return(null);
                }
            }
            CheckExpired(flow);
            return(flow);
        }
Exemplo n.º 26
0
        private IMsSqlDataTypesEntity CreateSpecialDataTypesEntity(IEntitySession session, string varCharProp)
        {
            var ent = session.NewEntity <IMsSqlDataTypesEntity>();

            ent.Id = Guid.NewGuid();
            // Test bug fix
            ent.CharNProp          = "12345678";
            ent.NCharNProp         = "234567";
            ent.VarCharProp        = varCharProp;
            ent.TimeProp           = DateTime.Now.TimeOfDay;
            ent.DateProp           = DateTime.Now.Date;
            ent.DateTimeProp       = DateTime.Now;
            ent.SmallDateTimeProp  = DateTime.Now;
            ent.DateTimeOffsetProp = new DateTimeOffset(2015, 3, 14, 9, 26, 53, TimeSpan.FromHours(-7)); //PI day/time in Seattle DateTimeOffset.Now;
            // ent.TimeStampProp is set automatically by database

            /*
             *    // Have no idea how to properly assign these properties; assigning random data does not work, so made columns nullable and skip assignment
             *    ent.GeographyProp = new byte[] { 1, 2, 3, 4 };
             *    ent.GeometryProp = new byte[] { 5, 6, 7, 8 };
             *    ent.HierarchyIdProp = new byte[] { 11, 12, 13, 14 };
             */
            ent.ImageProp      = new byte[] { 21, 22, 23, 24 };
            ent.NTextProp      = "abcd";
            ent.TextProp       = "defg";
            ent.XmlProp        = "<foo/>";
            ent.SmallMoneyProp = 1.23m;
            ent.SqlVariantProp = "xx"; // 1234;

            return(ent);
        }
Exemplo n.º 27
0
 public static int ImportSecretQuestions(IEntitySession session, string filePath)
 {
     Util.Check(File.Exists(filePath), "File {0} not found.", filePath);
       using(var fs = File.OpenRead(filePath)) {
     return ImportSecretQuestions(session, fs);
       }
 }
Exemplo n.º 28
0
        /// <summary>更新一批实体数据</summary>
        /// <param name="session">实体会话</param>
        /// <param name="setNames">更新属性列表</param>
        /// <param name="setValues">更新值列表</param>
        /// <param name="whereNames">条件属性列表</param>
        /// <param name="whereValues">条件值列表</param>
        /// <returns>返回受影响的行数</returns>
        public virtual Int32 Update(IEntitySession session, String[] setNames, Object[] setValues, String[] whereNames, Object[] whereValues)
        {
            var sc = Join(session, setNames, setValues, ", ");
            var wc = Join(session, whereNames, whereValues, " And ");

            return(Update(session, sc, wc));
        }
Exemplo n.º 29
0
        // Use it to import from resource - look at ImportDefaultSecretQuestions
        public static int ImportSecretQuestions(IEntitySession session, Stream stream)
        {
            var reader = new StreamReader(stream);
            var text   = reader.ReadToEnd(); // File.ReadAllLines(filePath);
            var lines  = text.Split(new [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            // Postgres blows up here, trying with LINQ
            //var oldList = session.GetEntities<ISecretQuestion>();
            var oldList = session.EntitySet <ISecretQuestion>().ToList();
            var count   = 0;

            foreach (var line in lines)
            {
                if (string.IsNullOrWhiteSpace(line) || line.StartsWith("//"))
                {
                    continue;
                }
                //check if there's existing
                var trimLine = line.Trim();
                var oldLine  = oldList.FirstOrDefault(l => l.Question == trimLine);
                if (oldLine != null)
                {
                    continue;
                }
                var q = session.NewEntity <ISecretQuestion>();
                q.Question = trimLine;
                q.Number   = count++;
                q.Flags    = SecretQuestionFlags.None;
            }
            return(count);
        }
Exemplo n.º 30
0
 public static int ImportSecretQuestions(IEntitySession session, string filePath)
 {
     Util.Check(File.Exists(filePath), "File {0} not found.", filePath);
     using (var fs = File.OpenRead(filePath)) {
         return(ImportSecretQuestions(session, fs));
     }
 }
Exemplo n.º 31
0
 internal static void UpdateStatus(this IEntitySession session, Guid tokenId, OAuthTokenStatus status)
 {
     var updQuery = from t in session.EntitySet <IOAuthAccessToken>()
                    where t.Id == tokenId
                    select new { Id = t.Id, Status = status };
     var cnt = updQuery.ExecuteUpdate <IOAuthAccessToken>();
 }
Exemplo n.º 32
0
        public IList <DataHistoryEntry> GetEntityHistory(IEntitySession session, Type entityType, object primaryKey,
                                                         DateTime?fromDate = null, DateTime?tillDate = null, int skip = 0, int take = 100, Guid?userId = null)
        {
            var entInfo = session.Context.App.Model.GetEntityInfo(entityType);

            Util.Check(entInfo != null, "Type {0} is not registered as an entity.", entityType);
            var entName     = entInfo.FullName;
            var entNameHash = Util.StableHash(entName);

            var where = session.NewPredicate <IDataHistory>()
                        .And(h => h.EntityNameHash == entNameHash && h.EntityName == entName)
                        .AndIfNotEmpty(fromDate, h => h.CreatedOn > fromDate.Value)
                        .AndIfNotEmpty(tillDate, h => h.CreatedOn < tillDate.Value);
            if (primaryKey != null)
            {
                var pkStr  = PrimaryKeyAsString(primaryKey);
                var pkHash = Util.StableHash(pkStr);
                where = where.And(h => h.EntityPrimaryKeyHash == pkHash && h.EntityPrimaryKey == pkStr);
            }
            var query       = session.EntitySet <IDataHistory>().Where(where).OrderByDescending(h => h.CreatedOn).Skip(skip).Take(take);
            var histEntList = query.ToList();
            var result      = histEntList.Select(h => h.ToHistoryEntry(entInfo)).ToList();

            return(result);
        }
Exemplo n.º 33
0
        private void PrintLastSql(IEntitySession session)
        {
            //Printout SQL query that was executed
            var cmd = session.GetLastCommand();

            Debug.WriteLine(cmd.ToLogString());
        }
Exemplo n.º 34
0
 public void SaveObjects(IEntitySession session, IList<object> items)
 {
     foreach (EventsPack pack in items) {
       foreach (var evt in pack.Events) {
     var ev = session.NewEvent(evt);
       }
     }//foreach
 }
Exemplo n.º 35
0
 //Called on background thread to persist the transaction data
 public void SaveObjects(IEntitySession session, IList<object> items)
 {
     foreach (TransactionLogEntry entry in items) {
     var entTrans = session.NewLogEntity<ITransactionLog>(entry);
     entTrans.Duration = entry.Duration;
     entTrans.RecordCount = entry.RecordCount;
     entTrans.Changes = entry.Changes;
       }
 }
Exemplo n.º 36
0
 public ITextTemplate GetTemplate(IEntitySession session, string templateName, string culture = "EN-US", Guid? ownerId = null)
 {
     var where = session.NewPredicate<ITextTemplate>()
     .And(t => t.Name == templateName)
     .AndIfNotEmpty(culture, t => t.Culture == culture)
     .AndIfNotEmpty(ownerId, t => t.OwnerId == ownerId.Value);
       var template = session.EntitySet<ITextTemplate>().Where(where).FirstOrDefault();
       return template;
 }
Exemplo n.º 37
0
 public BookOrderStats GetBookOrderStats(IEntitySession session, Guid orderId)
 {
     try {
     var order = session.GetEntity<IBookOrder>(orderId, LockOptions.SharedRead);
     return new BookOrderStats() {
       OrderId = orderId, LineCount = order.Lines.Count,
       MaxPrice = order.Lines.Max(ol => ol.Price) };
       } finally {
     session.ReleaseLocks();
       }
 }
Exemplo n.º 38
0
 //Alice defines a utility method to login users.
 public static ILogin Login(IEntitySession session, string userName, 
     int passwordHash)
 {
     // For simplicity, we use direct LINQ
     var query = from login in session.EntitySet<ILogin>()
         where login.UserName == userName &&
               login.PasswordHash == passwordHash
         select login;
     var logins = query.ToList();
     return logins.Count == 0 ? null : logins[0];
 }
Exemplo n.º 39
0
 void IObjectSaveHandler.SaveObjects(IEntitySession session, IList<object> items)
 {
     foreach (LoginLogEntry e in items) {
     var entry = session.NewEntity<ILoginLog>();
     entry.CreatedOn = e.CreatedOn;
     entry.UserName = e.UserName;
     entry.LoginId = e.LoginId;
     entry.EventType = e.EventType;
     entry.Notes = e.Notes;
     entry.WebCallId = e.WebCallId;
       }
 }
Exemplo n.º 40
0
 public string GetTemplatedValue(IEntitySession session, NotificationMessage message, string part) {
   if (_templateService == null)
     return null;
   var templateName = message.Type + "." + message.MediaType + "." + part;
   //Try with template
   var template = _templateService.GetTemplate(session, templateName, message.Culture, null);
   if (template == null && message.Culture != "EN-US") 
     template = _templateService.GetTemplate(session, templateName, "EN-US"); //try again with EN-US
   Util.Check(template != null, "Template {0}, culture '{1}' not found in TextTemplate table.", templateName, message.Culture);  
   var text = _templateService.Transform(template, message.Parameters);
   return text;
 }
Exemplo n.º 41
0
 public void EnableSnapshotIsolation(IEntitySession session)
 {
     var dbConn = session.GetDirectDbConnector(admin: true);
       dbConn.OpenConnection();
       // First get current DB name
       var cmdGetDb = dbConn.DbConnection.CreateCommand();
       cmdGetDb.CommandText = "SELECT DB_NAME()";
       var dbName = (string) dbConn.ExecuteDbCommand(cmdGetDb, Data.DbExecutionType.Scalar);
       var cmd = dbConn.DbConnection.CreateCommand();
       cmd.CommandText = string.Format("ALTER DATABASE {0} SET ALLOW_SNAPSHOT_ISOLATION ON;", dbName);
       dbConn.ExecuteDbCommand(cmd, Data.DbExecutionType.NonQuery);
       dbConn.CloseConnection();
 }
Exemplo n.º 42
0
 public void AddBookToOrder(IEntitySession session, Guid orderId, Guid bookId, int quantity)
 {
     var order = session.GetEntity<IBookOrder>(orderId, LockOptions.ForUpdate);
       var book = session.GetEntity<IBook>(bookId);
       var orderLine = session.NewEntity<IBookOrderLine>();
       orderLine.Order = order;
       orderLine.Book = book;
       orderLine.Quantity = quantity;
       orderLine.Price = book.Price;
       order.Lines.Add(orderLine);
       order.Total = order.Lines.Sum(ol => ol.Price * ol.Quantity);
       session.SaveChanges();
 }
Exemplo n.º 43
0
        // called by background process to save the info in provided session
        public void SaveObjects(IEntitySession session, IList<object> items)
        {
            foreach (WebCallContext webCtx in items) {
            var ent = session.NewEntity<IWebCallLog>();
            ent.Id = webCtx.Id;
            ent.WebCallId = webCtx.Id;
            ent.CreatedOn = webCtx.CreatedOn;
            ent.Duration = (int)(webCtx.TickCountEnd - webCtx.TickCountStart);
            ent.Url = webCtx.RequestUrl;
            ent.UrlTemplate = webCtx.RequestUrlTemplate;
            ent.UrlReferrer = webCtx.Referrer;
            ent.IPAddress = webCtx.IPAddress;
            var ctx = webCtx.OperationContext;
            if (ctx != null) {
              if (ctx.User != null)
            ent.UserName = ctx.User.UserName;
              if (ctx.LogLevel == LogLevel.Details)
            ent.LocalLog = ctx.GetLogContents();
              if (ctx.UserSession != null)
            ent.UserSessionId = ctx.UserSession.SessionId;
            }
            ent.ControllerName = webCtx.ControllerName;
            ent.MethodName = webCtx.MethodName;
            if (webCtx.Exception != null) {
              ent.Error = webCtx.Exception.Message;
              ent.ErrorDetails = webCtx.Exception.ToLogString();
            }
            ent.ErrorLogId = webCtx.ErrorLogId;
            ent.HttpMethod = webCtx.HttpMethod + string.Empty;
            ent.HttpStatus = webCtx.HttpStatus;
            ent.RequestSize = webCtx.RequestSize;
            ent.RequestHeaders = webCtx.RequestHeaders;
            ent.Flags = webCtx.Flags;
            if (webCtx.CustomTags.Count > 0)
              ent.CustomTags = string.Join(",", webCtx.CustomTags);
            if (webCtx.Flags.IsSet(WebCallFlags.HideRequestBody))
              ent.RequestBody = "(Omitted)";
            else
              ent.RequestBody = webCtx.RequestBody;

            ent.ResponseSize = webCtx.ResponseSize;
            ent.ResponseHeaders = webCtx.ResponseHeaders;
            if (webCtx.Flags.IsSet(WebCallFlags.HideResponseBody))
              ent.ResponseBody = "(Omitted)";
            else
              ent.ResponseBody = webCtx.ResponseBody;
            ent.RequestObjectCount = webCtx.RequestObjectCount;
            ent.ResponseObjectCount = webCtx.ResponseObjectCount;
              }
        }
Exemplo n.º 44
0
 public void ImportBooks(EntityApp app, int count = 250)
 {
     _app = app;
       _session = _app.OpenSystemSession();
       //Preload caches
       _bookCache = _session.GetEntities<IBook>(take: 1000).ToDictionary(b => b.Title, StringComparer.InvariantCultureIgnoreCase);
       _publishersCache = _session.GetEntities<IPublisher>(take: 200).ToDictionary(p => p.Name, StringComparer.InvariantCultureIgnoreCase);
       _authorsCache = _session.GetEntities<IAuthor>(take: 1000).ToDictionary(a => a.FirstName + a.LastName, StringComparer.InvariantCultureIgnoreCase);
       _client = new GoogleBooksApiClient();
       var batchSize = count / 5;
       ImportBooksInCategory(BookCategory.Programming, "c#", batchSize);
       ImportBooksInCategory(BookCategory.Programming, "Linux", batchSize);
       ImportBooksInCategory(BookCategory.Fiction, "Comics", batchSize);
       ImportBooksInCategory(BookCategory.Fiction, "Science fiction", batchSize);
       ImportBooksInCategory(BookCategory.Kids, "Fairy tales", batchSize);
 }
Exemplo n.º 45
0
 public DataHistoryEntry GetEntityOnDate(IEntitySession session, Type entityType, object primaryKey, DateTime onDate)
 {
     Util.Check(primaryKey != null, "Primary key may not be null");
       var entInfo = session.Context.App.Model.GetEntityInfo(entityType);
       Util.Check(entInfo != null, "Type {0} is not registered as an entity.", entityType);
       var entName = entInfo.FullName;
       var entNameHash = Util.StableHash(entName);
       string pkStr = PrimaryKeyAsString(primaryKey);
       var pkHash = Util.StableHash(pkStr);
       var query = session.EntitySet<IDataHistory>().Where(h => h.EntityNameHash == entNameHash && h.EntityName == entName &&
      h.EntityPrimaryKeyHash == pkHash && h.EntityPrimaryKey == pkStr && h.CreatedOn < onDate)
      .OrderByDescending(h => h.CreatedOn);
       var histEnt = query.FirstOrDefault();
       var result = histEnt.ToHistoryEntry(entInfo);
       return result;
 }
Exemplo n.º 46
0
 public static IOAuthRemoteServer CreateOrUpdateServer(IEntitySession session,  string name, OAuthServerOptions options, 
     string siteUrl, string authorizationUrl, string tokenRequestUrl, string tokenRefreshUrl, string scopes,
     string documentationUrl, string basicProfileUrl, string profileUserIdTag)
 {
     IOAuthRemoteServer srv = session.EntitySet<IOAuthRemoteServer>().Where(s => s.Name == name).FirstOrDefault();
       if(srv == null)
     srv = session.NewEntity<IOAuthRemoteServer>();
       srv.Name = name;
       srv.Options = options;
       srv.SiteUrl = siteUrl;
       srv.AuthorizationUrl = authorizationUrl;
       srv.TokenRequestUrl = tokenRequestUrl;
       srv.TokenRefreshUrl = tokenRefreshUrl;
       srv.Scopes = scopes;
       srv.DocumentationUrl = documentationUrl;
       srv.BasicProfileUrl = basicProfileUrl;
       srv.ProfileUserIdTag = profileUserIdTag;
       return srv;
 }
Exemplo n.º 47
0
 public void SaveObjects(IEntitySession session, IList<object> items)
 {
     //Group by WebCallId, SessionId, UserName
       var entries = items.OfType<LogEntry>().ToList();
       var groupedByWebCall = entries.GroupBy(e => e.WebCallId);
       foreach (var wg in groupedByWebCall) {
     if (wg.Key == null) {
       var groupedBySessionId = wg.GroupBy(e => e.UserSessionId);
       foreach (var sg in groupedBySessionId) {
     if (sg.Key == null) {
       var groupedByUserName = sg.GroupBy(e => e.UserName);
       foreach (var ug in groupedByUserName)
         SaveEntries(session, ug);
     } else
       SaveEntries(session, sg);
     }// foreach sg
       } //if wg.Key
       else
     SaveEntries(session, wg);
       }//foreach wg
 }
Exemplo n.º 48
0
 public IList<DataHistoryEntry> GetEntityHistory(IEntitySession session, Type entityType, object primaryKey, 
     DateTime? fromDate = null, DateTime? tillDate = null, int skip = 0, int take = 100, Guid? userId = null)
 {
     var entInfo = session.Context.App.Model.GetEntityInfo(entityType);
       Util.Check(entInfo != null, "Type {0} is not registered as an entity.", entityType);
       var entName = entInfo.FullName;
       var entNameHash = Util.StableHash(entName);
       var where = session.NewPredicate<IDataHistory>()
     .And(h => h.EntityNameHash == entNameHash && h.EntityName == entName)
     .AndIfNotEmpty(fromDate, h => h.CreatedOn > fromDate.Value)
     .AndIfNotEmpty(tillDate, h => h.CreatedOn < tillDate.Value);
       if (primaryKey != null) {
     var pkStr = PrimaryKeyAsString(primaryKey);
     var pkHash = Util.StableHash(pkStr);
     where = where.And(h => h.EntityPrimaryKeyHash == pkHash && h.EntityPrimaryKey == pkStr);
       }
       var query = session.EntitySet<IDataHistory>().Where(where).OrderByDescending(h => h.CreatedOn).Skip(skip).Take(take);
       var histEntList = query.ToList();
       var result = histEntList.Select(h => h.ToHistoryEntry(entInfo)).ToList();
       return result;
 }
Exemplo n.º 49
0
 // Use it to import from resource - look at ImportDefaultSecretQuestions
 public static int ImportSecretQuestions(IEntitySession session, Stream stream)
 {
     var reader = new StreamReader(stream);
       var text = reader.ReadToEnd(); // File.ReadAllLines(filePath);
       var lines = text.Split(new [] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
       var oldList = session.GetEntities<ISecretQuestion>();
       var count = 0;
       foreach(var line in lines) {
     if(string.IsNullOrWhiteSpace(line) || line.StartsWith("//"))
       continue;
     //check if there's existing
     var trimLine = line.Trim();
     var oldLine = oldList.FirstOrDefault(l => l.Question == trimLine);
     if(oldLine != null)
       continue;
     var q = session.NewEntity<ISecretQuestion>();
     q.Question = trimLine;
     q.Number = count++;
     q.Flags = SecretQuestionFlags.None;
       }
       return count;
 }
Exemplo n.º 50
0
 //Low-level methods
 public ILogin FindLogin(IEntitySession session, string userName, string password, Guid? tenantId)
 {
     var context = session.Context;
       context.ValidateNotEmpty(userName, ClientFaultCodes.ValueMissing, "UserName", null, "UserName may not be empty");
       context.ValidateNotEmpty(password, ClientFaultCodes.ValueMissing, "Password", null, "Password may not be empty");
       context.ThrowValidation();
       userName = CheckUserName(context, userName);
       var userNameHash = Util.StableHash(userName);
       var weakPwdHash = GetWeakPasswordHash(password);
       var tenantIdValue = tenantId == null ? Guid.Empty : tenantId.Value;
       // Note: we do not compare usernames, only UserNameHash values; UserName might be null if we don't save them
       var qryLogins = from lg in session.EntitySet<ILogin>()
               where lg.UserNameHash == userNameHash && lg.WeakPasswordHash == weakPwdHash
                 && lg.TenantId == tenantIdValue
               select lg;
       //Query logins table
       using(session.WithElevateRead()) {
     var logins = qryLogins.ToList(); //these are candidates, but most often will be just one
     var login = logins.FirstOrDefault(lg => VerifyPassword(lg, password));
     if(login != null)
       VerifyExpirationSuspensionDates(login);
     return login;
       }
 }
Exemplo n.º 51
0
 public SaveEventArgs(IEntitySession session)
 {
     Session = session;
 }
Exemplo n.º 52
0
 public NorthwindSession(IEntitySession session)
 {
     this.session = session;
 }
Exemplo n.º 53
0
 public EntitySessionEventArgs(IEntitySession session)
 {
     Session = session;
 }
Exemplo n.º 54
0
 private void PrintLastSql(IEntitySession session)
 {
     //Printout SQL query that was executed
       var cmd = session.GetLastCommand();
       Debug.WriteLine(cmd.ToLogString());
 }
Exemplo n.º 55
0
 private void RandomizeRecordOrder(IEntitySession session)
 {
     var entSession = session as EntitySession;
       var recs = entSession.RecordsChanged;
       var rand = new Random();
       for (int i = 0; i < recs.Count; i++) {
     var rec = recs[0];
     recs.RemoveAt(0);
     var newIndex = rand.Next(recs.Count - 1);
     recs.Insert(newIndex, rec);
       }
 }
Exemplo n.º 56
0
        private IDataTypesEntity CreateDataTypesEntity(IEntitySession session, string strProp, string memoProp)
        {
            var ent = session.NewEntity<IDataTypesEntity>();
              var id = ent.Id = Guid.NewGuid();
              ent.StringProp = strProp;
              ent.MemoProp = memoProp;
              ent.ByteProp = 250;
              ent.BoolProp = true;
              ent.Int16Prop = -234;
              ent.Int32Prop = -345;
              ent.Int64Prop = Int64.MinValue; // (long)Int32.MaxValue + 100;
              ent.Int32NullProp = 222;
              ent.CharProp = 'X';

              ent.DoubleProp = 3.456;
              ent.DoublePropNull = 1.2345;
              ent.SingleProp = 4.567f;
              ent.DecProp = 2.34m;
              ent.MoneyProp = 3.45m;
              ent.DateTimeProp = DateTime.Now;
              ent.TimeProp = DateTime.Now.TimeOfDay;

              ent.EnumProp = SimpleEnum.Two;
              ent.EnumNullProp = SimpleEnum.Three;
              ent.BitsProp = BitEnum.Bit1 | BitEnum.Bit2;
              ent.BitsNullProp = BitEnum.Bit0;

              ent.ByteArrayProp = new byte[] { 1, 2, 3 };
              ent.BinaryProp = new Binary(new byte[] { 4, 5, 6 });
              ent.BigBinaryProp = new Binary(new byte[] { 11, 12, 13, 14 });

              ent.SByteProp = 12;
              ent.UInt16Prop = 456;
              ent.UInt32Prop = 567;
              ent.UInt64Prop = 678;

              return ent;
        }
Exemplo n.º 57
0
        private IMsSqlDataTypesEntity CreateSpecialDataTypesEntity(IEntitySession session, string varCharProp)
        {
            var ent = session.NewEntity<IMsSqlDataTypesEntity>();
              ent.Id = Guid.NewGuid();
              ent.CharNProp = "12345678";
              ent.NCharNProp = "234567";
              ent.VarCharProp = varCharProp;
              ent.TimeProp = DateTime.Now.TimeOfDay;
              ent.DateProp = DateTime.Now.Date;
              ent.DateTimeProp = DateTime.Now;
              ent.SmallDateTimeProp = DateTime.Now;
              ent.DateTimeOffsetProp = new DateTimeOffset(2015, 3, 14, 9, 26, 53, TimeSpan.FromHours(-7)); //PI day/time in Seattle DateTimeOffset.Now;
              // ent.TimeStampProp is set automatically by database
              /*
            // Have no idea how to properly assign these properties; assigning random data does not work, so made columns nullable and skip assignment
            ent.GeographyProp = new byte[] { 1, 2, 3, 4 };
            ent.GeometryProp = new byte[] { 5, 6, 7, 8 };
            ent.HierarchyIdProp = new byte[] { 11, 12, 13, 14 };
               */
              ent.ImageProp = new byte[] { 21, 22, 23, 24 };
              ent.NTextProp = "abcd";
              ent.TextProp = "defg";
              ent.XmlProp = "<foo/>";
              ent.SmallMoneyProp = 1.23m;
              ent.SqlVariantProp = "xx"; // 1234;

              return ent;
        }
Exemplo n.º 58
0
 public AppErrorEventArgs(IEntitySession session, Exception exception)
 {
     Session = session;
       Exception = exception;
 }
Exemplo n.º 59
0
 private IncludeQueryHelper(IEntitySession session, IList<LambdaExpression> includes)
 {
     _session = (EntitySession)session;
       _includes = includes;
 }
Exemplo n.º 60
0
 public LinqCommandEventArgs(IEntitySession session, LinqCommand command)
     : base(session)
 {
     Command = command;
 }