Example #1
0
        private DomainObjectData loadFolderAndIncident(DomainObjectDataSet dataSet, GetMailMsgInfoRequest request, IXExecutionContext context)
        {
            DomainObjectData xobjFolder;

            if (request.ObjectType == "Folder")
            {
                xobjFolder = dataSet.GetLoadedStub("Folder", request.ObjectID);
                dataSet.LoadProperty(context.Connection, xobjFolder, "Name");
            }
            else
            {
                XDbCommand cmd = context.Connection.CreateCommand(
                    @"SELECT f.ObjectID as FolderID, f.Name as FolderName, i.Name as IncidentName, i.Number as IncidentNumber
					FROM Incident i JOIN Folder f ON i.Folder=f.ObjectID 
					WHERE i.ObjectID = @IncidentID"                    );
                cmd.Parameters.Add("IncidentID", DbType.Guid, ParameterDirection.Input, false, request.ObjectID);
                DomainObjectData xobjIncident = dataSet.GetLoadedStub("Incident", request.ObjectID);
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    if (!reader.Read())
                    {
                        throw new XObjectNotFoundException("Incident", request.ObjectID);
                    }
                    xobjFolder = dataSet.GetLoadedStub("Folder", reader.GetGuid(reader.GetOrdinal("FolderID")));
                    xobjFolder.SetLoadedPropValue("Name", reader.GetString(reader.GetOrdinal("FolderName")));
                    xobjIncident.SetLoadedPropValue("Name", reader.GetString(reader.GetOrdinal("IncidentName")));
                    xobjIncident.SetLoadedPropValue("Number", reader.GetInt32(reader.GetOrdinal("IncidentNumber")));
                    xobjIncident.SetLoadedPropValue("Folder", xobjFolder.ObjectID);
                }
            }
            return(xobjFolder);
        }
Example #2
0
        public void ExecuteTrigger(DomainObjectDataSet dataSet, DomainObjectData xobj, IXExecutionContext context)
        {
            XTrigger     trigger = (XTrigger)m_factory.GetInstance();
            XTriggerArgs args    = new XTriggerArgs(m_action, m_fireTime, m_fireType, dataSet, xobj);

            trigger.Execute(args, context);
        }
Example #3
0
        /// <summary>
        /// Сохранение данных множества объектов.
        /// </summary>
        /// <remarks>
        /// Управление транзакцией внешнее.
        /// </remarks>
        /// <param name="context"></param>
        /// <param name="dataSet"></param>
        /// <param name="transactionID"></param>
        public static void Save(IXExecutionContext context, DomainObjectDataSet dataSet, Guid transactionID)
        {
            // #1: Вызов триггеров Before
            XTriggersController.Instance.FireTriggers(dataSet, XTriggerFireTimes.Before, context);

            // #2: Сбросим закэшированные данные объектов
            IEnumerator enumerator = dataSet.GetModifiedObjectsEnumerator(false);

            while (enumerator.MoveNext())
            {
                DomainObjectData xobj = (DomainObjectData)enumerator.Current;
                // Примечание: для новых объектов сбрасывать кэш бессмысленно - их там нет
                if (!xobj.IsNew)
                {
                    DomainObjectRegistry.ResetObject(xobj);
                }
            }

            // #3: Запись данных
            XDatagramProcessorEx dg_proc   = XDatagramProcessorMsSqlEx.Instance;
            XDatagramBuilder     dgBuilder = dg_proc.GetDatagramBuilder();
            XDatagram            dg        = dgBuilder.GetDatagram(dataSet);

            dg_proc.Save(context.Connection, dg);

            // #4: Сохранение chunked-данных
            saveChunkedData(transactionID, dg, context.Connection);

            // #5: Сигнализируем Securitymanager, что обновились данные (для очистки кэшей)
            XSecurityManager.Instance.TrackModifiedObjects(dataSet);

            // #6: Вызов триггеров After
            XTriggersController.Instance.FireTriggers(dataSet, XTriggerFireTimes.After, context);
        }
