/// <summary>Return a response for the message</summary>
        /// <param name="msg">The message link to this response</param>
        /// <returns>The response to the message</returns>
        public ISpEventMessage Response(ISpEventMessage msg)
        {
            DemoMsgId   id    = SpConverter.IntToEnum <DemoMsgId>(msg.EventId);
            DemoMsgType _type = SpConverter.IntToEnum <DemoMsgType>(msg.TypeId);

            // Only one type of message for now.
            // Responses also in the same enum as messages so have to handle
            switch (_type)
            {
            case DemoMsgType.SimpleMsg:
                // TODO Hmm should this be a response instead of a message?
                return(new DemoMsgBase(_type, id, msg.Priority)
                {
                    ReturnCode = msg.ReturnCode,
                    StringPayload = msg.StringPayload,
                    ReturnStatus = msg.ReturnStatus,
                    // You can add any other info from derived message
                });

            case DemoMsgType.SimpleResponse:
                throw new Exception(string.Format("Response '{0}' is not a valid message", _type));

            default:
                throw new Exception(string.Format("Unhandled message '{0}'", _type));
            }
        }
Example #2
0
 /// <summary>Constructor</summary>
 /// <param name="msg">The message linked to this response</param>
 /// <param name="status">The status string of the response</param>
 public ResponseOk(ISpEventMessage msg, string status) :
     base(DemoMsgType.SimpleResponse, DemoMsgId.Tick, SpEventPriority.Normal)
 {
     this.ReturnCode   = SpConverter.EnumToInt(DemoReponseId.Success);
     this.ReturnStatus = status;
     this.Uid          = msg.Uid;
 }
Example #3
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="msg">The paired incoming message</param>
 /// <param name="status">Extra status information</param>
 //public MySimpleOkResponse(MyBaseMsg msg, string status)
 //: base(MyMsgType.SimpleResponse, msg, MyReturnCode.Success, status) {
 public MySimpleOkResponse(ISpEventMessage msg, string status)
     : base(MyMsgType.SimpleResponse, MyMsgId.Tick, SpEventPriority.Normal)
 {
     this.ReturnCode   = SpConverter.EnumToInt(MyReturnCode.Success);
     this.ReturnStatus = status;
     this.Uid          = msg.Uid;
 }
        public LoadedDto LoadWebApps()
        {
            var spFarm = SpLocationHelper.GetFarm();

            var farmLocation = SpConverter.ToLocation(spFarm);

            // this variable will save all loaded information of all web applications
            var loadedElements = new LoadedDto(farmLocation);

            var spWebApps = SpLocationHelper.GetAllWebApplications();

            foreach (var wa in spWebApps)
            {
                var waLocation = wa.ToLocation(farmLocation.UniqueId);

                var activatedFeatures = wa.Features.ToActivatedFeatures(waLocation);

                // no non full trust farm features expected on scope web app
                // (sand boxed and add-in features are only scoped site and web)

                loadedElements.AddChild(waLocation, activatedFeatures, null);
            }

            return(loadedElements);
        }
Example #5
0
        public ISpEventMessage Response(ISpEventMessage msg)
        {
            MyMsgId   eventType = SpConverter.IntToEnum <MyMsgId>(msg.EventId);
            MyMsgType msgType   = SpConverter.IntToEnum <MyMsgType>(msg.TypeId);

            // All my messages are Simple Types so I do not need any other info for types. Otherwise I would need a switch
            return(new MyBaseMsg(msgType, eventType, msg.Priority)
            {
                ReturnCode = msg.ReturnCode,
                StringPayload = msg.StringPayload,
                ReturnStatus = msg.ReturnStatus
            });
        }
