/// <summary>
        /// create a dynamic from given xml element
        /// this uses code from http://www.codeproject.com/Articles/461677/Creating-a-dynamic-object-from-XML-using-ExpandoOb
        /// </summary>
        public static dynamic ParseXML(this XElement xml)
        {
            var root = new ExpandoObject();

            ExpandoObjectHelper.Parse(root, xml);
            return(root);
        }
Exemple #2
0
        static void Main(string[] args)
        {
            // dynamic exp = new ExpandoObject();
            // exp.FullName = "Joe Satriani";

            dynamic exp = ExpandoObjectHelper.CreateDynamicObject("FullName", "Joseph Satriani");

            exp.DOB = new DateTime(1956, 7, 15);
            System.Console.WriteLine($"Name: {exp.FullName}; Date of birth: {exp.DOB.ToShortDateString()}");

            // #############################################################################################
            // public void ChangeName(string newName)
            // exp.ChangeName = (Action<string>)((string newName) =>
            // {
            //     exp.FullName = newName;
            // });
            // exp.ChangeName("Joe Satriani");
            // System.Console.WriteLine($"Name: {exp.FullName}; Date of birth: {exp.DOB.ToShortDateString()}");
            // #############################################################################################
            // public int Age()
            // exp.Age = (Func<int>)(() =>
            // {
            //     var today = DateTime.Today;
            //     var age = today.Year - exp.DOB.Year;
            //     // Go back to the year the person was born in case of a leap year
            //     if (exp.DOB.Date > today.AddYears(-age)) age--;
            //     return age;
            // });
            // System.Console.WriteLine($"Age: {exp.Age()}");
            // #############################################################################################
            // int ChangeNameGetLength(string newName)
            // exp.ChangeNameGetLength = (Func<string, int>)((string newName) =>
            // {
            //     exp.FullName = newName;
            //     return newName.Length;
            // });
            // System.Console.WriteLine(exp.ChangeNameGetLength("Joe 'Satch' Satriani"));
            // #############################################################################################


            System.Console.WriteLine("Serialized Contents:");
            var str = ExpandoObjectHelper.Serialize(exp);

            System.Console.WriteLine(str);

            System.Console.WriteLine("Deserialized Contents:");
            dynamic exp2 = ExpandoObjectHelper.Deserialize(str);

            ExpandoObjectHelper.GetProperties(exp2);
        }
Exemple #3
0
        private static void Register(XDocument xml)
        {
            var manifest = xml.Descendants("Manifest").First();
            var cls      = (string)manifest.Attribute("Type");
            var type     = Type.GetType(cls);

            if (type == null)
            {
                throw new InvalidDataException("Failed to load game type:" + cls);
            }

            var name     = (string)manifest.Attribute("Name");
            var viewPath = (string)manifest.Attribute("ViewPath");
            var colorSelectionEnabledAttribute = (string)manifest.Attribute("ColorSelectionEnabled");
            var colorSelectionEnabled          = (colorSelectionEnabledAttribute != null && colorSelectionEnabledAttribute.ToLower() == "false") ? false : true;
            var maxPlayers = (int)manifest.Attribute("MaxPlayers");
            var props      = new List <GameCreationProperty>();
            var xmlProps   = manifest.Element("CreationOptions").Elements("Option");


            foreach (var item in xmlProps)
            {
                dynamic data        = new ExpandoObject();
                var     dataElement = item.Element("Data");
                if (dataElement != null)
                {
                    var elements = dataElement.Elements();
                    ExpandoObjectHelper.Parse(data, dataElement, (new string[] { "Value" }).ToList());
                    data = data.Data;
                }

                var option = new GameCreationProperty(
                    (string)item.Attribute("Id"),
                    (string)item.Attribute("Name"),
                    (string)item.Attribute("Type"),
                    data
                    );
                props.Add(option);
            }

            Register(name, viewPath, type, maxPlayers, colorSelectionEnabled, props);
        }
Exemple #4
0
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void Render(Context context, TextWriter result)
        {
            // first ensure that entity commands are allowed in the context
            if (!this.IsAuthorized(context))
            {
                result.Write(string.Format(RockLavaBlockBase.NotAuthorizedMessage, this.Name));
                base.Render(context, result);
                return;
            }

            var parms = ParseMarkup(_markup, context);

            if (!string.IsNullOrWhiteSpace(parms["url"]))
            {
                dynamic responseData = null;

                try {
                    var client = new RestClient(parms["url"].ToString());

                    var request = new RestRequest(parms["method"].ToUpper().ConvertToEnum <Method>(Method.GET));
                    client.Timeout = parms["timeout"].AsInteger();

                    // handle basic auth
                    if (!string.IsNullOrWhiteSpace(parms["basicauth"]))
                    {
                        string[] authParts = parms["basicauth"].Split(',');
                        if (authParts.Length == 2)
                        {
                            client.Authenticator = new HttpBasicAuthenticator(authParts[0], authParts[1]);
                        }
                    }

                    // add query string parms
                    if (!string.IsNullOrWhiteSpace(parms["parameters"]))
                    {
                        foreach (var queryString in parms["parameters"].ToKeyValuePairList())
                        {
                            request.AddParameter(queryString.Key, queryString.Value);
                        }
                    }

                    // add headers
                    if (!string.IsNullOrWhiteSpace(parms["headers"]))
                    {
                        foreach (var header in parms["headers"].ToKeyValuePairList())
                        {
                            request.AddHeader(header.Key, header.Value.ToString());
                        }
                    }

                    // add body, this will be ignored if other parameters exist
                    if (!string.IsNullOrWhiteSpace(parms["body"]))
                    {
                        if (parms.ContainsKey("requestcontenttype"))
                        {
                            request.AddParameter(parms["requestcontenttype"], parms["body"], ParameterType.RequestBody);
                        }
                        else
                        {
                            result.Write("When using the 'body' parameter you must also provide a 'requestcontenttype' also.");
                            base.Render(context, result);
                            return;
                        }
                    }

                    IRestResponse response = client.Execute(request);
                    var           content  = response.Content;

                    var contentType = parms["responsecontenttype"].ToLower();

                    if (contentType == "xml")
                    {
                        responseData = new ExpandoObject();
                        var doc = XDocument.Parse(response.Content);
                        ExpandoObjectHelper.Parse(responseData, doc.Root);
                    }
                    else if (contentType == "json")
                    {
                        var converter = new ExpandoObjectConverter();

                        // determine if the return type is an array or not
                        if (content.Trim().Substring(0, 1) == "[")
                        {
                            responseData = JsonConvert.DeserializeObject <List <ExpandoObject> >(content, converter); // array
                        }
                        else
                        {
                            responseData = JsonConvert.DeserializeObject <ExpandoObject>(content, converter);  // not an array
                        }
                    }
                    else // otherwise assume html and just throw the contents out to the screen
                    {
                        responseData = content;
                    }

                    context.Scopes.Last()[parms["return"]] = responseData;
                } catch
                {
                    throw;
                }

                context.Scopes.Last()[parms["return"]] = responseData;
            }
            else
            {
                result.Write("No url parameter was found.");
            }
            base.Render(context, result);
        }