Example #4
0
 private void fireTriggersForObject(DomainObjectData xobj, XTriggerFireTimes fireTime, IXExecutionContext context)
 {
     if (m_triggersForObjects.Length > 0)
     {
         foreach (XTriggerDescription trigger in m_triggersForObjects)
         {
             if (isTriggerMatchForObject(trigger, xobj, fireTime))
             {
                 trigger.ExecuteTrigger(xobj.Context, xobj, context);
             }
         }
     }
     if (m_triggersForGroups.Length > 0)
     {
         ArrayList aObjectTypes = new ArrayList();
         foreach (XTriggerDescription trigger in m_triggersForGroups)
         {
             if (trigger.ObjectType == xobj.ObjectType && aObjectTypes.IndexOf(xobj.ObjectType) == -1)
             {
                 aObjectTypes.Add(xobj.ObjectType);
                 trigger.ExecuteTrigger(xobj.Context, xobj, context);
             }
         }
     }
 }
        public XmlElement SerializeObject(DomainObjectData xobj)
        {
            XmlDocument xmlDoc    = new XmlDocument();
            XmlElement  xmlObject = SerializeObject(xobj, xmlDoc);

            return((XmlElement )xmlDoc.AppendChild(xmlObject));
        }
        public override void Execute(XTriggerArgs args, IXExecutionContext context)
        {
            DomainObjectData xobj = args.TriggeredObject;
            // если изменилось значение признака "Архивное", проверим отсутствие у подразделения работающих сотрудников или не архивных департаментов.
            bool bUpdateIsArchive = xobj.HasUpdatedProp("IsArchive");

            if (bUpdateIsArchive)
            {
                bool newValue = (bool)xobj.GetUpdatedPropValue("IsArchive");
                if (!xobj.IsNew && newValue)
                {
                    //	1. Проверим, что все сотрудники (во всех вложенных департаментах) уволены
                    XDbCommand cmd = context.Connection.CreateCommand(@"
							SELECT 1 
							FROM dbo.Department d_s WITH(NOLOCK)
								JOIN dbo.Department d WITH(NOLOCK) ON d.LIndex >= d_s.LIndex AND d.RIndex <= d_s.RIndex AND d.Organization = d_s.Organization
									JOIN Employee e WITH(NOLOCK) ON (d.ObjectID = e.Department) and (e.WorkEndDate is null)
							WHERE d_s.ObjectID = @ObjectID
							"                            );
                    cmd.Parameters.Add("ObjectID", DbType.Guid, ParameterDirection.Input, false, xobj.ObjectID);
                    if (cmd.ExecuteScalar() != null)
                    {
                        throw new XBusinessLogicException("Департамент не может быть переведен с состояние \"Архивное\", так как содержит работающих сотрудников");
                    }
                }
                // добавим в датаграмму подчиненные департаменты
                UpdateChildDepartments(context.Connection, args.DataSet, xobj.ObjectID, newValue);
            }
        }
Example #7
0
        /// <summary>
        /// Проверка на сохранение объекта в БД, поступившего от клиента, в рамках датаграммы
        /// </summary>
        /// <param name="xuser">Пользователь, сохраняющий объект</param>
        /// <param name="ex">Описание запрета</param>
        public bool HasSaveObjectPrivilege(XUser xuser, DomainObjectData xobj, out Exception ex)
        {
            ex = null;
            ITUser user = (ITUser)xuser;

            using (XStorageConnection con = getConnection())
            {
                ObjectRightsCheckerBase checker = (ObjectRightsCheckerBase)m_ObjectRightCheckers[xobj.ObjectType];
                bool   bAllow;
                string sErrorDescription;
                if (checker != null)
                {
                    bAllow = checker.HasSaveObjectRight(user, xobj, con, out sErrorDescription);
                }
                else
                {
                    bAllow = m_coveringPrivilegesManager.HasSaveObjectRight(user, xobj, con, out sErrorDescription);
                }
                if (sErrorDescription != null && sErrorDescription.Length > 0)
                {
                    ex = new XSecurityException(sErrorDescription);
                }
                return(bAllow);
            }
        }
        public XmlElement SerializeObject(DomainObjectData xobj, string[] aPreloadProperties)
        {
            XmlDocument xmlDoc    = new XmlDocument();
            XmlElement  xmlObject = SerializeObject(xobj, xmlDoc, aPreloadProperties);

            return((XmlElement )xmlDoc.AppendChild(xmlObject));
        }
Example #9
0
        /// <summary>
        /// Выполнение команды - типизированный вариант
        /// </summary>
        /// <param name="request">Запрос команды, должен иметь тип XGetPropertyRequest</param>
        /// <param name="context">Контекст выполнения команды</param>
        /// <returns>XGetPropertyResponse</returns>
        public new XGetPropertyResponse Execute(XGetPropertyRequest request, IXExecutionContext context)
        {
            DomainObjectDataSet dataSet = new DomainObjectDataSet(context.Connection.MetadataManager.XModel);
            // создадим болванку объекта
            DomainObjectData xobj = dataSet.GetLoadedStub(request.TypeName, request.ObjectID);

            // загрузим свойства
            dataSet.LoadProperty(context.Connection, xobj, request.PropName);
            // создадим форматировщик
            DomainObjectDataXmlFormatter formatter = new DomainObjectDataXmlFormatter(context.Connection.MetadataManager);
            // и сериализуем свойство в XML
            XmlElement xmlProperty = formatter.SerializeProperty(xobj, request.PropName);

            // по всем объектам в свойстве (LoadProperty вызывается не только для объектных свойств - еще для bin и text)
            // обработаем объект и все вложенные объекты в прогруженных свойства, расставим атрибуты ограничения доступа
            foreach (XmlElement xmlObject in xmlProperty.SelectNodes("*[*]"))
            {
                DomainObjectData xobjValue = xobj.Context.Find(xmlObject.LocalName, new Guid(xmlObject.GetAttribute("oid")));
                if (xobjValue == null)
                {
                    throw new ApplicationException("Не удалось найти в контексте типизированного объекта DomainObjectData для xml-объекта-значения свойства " + xmlProperty.LocalName + " объекта " + xmlObject.LocalName);
                }
                XmlObjectRightsProcessor.ProcessObject(xobjValue, xmlObject);
            }
            XGetPropertyResponse response = new XGetPropertyResponse(xmlProperty);

            return(response);
        }
Example #10
0
        /// <summary>
        /// »змен¤ет помеченные свойства объекта, добав뤤 к ним подпись
        /// </summary>
        /// <param name="xobj">текущий объект</param>
        /// <param name="signature">подпись</param>
        private void modifyObjectProps(DomainObjectData xobj, string signature)
        {
            // пройдемс¤ по всем свойствам объекта
            foreach (string sPropName in xobj.UpdatedPropNames)
            {
                // получим информацию о свойстве по его названию
                XPropInfoBase propInfo = xobj.TypeInfo.GetProp(sPropName);

                // если подпись дл¤ данного свойства не нужна, пропускаем его
                if (hasPropSignature(propInfo))
                {
                    object vPropValue = xobj.GetUpdatedPropValue(sPropName);
                    if (vPropValue != null && vPropValue != DBNull.Value)
                    {
                        string sText = null;
                        if (propInfo.VarType == XPropType.vt_string || propInfo.VarType == XPropType.vt_text)
                        {
                            sText = (string)vPropValue;
                        }
                        else
                        {
                            throw new ApplicationException("ћеханизм автоподписи применим только к строковым и текстовым пол¤м");
                        }

                        if (sText != null)
                        {
                            xobj.SetUpdatedPropValue(sPropName, addSignature(sText, signature));
                        }
                    }
                }
            }
        }
Example #11
0
        public void DemandSaveObjectPrivilege(DomainObjectData xobj)
        {
            XUser user = GetCurrentUser();

            if (user.IsUnrestricted)
            {
                return;
            }
            Exception exOut;
            bool      bAllow;

            try
            {
                bAllow = m_SecurityProvider.HasSaveObjectPrivilege(user, xobj, out exOut);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Ошибка во время проверки прав на сохранение объекта: " + xobj.ObjectType + " [" + xobj.ObjectID + "]:\n" + ex.Message, ex);
            }
            if (!bAllow)
            {
                if (exOut != null)
                {
                    throw new XSecurityException(exOut.Message);
                }
                else
                {
                    throw new XSecurityException("Недостаточно прав");
                }
            }
        }
Example #12
0
        public XObjectRights GetObjectRights(DomainObjectData xobj)
        {
            XUser user = GetCurrentUser();

            if (user == null || xobj == null)
            {
                throw new ApplicationException("Ошибка в процессе проверки прав:\n");
            }
            if (user.IsUnrestricted)
            {
                return(XObjectRights.FullRights);
            }
            try
            {
                XObjectRights rights = m_SecurityProvider.GetObjectRights(user, xobj);
                if (rights == null)
                {
                    throw new XSecurityProviderErrorImplementationException("Метод GetObjectRights провайдера безопасности вернул null для объекта: " + xobj.ToString());
                }
                return(rights);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Ошибка в процессе проверки прав:\n" + ex.Message, ex);
            }
        }
Example #13
0
        public GetObjectsRightsExResponse Execute(CheckDatagramRequest request, IXExecutionContext context)
        {
            XObjectRightsDescr[] objectPermissionCheckList = new XObjectRightsDescr[request.ObjectsToCheck.Length];

            DomainObjectDataXmlFormatter formatter = new DomainObjectDataXmlFormatter(context.Connection.MetadataManager);
            DomainObjectDataSet          dataSet   = formatter.DeserializeForSave(request.XmlDatagram);

            int nIndex = -1;

            foreach (XObjectIdentity obj_id in request.ObjectsToCheck)
            {
                DomainObjectData xobj = dataSet.Find(obj_id.ObjectType, obj_id.ObjectID);
                //if (xobj.IsNew && xobj == null)
                //	throw new ArgumentException("Датаграмма не содержит нового объекта, для которого требуется вычислить права: " +obj_id.ObjectType + "[" + obj_id.ObjectType + "]");
                if (xobj == null)
                {
                    xobj = dataSet.Load(context.Connection, obj_id.ObjectType, obj_id.ObjectID);
                }
                if (xobj.IsNew)
                {
                    objectPermissionCheckList[++nIndex] = createObjectRightsDescr(XSecurityManager.Instance.GetRightsOnNewObject(xobj));
                }
                else
                {
                    objectPermissionCheckList[++nIndex] = createObjectRightsDescr(XSecurityManager.Instance.GetObjectRights(xobj));
                }
            }

            // Формируем результат операции
            return(new GetObjectsRightsExResponse(objectPermissionCheckList));
        }
Example #14
0
 public XTriggerArgs(XTriggerActions action, XTriggerFireTimes fireTimes, XTriggerFireTypes eventType, DomainObjectDataSet dataSet, DomainObjectData xobj)
 {
     m_action   = action;
     m_fireTime = fireTimes;
     m_fireType = eventType;
     m_dataSet  = dataSet;
     m_xobj     = xobj;
 }
Example #15
0
        /// <summary>
        /// Операция получения XML-документа с данными набора заданных ds-объектов
        /// ТИПИЗИРОВАННАЯ ВЕРСИЯ МЕТОДА
        /// АВТОМАТИЧЕСКИ ВЫЗЫВАЕТСЯ ЯДРОМ
        /// </summary>
        /// <param name="request">Запрос на вполнение операции</param>
        /// <param name="context">Контекст выоленения операции</param>
        /// <returns>Результат выполенения операции</returns>
        public XGetObjectsResponse Execute(XGetObjectsRequest request, IXExecutionContext context)
        {
            // Проверка праметров - массив с перечнем идентификационных данных
            // объектов должен быть задан, и не должен быть пустым:
            if (null == request.List)
            {
                throw new ArgumentNullException("request.List");
            }
            if (0 == request.List.Length)
            {
                throw new ArgumentException("request.List");
            }

            XmlDocument                  xmlDoc         = new XmlDocument();
            XmlElement                   xmlRootElement = xmlDoc.CreateElement("root");
            DomainObjectDataSet          dataSet        = new DomainObjectDataSet(context.Connection.MetadataManager.XModel);
            DomainObjectDataXmlFormatter formatter      = new DomainObjectDataXmlFormatter(context.Connection.MetadataManager);
            DomainObjectData             xobj;

            foreach (XObjectIdentity i in request.List)
            {
                if (i.ObjectID == Guid.Empty)
                {
                    xmlRootElement.AppendChild(context.Connection.Create(i.ObjectType, xmlDoc));
                }
                else
                {
                    try
                    {
                        xobj = dataSet.Load(context.Connection, i.ObjectType, i.ObjectID);
                        xmlRootElement.AppendChild(formatter.SerializeObject(xobj, xmlDoc));
                    }
                    catch (XObjectNotFoundException)
                    {
                        XmlElement xmlStub = (XmlElement)xmlRootElement.AppendChild(
                            context.Connection.CreateStub(i.ObjectType, i.ObjectID, xmlDoc));
                        xmlStub.SetAttribute("not-found", "1");
                    }
                }
            }
            // по всем запрошенным объектам
            foreach (XmlElement xmlObject in xmlRootElement.SelectNodes("*[*]"))
            {
                // обработаем объект и все вложенные объекты в прогруженных свойства, расставим атрибуты ограничения доступа
                if (!xmlObject.HasAttribute("new"))
                {
                    DomainObjectData xobjValue = dataSet.Find(xmlObject.LocalName, new Guid(xmlObject.GetAttribute("oid")));
                    if (xobjValue == null)
                    {
                        throw new ApplicationException("Не удалось найти в контексте типизированного объекта DomainObjectData для xml объекта: " + xmlObject.OuterXml);
                    }

                    XmlObjectRightsProcessor.ProcessObject(xobjValue, xmlObject);
                }
            }

            return(new XGetObjectsResponse(xmlRootElement));
        }
Example #16
0
        public XStorageObjectBase createXStorageObject(DomainObjectData obj)
        {
            XStorageObjectBase xobj;
            object             vPropValue;

            if (obj.ToDelete)
            {
                xobj = new XStorageObjectToDelete(obj.TypeInfo, obj.ObjectID, obj.TS, true);
            }
            else
            {
                xobj = new XStorageObjectToSave(obj.TypeInfo, obj.ObjectID, obj.TS, obj.IsNew);
                ((XStorageObjectToSave)xobj).PropertiesWithChunkedData = obj.PropertiesWithChunkedData;
            }
            bool bNeedTrackUniqueIndexParticipation = xobj.TypeInfo.HasUniqueIndexes && xobj.TypeInfo.DeferrableIndexes && !obj.ToDelete;

            foreach (string sPropName in obj.UpdatedPropNames)
            {
                vPropValue = obj.GetUpdatedPropValue(sPropName);
                XPropInfoBase propInfo = obj.TypeInfo.GetProp(sPropName);
                if (propInfo is XPropInfoNumeric)
                {
                    if (((XPropInfoSimpleEnumerable)propInfo).IsEnum)
                    {
                        // в качестве значения свойства может быть поcле перечисления, надо привести его в элементарному типу
                        if (vPropValue.GetType().IsEnum)
                        {
                            if (propInfo.VarType == XPropType.vt_i4)
                            {
                                vPropValue = (Int32)vPropValue;
                            }
                            else if (propInfo.VarType == XPropType.vt_i2)
                            {
                                vPropValue = (Int16)vPropValue;
                            }
                            else                             // if (propInfo.VarType == XPropType.vt_ui1)
                            {
                                vPropValue = (byte)vPropValue;
                            }
                        }
                    }
                }
                if (vPropValue != null)
                {
                    xobj.Props[sPropName] = vPropValue;
                }
                // если свойство участвует в уникальном индексе, запомним это
                if (bNeedTrackUniqueIndexParticipation)
                {
                    if (xobj.TypeInfo.IsPropIncludedIntoUniqueIndex(sPropName))
                    {
                        ((XStorageObjectToSave)xobj).ParticipateInUniqueIndex = true;
                    }
                }
            }
            return(xobj);
        }
        /// <summary>
        /// Обнуление нормы в случае увольнения сотрудника, либо временной нетрудоспособности.
        /// </summary>
        private void setEmployeeRate(XTriggerArgs args, string sComment, DateTime dtDate)
        {
            DomainObjectData xobjEmployeeRate = args.DataSet.CreateNew("EmployeeRate", true);

            xobjEmployeeRate.SetUpdatedPropValue("Employee", args.TriggeredObject.ObjectID);
            xobjEmployeeRate.SetUpdatedPropValue("Rate", 0);
            xobjEmployeeRate.SetUpdatedPropValue("Date", dtDate);
            xobjEmployeeRate.SetUpdatedPropValue("Comment", sComment);
        }
        private void setEmployeeHistoryEvent(XTriggerArgs args, EmployeeHistoryEvents enumEvent)
        {
            DomainObjectData xobjEmployeeHistory = args.DataSet.CreateNew("EmployeeHistory", true);
            ITUser           user = (ITUser)XSecurityManager.Instance.GetCurrentUser();

            xobjEmployeeHistory.SetUpdatedPropValue("Employee", args.TriggeredObject.ObjectID);
            xobjEmployeeHistory.SetUpdatedPropValue("Event", enumEvent);
            xobjEmployeeHistory.SetUpdatedPropValue("SystemUser", user.SystemUserID);
            xobjEmployeeHistory.SetUpdatedPropValue("EventDate", DateTime.Now);
        }
        public override void Execute(XTriggerArgs args, IXExecutionContext context)
        {
            DomainObjectData xobjEventSubscription = args.TriggeredObject;

            // для нового объекта если не задана группа рассылки проставим текущего пользователя
            if (args.Action == XTriggerActions.Insert && !(xobjEventSubscription.GetUpdatedPropValue("Group") is Guid))
            {
                xobjEventSubscription.SetUpdatedPropValue("User", ((ITUser)XSecurityManager.Instance.GetCurrentUser()).EmployeeID);
            }
        }
        public XmlElement SerializeObject(DomainObjectData xobj, XmlDocument xmlDoc, string[] aPreloadProperties)
        {
            PreloadsNavigator nav = null;

            if (aPreloadProperties != null)
            {
                nav = new PreloadsNavigator(aPreloadProperties);
            }
            return(serializeObject(xobj, xmlDoc, nav));
        }
Example #21
0
        public override void Execute(XTriggerArgs args, IXExecutionContext context)
        {
            DomainObjectData xobjTask = args.TriggeredObject;

            // для нового объекта, если не задан планировщик, или
            // если изменилось запланированное время при обновлении установим планировщиком задания текущего сотрудника
            if (xobjTask.IsNew && xobjTask.GetUpdatedPropValue("Planner") == null || !xobjTask.IsNew && xobjTask.HasUpdatedProp("PlannedTime"))
            {
                xobjTask.SetUpdatedPropValue("Planner", ((ITUser)XSecurityManager.Instance.GetCurrentUser()).EmployeeID);
            }
        }
Example #22
0
        public override void Execute(XTriggerArgs args, IXExecutionContext context)
        {
            DomainObjectData xobjHistory = getFolderHistoryObject(args.DataSet, args.TriggeredObject);

            xobjHistory.SetUpdatedPropValue("Event", FolderHistoryEvents.Creating);
            // если не задан Инициатор, то установим текущего сотрудника
            if (!args.TriggeredObject.HasUpdatedProp("Initiator") || args.TriggeredObject.GetUpdatedPropValue("Initiator") == DBNull.Value)
            {
                args.TriggeredObject.SetUpdatedPropValue("Initiator", ((ITUser)XSecurityManager.Instance.GetCurrentUser()).EmployeeID);
            }
        }
Example #23
0
        protected DomainObjectData getFolderHistoryObject(DomainObjectDataSet dataSet, DomainObjectData xobjFolder)
        {
            DomainObjectData xobjHistory = dataSet.CreateNew("FolderHistory", true);

            xobjHistory.SetUpdatedPropValue("Folder", xobjFolder.ObjectID);
            ITUser user = (ITUser)XSecurityManager.Instance.GetCurrentUser();

            xobjHistory.SetUpdatedPropValue("SystemUser", user.SystemUserID);
            xobjHistory.SetUpdatedPropValue("EventDate", DateTime.Now);
            return(xobjHistory);
        }
Example #24
0
        public override void Execute(XTriggerArgs args, IXExecutionContext context)
        {
            DomainObjectData xobjEmployeeHistory = args.DataSet.CreateNew("EmployeeHistory", true);
            ITUser           user          = (ITUser)XSecurityManager.Instance.GetCurrentUser();
            Guid             uidEmployeeID = getEmployeeID(context.Connection, args.TriggeredObject.ObjectID);

            xobjEmployeeHistory.SetUpdatedPropValue("Employee", uidEmployeeID);
            xobjEmployeeHistory.SetUpdatedPropValue("Event", EmployeeHistoryEvents.ChangeSecurity);
            xobjEmployeeHistory.SetUpdatedPropValue("SystemUser", user.SystemUserID);
            xobjEmployeeHistory.SetUpdatedPropValue("EventDate", DateTime.Now);
        }
        public XmlElement SerializeProperty(DomainObjectData xobj, string sPropName)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement  xmlProp;                                                        // Узел со значением свойства

            xmlDoc.AppendChild(xmlProp = xmlDoc.CreateElement(sPropName));              // Создаем корневой элемент
            // Указываем пространство имен urn:schemas-microsoft-com:datatypes
            xmlDoc.DocumentElement.SetAttribute("xmlns:dt", "urn:schemas-microsoft-com:datatypes");

            serializePropertyInternal(xobj, xmlProp, new PreloadsNavigator(new string[] { sPropName }));
            return(xmlProp);
        }