Example #6
0
        public TEntity MapEntity(TEntity entity, ListItem item)
        {
            if (_args == null || entity == null || item == null)
            {
                return(entity);
            }

            foreach (var fieldMap in _args.FieldMappings)
            {
                PropertyInfo prop = entity.GetType().GetProperty(fieldMap.Key, BindingFlags.Public | BindingFlags.Instance);
                if (null != prop)
                {
                    if (item.FieldValues.ContainsKey(fieldMap.Value.Name))
                    {
                        object value = item[fieldMap.Value.Name];
                        if (!SetEntityLookup(prop.PropertyType, prop.GetValue(entity), value))
                        {
                            if (prop.CanWrite)
                            {
                                value = GetFieldValue(fieldMap.Value, prop.PropertyType, value);
                                value = SpConverter.ConvertValue(value, prop.PropertyType);
                                prop.SetValue(entity, value);
                            }
                        }
                    }
                }
                FieldInfo field = entity.GetType().GetField(fieldMap.Key, BindingFlags.Public | BindingFlags.Instance);
                if (null != field)
                {
                    if (item.FieldValues.ContainsKey(fieldMap.Value.Name))
                    {
                        object value = item[fieldMap.Value.Name];
                        value = GetFieldValue(fieldMap.Value, field.FieldType, value);
                        value = SpConverter.ConvertValue(value, field.FieldType);
                        field.SetValue(entity, value);
                    }
                }
            }
            if (_args.IncludeItemPermissions)
            {
                if (item.IsPropertyAvailable("EffectiveBasePermissions"))
                {
                    if (entity is ListItemEntity)
                    {
                        (entity as ListItemEntity).EffectiveBasePermissions = item.EffectiveBasePermissions;
                    }
                }
            }
            return(entity);
        }
        public LoadedDto LoadFarm()
        {
            var loadedFarm = new LoadedDto(null);

            var farm = SpLocationHelper.GetFarm();

            var farmLocation = SpConverter.ToLocation(farm);

            var activatedFeatures = SpConverter.ToActivatedFeatures(farm.Features, farmLocation);

            // no non full trust farm features expected on scope farm
            // (sand boxed and add-in features are only scoped site and web)

            loadedFarm.AddChild(farmLocation, activatedFeatures, null);

            return(loadedFarm);
        }
        //protected override ISpEventMessage ExecOnTick(ISpEventMessage eventMsg) {
        //    Console.WriteLine("########## {0} has received OnTick event:{1}", this.FullName, eventMsg.EventId);
        //    return base.ExecOnEntry(eventMsg);
        //    // just push the same one back
        //    //return eventMsg;
        //}
        //protected override ISpEventMessage ExecOnTick(ISpEventMessage eventMsg) {
        //    Console.WriteLine("########## {0} has received OnTick event:{1}", this.FullName, eventMsg.EventId);
        //    return base.ExecOnEntry(eventMsg);
        //    // just push the same one back
        //    //return eventMsg;
        //}



        #region SpStateOverrides

        protected override ISpEventMessage OnRuntimeTransitionRequest(ISpEventMessage msg)
        {
            switch (SpConverter.IntToEnum <MyMsgId>(msg.EventId))
            {
            case MyMsgId.Abort:
                Log.Info("MySuperState", "OnRuntimeTransitionRequest", " *** Got abort and returning Stop");

                // get the GUID
                ISpEventMessage myMsg = new MyBaseMsg(MyMsgType.SimpleMsg, MyMsgId.Stop);
                myMsg.Uid = msg.Uid;
                return(myMsg);

            default:

                break;
            }


            //// Do not know which state this is except it is the current state
            if (msg.EventId == SpConverter.EnumToInt(MyMsgId.Abort))
            {
                //this.GetCurrentState().

                // get the GUID
                ISpEventMessage myMsg = new MyBaseMsg(MyMsgType.SimpleMsg, MyMsgId.Start);

                // Try recursion - no will not work
                //this.OnTick(myMsg);

                //this.GetCurrentState().

                //return this.GetOnResultTransition(myMsg);
            }


            return(base.OnRuntimeTransitionRequest(msg));
        }
