Example #1
0
        private void LoginLogWrite(BCEnterpriseContext db, UserLoginState userLoginState, EnterpriseData.Common.LoginStatus status, string description)
        {
            if (userLoginState == null)
            {
                return;
            }
            var loginLog = new UserLoginLog
            {
                UserID      = userLoginState.UserID,
                UserName    = userLoginState.UserName,
                Device      = userLoginState.Device,
                IP          = userLoginState.LoginIP,
                Status      = (int)status,
                Description = description
            };

            if (status == LoginStatus.Login && userLoginState.LoginTime.HasValue)
            {
                loginLog.Time = userLoginState.LoginTime.Value;
            }
            else
            {
                loginLog.Time = DBTimeHelper.DBNowTime(db);
            }

            LoginLogWrite(db, loginLog);
        }
 public bool SyncSceneItemStatusAndComments(string sceneItemID, ItemStatus status, Comment[] comments)
 {
     try
     {
         if (string.IsNullOrEmpty(sceneItemID))
         {
             throw new ArgumentNullException("sceneItemID");
         }
         var db   = new MongoDbProvider <SceneItem>();
         var item = db.GetById(sceneItemID);
         if (item == null)
         {
             throw new KnownException("此现场数据不存在.");
         }
         item.Comments   = comments.ToList();
         item.Status     = status;
         item.UpdateTime = DBTimeHelper.DBNowTime();
         db.Update(item);
         return(true);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public bool SetSceneItemStatus(string sceneItemID, Examine examine)
        {
            try
            {
                if (string.IsNullOrEmpty(sceneItemID))
                {
                    throw new KnownException("id为空,无法设置!");
                }
                var db = new MongoDbProvider <SceneItem>();
//                var item = db.GetByCondition(x=>x.);
                //if (examine.ExamineStatus == ItemStatus.Final)
                //{
                //    SetSceneStatusFinal(sceneItemID);
                //}
                var tempstring = GetSceneItemByRelation(sceneItemID, db);
                var item       = db.GetByCondition(x => x.Id == tempstring);
                item.Status  = examine.ExamineStatus;
                examine.Time = DBTimeHelper.DBNowTime();
                (item.Examines ?? new List <Examine>()).Add(examine);
                item.UpdateTime = examine.Time;
                db.Update(item);
                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #4
0
        public List <UserMessageQueueItem> PopupUserMessageQueueItem(string userId, string device)
        {
            if (userId == null)
            {
                throw new ArgumentNullException("userId");
            }
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            var db     = new MongoDbProvider <UserMessageQueueItem>();
            var list   = db.GetAll(n => n.State == AppSyncDataStateEnum.Normal && n.UserID == userId && n.Device == device).ToList();
            var result = list.ToArray().Clone() as UserMessageQueueItem[];

            foreach (var l in list)
            {
                l.Time = l.Time.ToLocalTime();
                var chatMessage = l.Data as ChatMessage;
                if (chatMessage == null)
                {
                    continue;
                }
                chatMessage.SendTime = chatMessage.SendTime.ToLocalTime();
                chatMessage.IsRead   = ReadStatus.Read;
            }
            list.ForEach(n =>
            {
                n.State      = AppSyncDataStateEnum.Sent;
                n.UpdateTime = DBTimeHelper.DBNowTime();
                db.Update(n);
            });

            return(null != result?result.ToList() : new List <UserMessageQueueItem>());
        }
        public bool DeleteCommentItem(string sceneItemID, Guid commentGuid, DateTime updateTime)
        {
            var mgdb      = new MongoDbProvider <SceneItem>();
            var sceneItem = mgdb.GetById(sceneItemID);

            if (sceneItem.Status == ItemStatus.Final)
            {
                throw new KnownException("已经归档,无法删除");
            }
            var del = sceneItem.Comments.FirstOrDefault(o => o.CommentGuid == commentGuid);

            if (null == del)
            {
                throw new KnownException("评论不存在,无法删除");
            }
            if (sceneItem.Comments.Remove(del))
            {
                sceneItem.UpdateTime = DBTimeHelper.DBNowTime();
            }
            mgdb.Update(sceneItem);

            //  删除评论分发消息
            Send2MsmqAsDelete(commentGuid.ToString(), OperationEnum.Deleted, sceneItem.SceneID);
            return(true);
        }
        public Infrastructure.MsmqHelper.MessageItem GetChangedEntryData(
            System.Data.Entity.Infrastructure.DbEntityEntry entry)
        {
            var result = new Infrastructure.MsmqHelper.MessageItem
            {
                EntityName = "SceneType",
                Data       = new List <Infrastructure.MsmqHelper.CustomKeyValue>()
                {
                    new ML.BC.Infrastructure.MsmqHelper.CustomKeyValue
                    {
                        Key   = "SceneTypeID",
                        Value = this.ID.ToString()
                    },
                    new ML.BC.Infrastructure.MsmqHelper.CustomKeyValue
                    {
                        Key   = "EnterpriseID",
                        Value = this.EnterpriseID
                    }
                },
                Operation  = (ML.BC.Infrastructure.MsmqHelper.OperationEnum)entry.State,
                Type       = Infrastructure.MsmqHelper.TypeEnum.SceneType,
                ChangeTime = DBTimeHelper.DBNowTime()
            };

            return(result);
        }
Example #7
0
 private static MessageItem MakeCommonInfo(ChatMessageDto msgDto)
 {
     return(new MessageItem
     {
         EntityName = "ChatMessage",
         Type = TypeEnum.Message,
         Operation = OperationEnum.Added,
         ChangeTime = DBTimeHelper.DBNowTime(),
         Data =
             new List <CustomKeyValue>
         {
             new CustomKeyValue {
                 Key = "SendUserID", Value = msgDto.SendUserID
             },
             new CustomKeyValue {
                 Key = "Text", Value = msgDto.Message
             },
             new CustomKeyValue {
                 Key = "SendTime", Value = msgDto.SendTime.ToString()
             },
             new CustomKeyValue {
                 Key = "MessageID", Value = msgDto.MessageID.ToString()
             }
         }
     });
 }
Example #8
0
        private bool Send2Msmq(string id, OperationEnum operation)
        {
            try
            {
                var msg = new MessageItem
                {
                    EntityName = _collectionName,
                    Operation  = operation,
                    Type       = TypeName2TypeEnum(_collectionName),
                    ChangeTime = DBTimeHelper.DBNowTime(),
                    Data       = new List <CustomKeyValue> {
                        new CustomKeyValue()
                        {
                            Key = "Id", Value = id
                        }
                    }
                };

                using (var msmq = ML.BC.Infrastructure.Ioc.GetService <IMsmqProvider>())
                {
                    msmq.Send <List <MessageItem> >(new Message(new List <MessageItem> {
                        msg
                    }));
                    return(true);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #9
0
 public SceneItem AddCommentItem(string sceneItemID, Comment comment, ItemStatus status)
 {
     try
     {
         if (string.IsNullOrEmpty(sceneItemID) || null == comment)
         {
             throw new KnownException("id或信息对象为空,无法添加!");
         }
         var db   = new MongoDbProvider <SceneItem>();
         var item = db.GetById(sceneItemID);
         if (item == null)
         {
             throw new KnownException("此数据在服务器上已被删除,请手动删除此条数据!");
         }
         if (ItemStatus.Final == item.Status)
         {
             throw new KnownException("已经归档,无法评论!");
         }
         if (item.Comments == null)
         {
             item.Comments = new List <Comment>();
         }
         comment.Time = DBTimeHelper.DBNowTime();
         item.Comments.Add(comment);
         item.Status     = status;
         item.UpdateTime = DBTimeHelper.DBNowTime();
         var re = db.Update(item);
         re.Images = MakeUrlWithPictureName(re.Images);
         return(re);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
 public void DeleteSceneItemPicture(string sceneItemId, string orgPicName)
 {
     try
     {
         if (string.IsNullOrEmpty(sceneItemId) || string.IsNullOrEmpty(orgPicName))
         {
             throw new KnownException("参数不允许为空");
         }
         var db        = new MongoDbProvider <SceneItem>();
         var sceneItem = db.GetById(sceneItemId);
         if (null == sceneItem)
         {
             throw new KnownException("该现场数据不存在");
         }
         var pic = sceneItem.Images.FirstOrDefault(x => x.OriginalPicture.Equals(orgPicName));
         if (pic != null)
         {
             var orglen = db.GetFileAsStream(orgPicName, PictureDbName).Length;
             var thulen = db.GetFileAsStream(pic.ThumbnailPicture, PictureDbName).Length;
             db.DeleteFileByName(pic.OriginalPicture, PictureDbName);
             db.DeleteFileByName(pic.ThumbnailPicture, PictureDbName);
             sceneItem.TotalOrgImageBytes = sceneItem.TotalOrgImageBytes - orglen - thulen;
             sceneItem.Images.Remove(pic);
             sceneItem.UpdateTime = DBTimeHelper.DBNowTime();
             sceneItem.Count      = sceneItem.Count - 1;
             db.Update(sceneItem);
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Example #11
0
 public DateTime GetWorkerTime()
 {
     try
     {
         return(DBTimeHelper.DBNowTime());
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Example #12
0
        /// <summary>
        /// 设置同步记录,如果存在就更新
        /// </summary>
        /// <param name="syncStateDtos"></param>
        /// <returns></returns>
        public bool SetSyncState(params SyncStateDto[] syncStateDtos)
        {
            lock (SETSYNCSTATELOCK)
            {
                try
                {
                    if (null == syncStateDtos || syncStateDtos.Length == 0)
                    {
                        throw new ArgumentNullException("syncStateDtos");
                    }
                    for (int i = 0; i < syncStateDtos.Length; i++)
                    {
                        if (string.IsNullOrEmpty(syncStateDtos[i].UserID) || string.IsNullOrEmpty(syncStateDtos[i].DeviceID) || syncStateDtos[i].ActionType < 0)
                        {
                            throw new KnownException("对象索引:" + i + " 缺少必要信息,无法添加或更新!");
                        }
                    }

                    using (var db = new BCEnterpriseContext())
                    {
                        syncStateDtos.ToList().ForEach(m => m.SyncTime = DBTimeHelper.DBNowTime(db));
                        var objs = syncStateDtos.Select(n => new SyncState
                        {
                            SyncStateID = n.SyncStateID,
                            UserID      = n.UserID,
                            DeviceID    = n.DeviceID,
                            ActionType  = n.ActionType,
                            SyncTime    = n.SyncTime
                        }).ToList();

                        List <string> userids     = objs.Select((n) => n.UserID).ToList();
                        List <string> deviceIDs   = objs.Select((n) => n.DeviceID).ToList();
                        List <byte>   actionTypes = objs.Select((n) => n.ActionType).ToList();
                        var           oldlist     = db.SyncStates.Where(m => userids.Contains(m.UserID) && deviceIDs.Contains(m.DeviceID) && actionTypes.Contains(m.ActionType));
                        oldlist.ToList().ForEach(n =>
                        {
                            db.SyncStates.Remove(n);
                        });

                        objs.ForEach(n =>
                        {
                            db.SyncStates.Add(n);
                        });
                        db.SaveChanges();
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Example #13
0
        private void SetUpdateTime(System.Data.Entity.Infrastructure.DbEntityEntry entry)
        {
            if (entry.State != EntityState.Added && entry.State != EntityState.Modified)
            {
                return;
            }

            var  entity = entry.Entity;
            Type type   = entity.GetType();
            var  pi     = type.GetProperty("UpdateTime");

            if (pi != null)
            {
                pi.SetValue(entity, DBTimeHelper.DBNowTime(this));
            }
        }
Example #14
0
        private bool ScanSceneParents(string userID, string sceneID, BCEnterpriseContext db)
        {
            try
            {
                var templist  = GetParentsScenes(sceneID, db);
                var list      = templist.Select(x => x.SceneID).ToList();
                var scenelist = db.ScanLog.Where(x => list.Contains(x.ObjectID) && x.Type == (int)ScanType.Scene && x.UserID.Equals(userID)).Select(n => n.ObjectID).ToList();
                var sc        = new List <string>();
                sc.Add(sceneID);
                if (0 < scenelist.Count())
                {
                    sc = list.Except(scenelist).ToList();
                    sc.Distinct();
                }

                if (1 < sc.Count())
                {
                    foreach (var scene in sc)
                    {
                        var obj = new ScanLog()
                        {
                            UserID   = userID,
                            ObjectID = scene,
                            Type     = (int)ScanType.Scene,
                            Time     = DBTimeHelper.DBNowTime()
                        };
                        db.ScanLog.Add(obj);
                    }
                }
                else
                {
                    var obj = new ScanLog()
                    {
                        UserID   = userID,
                        ObjectID = sceneID,
                        Type     = (int)ScanType.Scene,
                        Time     = DBTimeHelper.DBNowTime()
                    };
                    db.ScanLog.Add(obj);
                }
                return(0 < db.SaveChanges());
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Example #15
0
 public bool AddScan(ScanDto scan)
 {
     try
     {
         if (string.IsNullOrEmpty(scan.ObjectID) || string.IsNullOrEmpty(scan.UserID))
         {
             return(false);
         }
         using (var db = new BCEnterpriseContext())
         {
             var scanlog =
                 db.ScanLog.FirstOrDefault(x => x.ObjectID.Equals(scan.ObjectID) && x.UserID.Equals(scan.UserID) && x.Type == (int)scan.Type);
             if (null != scanlog)
             {
                 return(false);
             }
             if (scan.Type == ScanType.Project)
             {
                 db.ScanLog.Add(new ScanLog()
                 {
                     UserID   = scan.UserID,
                     ObjectID = scan.ObjectID,
                     Type     = (int)scan.Type,
                     Time     = DBTimeHelper.DBNowTime()
                 });
                 return(0 < db.SaveChanges());
             }
             else
             {
                 return(ScanSceneParents(scan.UserID, scan.ObjectID, db));
             }
             //var temp = (scan.Type == ScanType.Project) ? (null == db.ScanLog.Add(new ScanLog()
             //{
             //    UserID = scan.UserID,
             //    ObjectID = scan.ObjectID,
             //    Type = (int)scan.Type,
             //    Time = DBTimeHelper.DBNowTime()
             //})) : ScanSceneParents(scan.UserID, scan.ObjectID,db);
             //return temp;
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Example #16
0
 public bool YesOrNo(DateTime?time)
 {
     try
     {
         if (null != time)
         {
             return(3 <= (DBTimeHelper.DBNowTime() - time).Value.Days);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Example #17
0
 public bool SetSceneItemStatus(string sceneItemID, ItemStatus status, DateTime updateTime)
 {
     try
     {
         if (string.IsNullOrEmpty(sceneItemID))
         {
             throw new KnownException("id为空,无法设置!");
         }
         var db   = new MongoDbProvider <SceneItem>();
         var item = db.GetById(sceneItemID);
         item.UpdateTime = DBTimeHelper.DBNowTime();
         item.Status     = status;
         db.Update(item);
         return(true);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #18
0
        public bool AddUserMessageQueueItem(UserMessageQueueItem userMessaeQueueItem)
        {
            if (userMessaeQueueItem == null)
            {
                throw new ArgumentNullException("userMessaeQueueItem");
            }
            if (string.IsNullOrEmpty(userMessaeQueueItem.UserID) || string.IsNullOrEmpty(userMessaeQueueItem.Device))
            {
                throw new KnownException("用户ID及设备不能为空");
            }

            userMessaeQueueItem.Id         = string.Empty;
            userMessaeQueueItem.State      = AppSyncDataStateEnum.Normal;
            userMessaeQueueItem.UpdateTime = DBTimeHelper.DBNowTime();

            var db = new MongoDbProvider <UserMessageQueueItem>();

            db.Insert(userMessaeQueueItem);
            return(true);
        }
        public Infrastructure.MsmqHelper.MessageItem GetChangedEntryData(System.Data.Entity.Infrastructure.DbEntityEntry entry)
        {
            var result = new Infrastructure.MsmqHelper.MessageItem
            {
                EntityName = "Project",
                Data       = new List <Infrastructure.MsmqHelper.CustomKeyValue>()
                {
                    new  ML.BC.Infrastructure.MsmqHelper.CustomKeyValue {
                        Key   = "ProjectID",
                        Value = this.ProjectID
                    },
                    new  ML.BC.Infrastructure.MsmqHelper.CustomKeyValue {
                        Key   = "DepartMentIDs",
                        Value = this.Departments
                    }
                },
                Operation  = (ML.BC.Infrastructure.MsmqHelper.OperationEnum)entry.State,
                Type       = Infrastructure.MsmqHelper.TypeEnum.Project,
                ChangeTime = DBTimeHelper.DBNowTime()
            };

            return(result);
        }
        //  暂用方法,需要优化
        private static bool Send2MsmqAsDelete(string id, OperationEnum operation, string sceneID)
        {
            try
            {
                var msg = new MessageItem
                {
                    EntityName = "SceneItem",
                    Operation  = operation,
                    Type       = TypeEnum.SceneData,
                    ChangeTime = DBTimeHelper.DBNowTime(),
                    Data       = new List <CustomKeyValue>
                    {
                        new CustomKeyValue()
                        {
                            Key = "Id", Value = id
                        },
                        new CustomKeyValue()
                        {
                            Key = "SceneID", Value = sceneID
                        }
                    }
                };

                using (var msmq = ML.BC.Infrastructure.Ioc.GetService <IMsmqProvider>())
                {
                    msmq.Send <List <MessageItem> >(new Message(new List <MessageItem> {
                        msg
                    }));
                    return(true);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #21
0
 public bool UpdateSceneType(SceneTypeDto sceneType)
 {
     try
     {
         if (string.IsNullOrEmpty(sceneType.EnterpriseID))
         {
             throw new KnownException("企业ID不允许为空");
         }
         using (var db = new BCEnterpriseContext())
         {
             var temp = db.SceneTypes.FirstOrDefault(x => x.ID == sceneType.ID);
             temp.Name         = sceneType.Name;
             temp.EnterpriseID = sceneType.EnterpriseID;
             temp.ParentID     = sceneType.ParentID;
             temp.Available    = sceneType.Available;
             temp.UpdateTime   = DBTimeHelper.DBNowTime(db);
             return(0 < db.SaveChanges());
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Example #22
0
 public bool UpdateFileType(string Name, int knowledgeType, Guid fileGuid)
 {
     try
     {
         using (var db = new BCEnterpriseContext())
         {
             var list = db.KnowledgeBase.Where(x => x.FileGUID == fileGuid);
             if (list.Count() > 0)
             {
                 foreach (var temp in list)
                 {
                     temp.KnowledgeType = knowledgeType;
                     temp.Name          = Name;
                     temp.UpdateTime    = DBTimeHelper.DBNowTime();
                 }
             }
             return(0 < db.SaveChanges());
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
        public SceneItem AddCommentItem(string sceneItemID, Comment comment, Examine examine)
        {
            try
            {
                if (string.IsNullOrEmpty(sceneItemID) || null == comment)
                {
                    throw new KnownException("id或信息对象为空,无法添加!");
                }
                var db   = new MongoDbProvider <SceneItem>();
                var item = db.GetById(sceneItemID);
                if (item == null)
                {
                    throw new KnownException("此数据在服务器上已被删除,请手动删除此条数据!");
                }
                if (ItemStatus.Final == item.Status)
                {
                    throw new KnownException("已经归档,无法评论!");
                }
                if (item.Comments == null)
                {
                    item.Comments = new List <Comment>();
                }
                var tempitem = new SceneItem();
                if (examine.ExamineStatus != item.Status)
                {
                    var tempstring = GetSceneItemByRelation(sceneItemID, db);
                    tempitem = db.GetById(tempstring);
                    if (null != tempitem)
                    {
                        if (null == tempitem.Examines)
                        {
                            tempitem.Examines = new List <Examine>();
                        }
                        examine.Time = DBTimeHelper.DBNowTime();
                        tempitem.Examines.Add(examine);
                        tempitem.UpdateTime = examine.Time;
                    }
                }
                comment.Time = DBTimeHelper.DBNowTime();
                var temp = new Guid();
                temp = Guid.NewGuid();
                comment.CommentGuid = temp;
                item.Comments.Add(comment);
//                item.Status = examine.ExamineStatus;
                if (examine.ExamineStatus == ItemStatus.Redo)
                {
                    item.IsExamine = false;
                }
                item.UpdateTime = DBTimeHelper.DBNowTime();

                var re = db.Update(item);
                re.Images = MakeUrlWithPictureName(re.Images);
                if (examine.ExamineStatus != item.Status)
                {
                    tempitem.Status = examine.ExamineStatus;
                    db.Update(tempitem);
                }
                return(re);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public List <SceneItemDto> GetAllByStatus(string userID, string deviceID, string sceneID, ItemStatus status,
                                                  int pageSize, DateTime time, out int count)
        {
            if (string.IsNullOrEmpty(sceneID))
            {
                throw new ArgumentNullException("sceneID");
            }

            using (var db = new BCEnterpriseContext())
            {
                var iSsync =
                    db.SyncStates.Any(
                        n =>
                        n.UserID == userID && n.DeviceID == deviceID &&
                        n.ActionType == (int)ML.BC.Infrastructure.MsmqHelper.TypeEnum.SceneData);
                if (!iSsync)
                {
                    var syncSceneData = new SyncState()
                    {
                        UserID     = userID,
                        DeviceID   = deviceID,
                        ActionType = (int)TypeEnum.SceneData,
                        SyncTime   = DBTimeHelper.DBNowTime(db)
                    };

                    db.SyncStates.Add(syncSceneData);
                    if (!(0 < db.SaveChanges()))
                    {
                        var logger = log4net.LogManager.GetLogger(typeof(SceneItemManagementService));
                        logger.Error("第一次写入同步现场数据的状态失败!");
                    }
                }
            }

            var mgdb  = new MongoDbProvider <SceneItem>();
            var query = ItemStatus.All == status
                ? mgdb.GetAll(o => (o.SceneID == sceneID) && (o.UpdateTime < time))
                : mgdb.GetAll(o => (o.SceneID == sceneID) && (o.Status == status) && (o.UpdateTime < time));

            count = query.Count();
            if (pageSize < 1)
            {
                pageSize = 10;
            }
            var sceneItems = query
                             .OrderByDescending(obj => obj.CreateTime)
                             .Take(pageSize)
                             .ToList();

            using (var db = new BCEnterpriseContext())
            {
                if (0 == sceneItems.Count)
                {
                    return(new List <SceneItemDto>());
                }
                var userIds    = sceneItems.Select(o => o.UserID).ToList();
                var reUserInfo = db.FrontUsers.Where(obj => userIds.Contains(obj.UserID)).Select(o => new
                {
                    uid     = o.UserID,
                    name    = o.Name,
                    picture = o.Picture
                }).ToList();

                var re = (from item in sceneItems
                          join r in reUserInfo on item.UserID equals r.uid into tempSU
                          from t in tempSU.DefaultIfEmpty()
                          select new SceneItemDto
                {
                    Id = item.Id,
                    SceneID = item.SceneID,
                    PictureGuid = item.PictureGuid,
                    Count = item.Count,
                    Status = item.Status,
                    UserID = item.UserID,
                    CreateTime = item.CreateTime,
                    UpdateTime = item.UpdateTime,
                    Address = item.Address,
                    GPS = item.GPS,
                    Description = item.Description,
                    Images = item.Images,
                    Examines = item.Examines,
                    Comments = item.Comments,
                    Relation = item.Relation,
                    IsExamine = item.IsExamine,
                    Type = item.Type,
                    UserName = t == null ? string.Empty : t.name,
                    UserPicture = t == null ? string.Empty : UriExtensions.GetFullUrl(t.picture)
                })
                         .ToList();
                foreach (var r in re)
                {
                    r.Images = MakeUrlWithPictureName(r.Images);
                }
                return(re);
            }
        }
        public SceneItem Add(SceneItem sceneItem)
        {
            try
            {
                if (null == sceneItem)
                {
                    throw new KnownException("现场数据为空,不能添加!");
                }
                if (null == sceneItem.Relation)
                {
                    sceneItem.Relation = "";
                }
                if (string.IsNullOrEmpty(sceneItem.SceneID) && string.IsNullOrEmpty(sceneItem.UserID) &&
                    string.IsNullOrEmpty(sceneItem.GPS) && (string.IsNullOrEmpty(sceneItem.Address)))
                {
                    throw new KnownException("必要的现场数据缺失,无法保存!");
                }
                using (var db = new BCEnterpriseContext())
                {
                    if (db.Scenes.Any(o => o.ParentSceneID == sceneItem.SceneID &&
                                      o.Status == (byte)ML.BC.EnterpriseData.Common.Status.End))
                    {
                        throw new KnownException("当前现场不是叶子现场,或者该现场已完工,不能添加现场数据!");
                    }
                }
                sceneItem.UpdateTime = DBTimeHelper.DBNowTime();
                var mgdb = new MongoDbProvider <SceneItem>();
                if (sceneItem.Count == 0)
                {
                    var si = mgdb.Insert(sceneItem);
                    if (!string.IsNullOrEmpty(sceneItem.Relation))
                    {
                        var item = mgdb.GetById(sceneItem.Relation);
                        if (null != item)
                        {
                            item.IsExamine  = true;
                            item.UpdateTime = DBTimeHelper.DBNowTime();
                            mgdb.Update(item);
                        }
                    }
                    return(SetSceneHasData(si.SceneID) ? si : null);
                }

                var sessionDatas = HttpContext.Current.Session[sceneItem.PictureGuid.ToString()] as List <ImageInfo>;
                sessionDatas = sessionDatas ?? new List <ImageInfo>();

                var listUrl = new List <ImageUrl>();
                if (sceneItem.Count != sessionDatas.Count)
                {
                    throw new KnownException("图片还未上传完成!");
                }
                foreach (var info in sessionDatas)
                {
                    sceneItem.TotalOrgImageBytes += info.OrgImageBytes;
                    sceneItem.TotalThuImageBytes += info.ThuImageBytes;
                    listUrl.Add(new ImageUrl()
                    {
                        OriginalPicture = info.OriginalPicture, ThumbnailPicture = info.ThumbnailPicture
                    });
                }
                sceneItem.Images = listUrl;

                var re = mgdb.Insert(sceneItem);
                if (null == re)
                {
                    throw new KnownException("保存失败!");
                }
                if (!SetSceneHasData(re.SceneID))
                {
                    return(null);
                }
                HttpContext.Current.Session[sceneItem.PictureGuid.ToString()] = null;
                re.Images = MakeUrlWithPictureName(re.Images);
                if (!string.IsNullOrEmpty(sceneItem.Relation))
                {
                    var item = mgdb.GetById(sceneItem.Relation);
                    if (null != item)
                    {
                        item.IsExamine  = true;
                        item.UpdateTime = DBTimeHelper.DBNowTime();
                        mgdb.Update(item);
                    }
                }
                return(re);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public List <SceneItemDto> GetSceneItemForSync(string userId, string device)
        {
            lock (GETSCENEITEMFORSYNCLOCK)
            {
                using (var db = new BCEnterpriseContext())
                {
                    List <string> sceneIDs = new List <string>();

                    #region get sceneIDs

                    var userDepartmentID = db.FrontUsers.Where(o => o.UserID == userId).Select(o => o.DepartmentID).FirstOrDefault().ToString();
                    if (!string.IsNullOrEmpty(userDepartmentID))
                    {
                        sceneIDs = (from scene in db.Scenes
                                    join project in db.Projects on scene.ProjectID equals project.ProjectID into tPrj
                                    from prj in tPrj.DefaultIfEmpty()
                                    where prj.Departments.Contains(userDepartmentID)
                                    select scene.SceneID
                                    ).Distinct()
                                   .ToList();
                    }

                    if (!(db.SyncStates.Any(n => n.UserID == userId && n.DeviceID == device && n.ActionType == (int)ML.BC.Infrastructure.MsmqHelper.TypeEnum.SceneData)))
                    {
                        var syncSceneData = new SyncState()
                        {
                            UserID     = userId,
                            DeviceID   = device,
                            ActionType = (int)TypeEnum.SceneData,
                            SyncTime   = DBTimeHelper.DBNowTime(db)
                        };
                        db.SyncStates.Add(syncSceneData);
                        if (0 < db.SaveChanges())
                        {
                            return(new List <SceneItemDto>());
                        }
                        else
                        {
                            var logger = log4net.LogManager.GetLogger(typeof(SceneItemManagementService));
                            logger.Error("第一次写入同步现场数据的状态失败!");
                            return(new List <SceneItemDto>());
                        }
                    }

                    var lastSyncTime = (db.SyncStates.FirstOrDefault(
                                            n =>
                                            n.UserID == userId && n.DeviceID == device &&
                                            n.ActionType == (int)ML.BC.Infrastructure.MsmqHelper.TypeEnum.SceneData)
                                        ?? new SyncState {
                        SyncTime = DateTime.MinValue
                    }).SyncTime;

                    #endregion

                    var mgdb       = new MongoDbProvider <SceneItem>();
                    var sceneItems = mgdb.GetAll(n => (sceneIDs.Contains(n.SceneID)) && (n.UpdateTime >= lastSyncTime));

                    var userIds     = sceneItems.Select(n => n.UserID).ToList();
                    var relateUsers = db.FrontUsers.Where(obj => userIds.Contains(obj.UserID)).Select(o => new
                    {
                        uid     = o.UserID,
                        name    = o.Name,
                        picture = o.Picture
                    }).ToList();

                    var resultList = (from item in sceneItems
                                      join r in relateUsers on item.UserID equals r.uid into tempSU
                                      from t in tempSU.DefaultIfEmpty()
                                      select new SceneItemDto
                    {
                        Id = item.Id,
                        SceneID = item.SceneID,
                        PictureGuid = item.PictureGuid,
                        Count = item.Count,
                        Status = item.Status,
                        UserID = item.UserID,
                        CreateTime = item.CreateTime,
                        UpdateTime = item.UpdateTime,
                        Address = item.Address,
                        GPS = item.GPS,
                        Description = item.Description,
                        Images = item.Images,
                        Relation = item.Relation,
                        IsExamine = item.IsExamine,
                        Comments = item.Comments,
                        Type = item.Type,
                        UserName = t == null ? string.Empty : t.name,
                        UserPicture = t == null ? string.Empty : UriExtensions.GetFullUrl(t.picture)
                    })
                                     .OrderByDescending(o => o.UpdateTime)
                                     .ToList();
                    foreach (var r in resultList)
                    {
                        r.Images = MakeUrlWithPictureName(r.Images);
                    }
                    return(resultList);
                }
            }
        }