Example #26
0
        public override void Execute(XTriggerArgs args, IXExecutionContext context)
        {
            IEnumerator enumerator = args.DataSet.GetModifiedObjectsEnumerator(true);

            while (enumerator.MoveNext())
            {
                DomainObjectData xobj = (DomainObjectData)enumerator.Current;
                if (xobj.IsNew)
                {
                    //TODO Метод ChangeObjectIdentifier(изменение идентификатора нового объекта) был убран из solution
                }
            }
        }
Example #27
0
        public override XTreeMenuInfo GetMenuForEmptyTree(XGetTreeMenuRequest request, IXExecutionContext context, XTreePageInfoStd treePage)
        {
            XTreeMenuInfo       menu         = new XTreeMenuInfo("", true);
            DomainObjectDataSet dataSet      = new DomainObjectDataSet(context.Connection.MetadataManager.XModel);
            DomainObjectData    xobj         = dataSet.CreateNew("IncidentType", true);
            XNewObjectRights    create_right = XSecurityManager.Instance.GetRightsOnNewObject(xobj);

            if (create_right.AllowCreate)
            {
                XMenuActionItem item = menu.Items.AddActionItem("—оздать тип инцидента", StdActions.DoCreate);
                item.Parameters.Add("ObjectType", "IncidentType");
            }
            return(menu);
        }