Example #9
0
        protected override void VisitBodyClauses(ObservableCollection <IBodyClause> bodyClauses, QueryModel queryModel)
        {
            //base.VisitBodyClauses(bodyClauses, queryModel);
            if (_expression != null && _args != null)
            {
                if (_args != _expression.Args)
                {
                    return;
                }
                var item = _expression.Item;
                if (item != null)
                {
                    StringBuilder sb      = new StringBuilder();
                    bool          isIdSet = false;
                    foreach (var orderClause in bodyClauses.OfType <OrderByClause>())
                    {
                        if (orderClause != null)
                        {
                            foreach (var ordering in orderClause.Orderings)
                            {
                                string sortFieldKey = (ordering.Expression as MemberExpression).Member.Name;
                                if (_args.FieldMappings.ContainsKey(sortFieldKey))
                                {
                                    var fieldMap = _args.FieldMappings[sortFieldKey];
                                    if (fieldMap.Sortable == false)
                                    {
                                        continue;
                                    }
                                    object value = item[fieldMap.Name];

                                    if (fieldMap.DataType == FieldType.MultiChoice)
                                    {
                                        continue;
                                    }
                                    else if (fieldMap is ChoiceFieldAttribute && (fieldMap as ChoiceFieldAttribute).IsMultiple)
                                    {
                                        continue;
                                    }
                                    else if (fieldMap is NoteFieldAttribute)
                                    {
                                        continue;
                                    }

                                    if (value is DateTime)
                                    {
                                        value = Convert.ToDateTime(value).ToUniversalTime().ToString("yyyyMMdd HH:mm:ss");
                                    }
                                    else if (value is FieldLookupValue)
                                    {
                                        value = (value as FieldLookupValue).LookupValue;
                                    }
                                    else if (value is ICollection <FieldLookupValue> )
                                    {
                                        continue;
                                    }
                                    else if (value is FieldUrlValue)
                                    {
                                        value = string.IsNullOrEmpty((value as FieldUrlValue).Description)
                                            ? (value as FieldUrlValue).Url
                                            : (value as FieldUrlValue).Description;
                                    }
                                    else if (value is bool)
                                    {
                                        value = Convert.ToBoolean(value) == true ? 1 : 0;
                                    }
                                    else
                                    {
                                        if (value != null && value.GetType().IsArray)
                                        {
                                            continue;
                                        }
                                        value = SpConverter.ConvertValue(value, typeof(string));
                                    }
                                    if (sb.Length > 0)
                                    {
                                        sb.Append("&");
                                    }
                                    sb.Append($"p_{fieldMap.Name}={HttpUtility.UrlKeyValueEncode(Convert.ToString(value))}");
                                    if (fieldMap.Name == "ID")
                                    {
                                        isIdSet = true;
                                    }
                                }
                            }
                        }
                    }
                    if (!isIdSet)
                    {
                        if (sb.Length > 0)
                        {
                            sb.Append("&");
                        }
                        sb.Append($"p_ID={item.Id}");
                    }
                    PagingInfo = _expression.IsPrev ? $"Paged=TRUE&PagedPrev=TRUE&{sb.ToString()}" : $"Paged=TRUE&{sb.ToString()}";
                }
            }
        }
Example #10
0
        private static object GetFieldValue(FieldAttribute fieldAttr, Type valueType, object value)
        {
            if (value != null)
            {
                if (fieldAttr.DataType == FieldType.Choice || fieldAttr.DataType == FieldType.MultiChoice)
                {
                    value = EnumExtensions.ParseChoiceValue(valueType, value.ToString());
                }
                else if (fieldAttr.DataType == FieldType.Lookup && (typeof(LookupFieldAttribute).IsAssignableFrom(fieldAttr.GetType()) || fieldAttr.GetType().IsSubclassOf(typeof(LookupFieldAttribute))))
                {
                    var lookupFieldMap = fieldAttr as LookupFieldAttribute;

                    if (lookupFieldMap.Result == LookupItemResult.None)
                    {
                        return(value);
                    }

                    if (value is FieldLookupValue)
                    {
                        if (!typeof(FieldLookupValue).IsAssignableFrom(valueType) && !valueType.IsSubclassOf(typeof(FieldLookupValue)))
                        {
                            value = lookupFieldMap.Result == LookupItemResult.Id
                                ? (object)(value as FieldLookupValue).LookupId
                                : (value as FieldLookupValue).LookupValue;

                            if (valueType.IsArray)
                            {
                                var elType = (valueType.GetElementType()
                                              ?? valueType.GenericTypeArguments.FirstOrDefault())
                                             ?? typeof(object);
                                value = new[] { SpConverter.ConvertValue(value, elType) }.ToArray(elType);
                            }
                        }
                    }
                    else if (value is FieldLookupValue[])
                    {
                        if (!lookupFieldMap.IsMultiple)
                        {
                            var lookupValue = (value as FieldLookupValue[]).FirstOrDefault();
                            if (lookupValue != null)
                            {
                                if (!typeof(FieldLookupValue).IsAssignableFrom(valueType) && !valueType.IsSubclassOf(typeof(FieldLookupValue)))
                                {
                                    value = lookupFieldMap.Result == LookupItemResult.Id ? (object)lookupValue.LookupId : lookupValue.LookupValue;
                                }
                                else
                                {
                                    value = lookupValue;
                                }
                            }
                            else
                            {
                                value = null;
                            }
                        }
                        else
                        {
                            var elType = (valueType.GetElementType()
                                          ?? valueType.GenericTypeArguments.FirstOrDefault())
                                         ?? typeof(object);
                            if (!typeof(FieldLookupValue).IsAssignableFrom(elType) && !elType.IsSubclassOf(typeof(FieldLookupValue)))
                            {
                                var result = lookupFieldMap.Result == LookupItemResult.Id
                                ? (value as FieldLookupValue[]).Select(v => SpConverter.ConvertValue(v.LookupId, elType))
                                : (value as FieldLookupValue[]).Select(v => SpConverter.ConvertValue(v.LookupValue, elType));
                                if (valueType.IsArray)
                                {
                                    value = result.ToArray(elType);
                                }
                                else
                                {
                                    value = result.ToList(elType);
                                }
                            }
                        }
                    }
                }
            }
            return(value);
        }