Example #28
0
        /// <summary>
        /// Запрос разрешенных действий при создании объекта
        /// </summary>
        /// <param name="xuser">Пользователь</param>
        /// <param name="xobj"></param>
        /// <returns></returns>
        public XNewObjectRights GetRightsOnNewObject(XUser xuser, DomainObjectData xobj)
        {
            ITUser user = (ITUser)xuser;

            using (XStorageConnection con = getConnection())
            {
                ObjectRightsCheckerBase checker = (ObjectRightsCheckerBase)m_ObjectRightCheckers[xobj.ObjectType];
                if (checker != null)
                {
                    return(checker.GetRightsOnNewObject(user, xobj, con));
                }
                return(m_coveringPrivilegesManager.GetRightsOnNewObject(user, xobj, con));
            }
        }
        private XTreeMenuInfo getMenuForEmployee(Guid ObjectID, DomainObjectDataSet dataSet, IXExecutionContext context)
        {
            XTreeMenuInfo menu = new XTreeMenuInfo("@@Title", true);

            menu.CacheMode = XTreeMenuCacheMode.NoCache;
            menu.ExecutionHandlers.Add(new XUserCodeWeb("CompanyTree_Menu_ExecutionHandler"));

            // просмотр
            // Раскоментировать после удаления ссылок на НСИ
            //menu.Items.AddActionItem("Просмотр", StdActions.DoView).Parameters.Add("ReportURL", StdMenuUtils.GetEmployeeReportURL(context.Config,  ObjectID));

            DomainObjectData xobj   = dataSet.GetLoadedStub("Employee", ObjectID);
            XObjectRights    rights = XSecurityManager.Instance.GetObjectRights(xobj);

            // Редактировать
            if (rights.AllowParticalOrFullChange)
            {
                menu.Items.AddActionItem("Редактировать", StdActions.DoEdit).Default = true;
            }
            // Удалить
            if (rights.AllowDelete)
            {
                menu.Items.AddActionItem("Удалить", StdActions.DoDelete);
            }

            // Секция "Отчеты"
            //XMenuActionItem item;
            //XMenuSection sec = menu.Items.AddSection("Отчеты");
            //item = sec.Items.AddActionItem("Сальдо ДС", "DoView");
            //item.Parameters.Add("ReportURL", "x-get-report.aspx?name=r-EmployeeSaldoDS.xml&amp;EmployeeID=@@ObjectID");

            /*
             * item = sec.Items.AddActionItem("Инциденты и списания времени сотрудника", "DoRunReport");
             *          item.Parameters.Add("ReportName", "ReportEmployeeExpensesList");
             *          item.Parameters.Add("UrlParams", ".Employee=" + ObjectID);
             *          item = sec.Items.AddActionItem("Баланс списаний сотрудника", "DoRunReport");
             *          item.Parameters.Add("ReportName", "EmployeeExpensesBalance");
             *          item.Parameters.Add("UrlParams", ".Employee=" + ObjectID);
             * item = sec.Items.AddActionItem("Плановая занятость сотрудников", "DoRunReport");
             * item.Parameters.Add("ReportName", "Employment");
             * item.Parameters.Add("UrlParams", ".Employees=" + ObjectID + "&.Organizations=&.Departments=");
             */

            // Секция "Информация"
            XMenuSection sec = menu.Items.AddSection("Информация");

            fillEmployeeInfoSection(sec, ObjectID, context.Connection);
            return(menu);
        }
Example #30
0
        public XResponse Execute(MoveObjectsRequest request, IXExecutionContext context)
        {
            DomainObjectDataSet dataSet = new DomainObjectDataSet(context.Connection.MetadataManager.XModel);

            foreach (Guid oid in request.SelectedObjectsID)
            {
                DomainObjectData xobj = dataSet.CreateStubLoaded(request.SelectedObjectType, oid, -1);
                xobj.SetUpdatedPropValue(request.ParentPropName, request.NewParent);
                // для объекта проверим права
                XSecurityManager.Instance.DemandSaveObjectPrivilege(xobj);
            }
            XStorageGateway.Save(context, dataSet, Guid.NewGuid());

            return(new XResponse());
        }