Example #11
0
        public TEntity ToEntity(ListItem item)
        {
            var entity = new TEntity();

            if (_args != null)
            {
                if (item != null)
                {
                    foreach (var fieldMap in _args.FieldMappings)
                    {
                        PropertyInfo prop = entity.GetType().GetProperty(fieldMap.Key, BindingFlags.Public | BindingFlags.Instance);
                        if (null != prop)
                        {
                            if (prop.CustomAttributes.Any(att => att.AttributeType == typeof(RemovedFieldAttribute)))
                            {
                                continue;
                            }
                            if (fieldMap.Value.Name == "ID" && item.IsPropertyAvailable("Id"))
                            {
                                if (prop.CanWrite)
                                {
                                    prop.SetValue(entity, SpConverter.ConvertValue(item.Id, prop.PropertyType));
                                }
                                continue;
                            }
                            if (item.FieldValues.ContainsKey(fieldMap.Value.Name))
                            {
                                object value = item[fieldMap.Value.Name];
                                if (!SetEntityLookup(prop.PropertyType, prop.GetValue(entity), value))
                                {
                                    if (typeof(IListItemEntity).IsAssignableFrom(prop.PropertyType))
                                    {
                                        continue;
                                    }
                                    if (!prop.CanWrite)
                                    {
                                        continue;
                                    }
                                    value = GetFieldValue(fieldMap.Value, prop.PropertyType, value);
                                    value = SpConverter.ConvertValue(value, prop.PropertyType);
                                    prop.SetValue(entity, value);
                                }
                            }
                        }
                        FieldInfo field = entity.GetType().GetField(fieldMap.Key, BindingFlags.Public | BindingFlags.Instance);
                        if (null != field)
                        {
                            if (field.CustomAttributes.Any(att => att.AttributeType == typeof(RemovedFieldAttribute)))
                            {
                                continue;
                            }
                            if (fieldMap.Value.Name == "ID" && item.IsPropertyAvailable("Id"))
                            {
                                field.SetValue(entity, SpConverter.ConvertValue(item.Id, field.FieldType));
                                continue;
                            }
                            if (item.FieldValues.ContainsKey(fieldMap.Value.Name))
                            {
                                object value = item[fieldMap.Value.Name];
                                value = GetFieldValue(fieldMap.Value, field.FieldType, value);
                                value = SpConverter.ConvertValue(value, field.FieldType);
                                field.SetValue(entity, value);
                            }
                        }
                    }
                    if (_args.IncludeItemPermissions)
                    {
                        if (item.IsPropertyAvailable("EffectiveBasePermissions"))
                        {
                            if (entity is ListItemEntity)
                            {
                                (entity as ListItemEntity).EffectiveBasePermissions = item.EffectiveBasePermissions;
                            }
                        }
                    }

                    if (typeof(ICustomMapping).IsAssignableFrom(entity.GetType()))
                    {
                        (entity as ICustomMapping).MapFrom(item);
                    }
                }

                foreach (var entitySet in GetEntitySets(entity))
                {
                    if (entitySet != null && entitySet.SpQueryArgs != null)
                    {
                        entitySet.SpQueryArgs.Context = _args.Context;
                    }
                }
            }
            return(entity);
        }
        public LoadedDto LoadWebAppChildren(Location location, bool elevatedPrivileges)
        {
            // this variable will save all loaded information of all web applications
            var loadedElements = new LoadedDto(location);

            var spWebApp = SpLocationHelper.GetWebApplication(location.Id);

            if (spWebApp == null)
            {
                // The web application might have got deleted!?
                // throw?
                return(null);
            }

            var siCos = spWebApp.Sites;

            foreach (SPSite spSite in siCos)
            {
                Location siteLocation;
                //try
                //{

                if (elevatedPrivileges)
                {
                    siteLocation = SpSiteElevation.SelectAsSystem(spSite, SpConverter.ToLocation, location.UniqueId);
                }
                else
                {
                    siteLocation = SpConverter.ToLocation(spSite, location.UniqueId);
                }

                // meaning that they are not installed in the farm, rather on site or web level
                IEnumerable <FeatureDefinition> nonFarmFeatureDefinitions;

                SPFeatureCollection siteFeatureCollection = SpFeatureHelper.GetFeatureCollection(spSite, elevatedPrivileges);

                var activatedSiteFeatures = siteFeatureCollection.ToActivatedFeatures(siteLocation, out nonFarmFeatureDefinitions);

                loadedElements.AddChild(siteLocation, activatedSiteFeatures, nonFarmFeatureDefinitions);

                if (siteLocation.LockState != LockState.NoAccess && spSite != null && spSite.AllWebs != null)
                {
                    SPWebCollection allWebs;

                    if (elevatedPrivileges)
                    {
                        allWebs = SpSiteElevation.SelectAsSystem(spSite, SpLocationHelper.GetAllWebs);
                    }
                    else
                    {
                        allWebs = spSite.AllWebs;
                    }

                    foreach (SPWeb spWeb in allWebs)
                    {
                        var webLocation = SpConverter.ToLocation(spWeb, siteLocation.UniqueId);

                        nonFarmFeatureDefinitions = null;

                        SPFeatureCollection webFeatureCollection = SpFeatureHelper.GetFeatureCollection(spWeb, elevatedPrivileges);

                        var activatedWebFeatures = webFeatureCollection.ToActivatedFeatures(webLocation, out nonFarmFeatureDefinitions);

                        loadedElements.AddChild(webLocation, activatedWebFeatures, nonFarmFeatureDefinitions);

                        // https://blogs.technet.microsoft.com/stefan_gossner/2008/12/05/disposing-spweb-and-spsite-objects/
                        spWeb.Dispose();
                    }
                }

                spSite.Dispose();

                // This is the right place for debugging exception handling of lock state of site collections
                //}
                //catch (Exception Ex)
                //{

                //    throw Ex;
                //}
            }

            return(loadedElements);
        }