Converts an ExpandoObject to and from JSON.
Inheritance: JsonConverter
Exemplo n.º 1
0
        public ContractABI DeserialiseContract(string abi)
        {
            var convertor = new ExpandoObjectConverter();
            var contract = JsonConvert.DeserializeObject<List<ExpandoObject>>(abi, convertor);
            var functions = new List<FunctionABI>();
            var events = new List<EventABI>();
            ConstructorABI constructor = null;

            foreach (dynamic element in contract)
            {
                if (element.type == "function")
                {
                    functions.Add(BuildFunction(element));
                }
                if (element.type == "event")
                {
                    events.Add(BuildEvent(element));
                }
                if (element.type == "constructor")
                {
                    constructor = BuildConstructor(element);
                }
            }

            var contractABI = new ContractABI();
            contractABI.Functions = functions.ToArray();
            contractABI.Constructor = constructor;
            contractABI.Events = events.ToArray();

            return contractABI;

        }
        /// <summary>
        /// Deep copies an ExpandoObject though serialization
        /// </summary>
        /// <param name="obj">ExpandoObject to copy</param>
        /// <returns></returns>
        public static ExpandoObject DeepCopy(this ExpandoObject obj)
        {
            string data = JsonConvert.SerializeObject(obj);
            ExpandoObjectConverter converter = new ExpandoObjectConverter();

            return JsonConvert.DeserializeObject<ExpandoObject>(data, converter);
        }
Exemplo n.º 3
0
        public static ExpandoObject Clone(this ExpandoObject original)
        {
            var expandoObjectConverter = new ExpandoObjectConverter();
            var originalDoc = JsonConvert.SerializeObject(original, expandoObjectConverter);

            dynamic clone = JsonConvert.DeserializeObject<ExpandoObject>(originalDoc, expandoObjectConverter);

            return clone;
        }
Exemplo n.º 4
0
        public async Task<dynamic> GetDeploymentProcessAsync(string id)
        {
            var deploymentProcessLink = string.Format("api/deploymentprocesses/{0}", id);
            var deploymentProcesDoc = await this.GetStringAsync(deploymentProcessLink);
            var expandoObjectConverter = new ExpandoObjectConverter();
            dynamic deployementProcess = JsonConvert.DeserializeObject<ExpandoObject>(deploymentProcesDoc, expandoObjectConverter);

            return deployementProcess;
        }
Exemplo n.º 5
0
        public async Task UpdateDeploymentProcessAsync(string id, dynamic deploymentProcess)
        {
            var expandoObjectConverter = new ExpandoObjectConverter();
            var deploymentProcessDoc = JsonConvert.SerializeObject(deploymentProcess, expandoObjectConverter);

            var updateLink = string.Format("api/deploymentprocesses/{0}", id);

            var response = await this.PutAsync(updateLink, new StringContent(deploymentProcessDoc));
            var responseContent = response.Content.ReadAsStringAsync();
            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 6
0
        public static dynamic DeserializeResponse(string data, string format = null)
        {
            // Empty responses
            if (String.IsNullOrWhiteSpace(data)) return null;
            if (data.Trim() == "[]") return null;

            var converter = new ExpandoObjectConverter();
            data = data.Trim();

            if(format != null)
            {
                // Data response (such as from Pull requests)
                switch(format)
                {
                    case Constants.DATA_FORMAT_META_PLUS_INTERACTIONS:
                        return JsonConvert.DeserializeObject<ExpandoObject>(data, converter);
                    case Constants.DATA_FORMAT_ARRAY_INTERACTIONS:
                        return JsonConvert.DeserializeObject<List<ExpandoObject>>(data, converter);
                    case Constants.DATA_FORMAT_NEWLINE_INTERACTIONS:

                        var items = new List<ExpandoObject>();

                        foreach(var line in data.Split('\n'))
                        {
                            items.Add(JsonConvert.DeserializeObject<ExpandoObject>(line, converter));
                        }
                        return items;

                    default:
                        throw new ArgumentException(Messages.UNRECOGNISED_DATA_FORMAT, "format");
                }

            }
            else
            {
                // Standard API responses
                if (data.StartsWith("["))
                {
                    // Data is an array of items
                    if (data.StartsWith("[\""))
                    {
                        // Is an array of strings
                        return JsonConvert.DeserializeObject<List<string>>(data, converter);
                    }
                    else
                        return JsonConvert.DeserializeObject<List<ExpandoObject>>(data, converter);
                }
                else
                {
                    return JsonConvert.DeserializeObject<ExpandoObject>(data, converter);
                }
            }
        }
Exemplo n.º 7
0
        void IDiaSession.findChildren(IDiaSymbol parent, SymTagEnum symTag, string name, uint compareFlags, out IDiaEnumSymbols ppResult)
        {
            dynamic typ = null;

            if (!Dia3.StructCache.ContainsKey(name))
            {
                var json      = SymAPI.TypeDef(name, CV);
                var converter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();
                var obj       = JsonConvert.DeserializeObject <List <ExpandoObject> >(json.Result, converter);
                // we access just the first object back
                Dia3.StructCache.TryAdd(name, obj.First());
            }
            Dia3.StructCache.TryGetValue(name, out typ);

            ppResult = new EnumSymbols(CV, EnumSymType.Sym, typ);
            return;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Gets the name of the facebook user.
        /// </summary>
        /// <param name="facebookUser">The facebook user.</param>
        /// <param name="syncFriends">if set to <c>true</c> [synchronize friends].</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetFacebookUserName( FacebookUser facebookUser, bool syncFriends = false, string accessToken = "" )
        {
            string username = string.Empty;
            string facebookId = facebookUser.id;
            string facebookLink = facebookUser.link;

            string userName = "******" + facebookId;
            UserLogin user = null;

            using ( var rockContext = new RockContext() )
            {

                // Query for an existing user
                var userLoginService = new UserLoginService( rockContext );
                user = userLoginService.GetByUserName( userName );

                // If no user was found, see if we can find a match in the person table
                if ( user == null )
                {
                    // Get name/email from Facebook login
                    string lastName = facebookUser.last_name.ToStringSafe();
                    string firstName = facebookUser.first_name.ToStringSafe();
                    string email = string.Empty;
                    try { email = facebookUser.email.ToStringSafe(); }
                    catch { }

                    Person person = null;

                    // If person had an email, get the first person with the same name and email address.
                    if ( !string.IsNullOrWhiteSpace( email ) )
                    {
                        var personService = new PersonService( rockContext );
                        var people = personService.GetByMatch( firstName, lastName, email );
                        if ( people.Count() == 1)
                        {
                            person = people.First();
                        }
                    }

                    var personRecordTypeId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                    var personStatusPending = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid() ).Id;

                    rockContext.WrapTransaction( () =>
                    {
                        if ( person == null )
                        {
                            person = new Person();
                            person.IsSystem = false;
                            person.RecordTypeValueId = personRecordTypeId;
                            person.RecordStatusValueId = personStatusPending;
                            person.FirstName = firstName;
                            person.LastName = lastName;
                            person.Email = email;
                            person.IsEmailActive = true;
                            person.EmailPreference = EmailPreference.EmailAllowed;
                            try
                            {
                                if ( facebookUser.gender.ToString() == "male" )
                                {
                                    person.Gender = Gender.Male;
                                }
                                else if ( facebookUser.gender.ToString() == "female" )
                                {
                                    person.Gender = Gender.Female;
                                }
                                else
                                {
                                    person.Gender = Gender.Unknown;
                                }
                            }
                            catch { }

                            if ( person != null )
                            {
                                PersonService.SaveNewPerson( person, rockContext, null, false );
                            }
                        }

                        if ( person != null )
                        {
                            int typeId = EntityTypeCache.Read( typeof( Facebook ) ).Id;
                            user = UserLoginService.Create( rockContext, person, AuthenticationServiceType.External, typeId, userName, "fb", true );
                        }

                    } );
                }

                if ( user != null )
                {
                    username = user.UserName;

                    if ( user.PersonId.HasValue )
                    {
                        var converter = new ExpandoObjectConverter();

                        var personService = new PersonService( rockContext );
                        var person = personService.Get( user.PersonId.Value );
                        if ( person != null )
                        {
                            // If person does not have a photo, try to get their Facebook photo
                            if ( !person.PhotoId.HasValue )
                            {
                                var restClient = new RestClient( string.Format( "https://graph.facebook.com/v2.2/{0}/picture?redirect=false&type=square&height=400&width=400", facebookId ) );
                                var restRequest = new RestRequest( Method.GET );
                                restRequest.RequestFormat = DataFormat.Json;
                                restRequest.AddHeader( "Accept", "application/json" );
                                var restResponse = restClient.Execute( restRequest );
                                if ( restResponse.StatusCode == HttpStatusCode.OK )
                                {
                                    dynamic picData = JsonConvert.DeserializeObject<ExpandoObject>( restResponse.Content, converter );
                                    bool isSilhouette = picData.data.is_silhouette;
                                    string url = picData.data.url;

                                    // If Facebook returned a photo url
                                    if ( !isSilhouette && !string.IsNullOrWhiteSpace( url ) )
                                    {
                                        // Download the photo from the url provided
                                        restClient = new RestClient( url );
                                        restRequest = new RestRequest( Method.GET );
                                        restResponse = restClient.Execute( restRequest );
                                        if ( restResponse.StatusCode == HttpStatusCode.OK )
                                        {
                                            var bytes = restResponse.RawBytes;

                                            // Create and save the image
                                            BinaryFileType fileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid() );
                                            if ( fileType != null )
                                            {
                                                var binaryFileService = new BinaryFileService( rockContext );
                                                var binaryFile = new BinaryFile();
                                                binaryFileService.Add( binaryFile );
                                                binaryFile.IsTemporary = false;
                                                binaryFile.BinaryFileType = fileType;
                                                binaryFile.MimeType = "image/jpeg";
                                                binaryFile.FileName = user.Person.NickName + user.Person.LastName + ".jpg";
                                                binaryFile.ContentStream = new MemoryStream( bytes );

                                                rockContext.SaveChanges();

                                                person.PhotoId = binaryFile.Id;
                                                rockContext.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }

                            // Save the facebook social media link
                            var facebookAttribute = AttributeCache.Read( Rock.SystemGuid.Attribute.PERSON_FACEBOOK.AsGuid() );
                            if ( facebookAttribute != null )
                            {
                                person.LoadAttributes( rockContext );
                                person.SetAttributeValue( facebookAttribute.Key, facebookLink );
                                person.SaveAttributeValues( rockContext );
                            }

                            if ( syncFriends && !string.IsNullOrWhiteSpace( accessToken ) )
                            {
                                // Get the friend list (only includes friends who have also authorized this app)
                                var restRequest = new RestRequest( Method.GET );
                                restRequest.AddParameter( "access_token", accessToken );
                                restRequest.RequestFormat = DataFormat.Json;
                                restRequest.AddHeader( "Accept", "application/json" );

                                var restClient = new RestClient( string.Format( "https://graph.facebook.com/v2.2/{0}/friends", facebookId ) );
                                var restResponse = restClient.Execute( restRequest );

                                if ( restResponse.StatusCode == HttpStatusCode.OK )
                                {
                                    // Get a list of the facebook ids for each friend
                                    dynamic friends = JsonConvert.DeserializeObject<ExpandoObject>( restResponse.Content, converter );
                                    var facebookIds = new List<string>();
                                    foreach ( var friend in friends.data )
                                    {
                                        facebookIds.Add( friend.id );
                                    }

                                    // Queue a transaction to add/remove friend relationships in Rock
                                    var transaction = new Rock.Transactions.UpdateFacebookFriends( person.Id, facebookIds );
                                    Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction );
                                }
                            }
                        }

                    }
                }

                return username;
            }
        }
        /// <summary>
        /// Queries the Cireson Portal for the specified user's security rights
        /// </summary>
        /// <param name="authToken">AuthorizationToken to use</param>
        /// <param name="userName">User name to query</param>
        /// <param name="domain">Domain of the user</param>
        /// <returns></returns>
        public static async Task<ConsoleUser> GetUserRights(AuthorizationToken authToken, string userName, string domain)
        {
            if (!authToken.IsValid)
            {
                throw new InvalidCredentialException("AuthorizationToken is not valid.");
            }

            string endpointUrl = IS_USER_AUTHORIZED_ENDPOINT + "?userName="******"&domain=" + domain;

            try
            {
                // Initialize the HTTP helper and get going
                PortalHttpHelper helper = new PortalHttpHelper(authToken);
                string result = await helper.PostAsync(endpointUrl, String.Empty);

                // Deserialize the object to an ExpandoObject and return a ConsoleUser
                ExpandoObjectConverter converter = new ExpandoObjectConverter();
                dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(result, converter);

                ConsoleUser returnObj = new ConsoleUser(obj);
                returnObj.IncidentSupportGroups = await GetUsersTierQueueEnumerations(authToken, returnObj);

                return returnObj;
            }
            catch (Exception e)
            {
                throw; // Rethrow exceptions
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Gets the name of the Google user.
        /// </summary>
        /// <param name="googleUser">The Google user.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetGoogleUser( GoogleUser googleUser, string accessToken = "" )
        {
            string username = string.Empty;
            string googleId = googleUser.id;
            string googleLink = googleUser.link;

            string userName = "******" + googleId;
            UserLogin user = null;

            using (var rockContext = new RockContext() )
            {

                // Query for an existing user
                var userLoginService = new UserLoginService(rockContext);
                user = userLoginService.GetByUserName(userName);

                // If no user was found, see if we can find a match in the person table
                if ( user == null )
                    {
                    // Get name/email from Google login
                    string lastName = googleUser.family_name.ToString();
                    string firstName = googleUser.given_name.ToString();
                    string email = string.Empty;
                    try { email = googleUser.email.ToString(); }
                    catch { }

                    Person person = null;

                    // If person had an email, get the first person with the same name and email address.
                    if ( !string.IsNullOrWhiteSpace(email) )
                    {
                        var personService = new PersonService(rockContext);
                        var people = personService.GetByMatch(firstName, lastName, email);
                        if ( people.Count() == 1 )
                        {
                            person = people.First();
                        }
                    }

                    var personRecordTypeId = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    var personStatusPending = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id;

                    rockContext.WrapTransaction(( ) =>
                    {
                        if ( person == null )
                        {
                            person = new Person();
                            person.IsSystem = false;
                            person.RecordTypeValueId = personRecordTypeId;
                            person.RecordStatusValueId = personStatusPending;
                            person.FirstName = firstName;
                            person.LastName = lastName;
                            person.Email = email;
                            person.IsEmailActive = true;
                            person.EmailPreference = EmailPreference.EmailAllowed;
                            try
                            {
                                if ( googleUser.gender.ToString() == "male" )
                                {
                                    person.Gender = Gender.Male;
                                }
                                else if ( googleUser.gender.ToString() == "female" )
                                {
                                    person.Gender = Gender.Female;
                                }
                                else
                                {
                                    person.Gender = Gender.Unknown;
                                }
                            }
                            catch { }

                            if ( person != null )
                            {
                                PersonService.SaveNewPerson(person, rockContext, null, false);
                            }
                        }

                        if ( person != null )
                        {
                            int typeId = EntityTypeCache.Read(typeof(Google)).Id;
                            user = UserLoginService.Create(rockContext, person, AuthenticationServiceType.External, typeId, userName, "goog", true);
                        }

                    });
                }
                if ( user != null )
                {
                    username = user.UserName;

                    if ( user.PersonId.HasValue )
                    {
                        var converter = new ExpandoObjectConverter();

                        var personService = new PersonService(rockContext);
                        var person = personService.Get(user.PersonId.Value);
                    }
                }

                return username;
            }
        }
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if(context.HttpContext.Request.Method != HttpMethod.Post.ToString())
            {
                throw new reCAPTCHAException("ValidateRecaptchaAttribute must only decorate POST actions.");
            }

            StringValues recaptchaResponse;
            try {
                recaptchaResponse = context.HttpContext.Request.Form["g-recaptcha-response"];
            }
            catch(InvalidOperationException exc)
            {
                throw new reCAPTCHAException("reCAPTCHA failure, likely due to ValidateRecaptchaAttribute improperly decorating an action to which an unintended request has been posted.", exc);
            }

            if (String.IsNullOrWhiteSpace(recaptchaResponse))
            {
                context.ModelState.AddModelError("reCAPTCHAFailure", ErrorMessage);
                await next();
            }

            var builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings.json");
            builder.AddEnvironmentVariables();
            var config = builder.Build();
            var siteSecret = config["RecaptchaOptions:Secret"];

            if (String.IsNullOrWhiteSpace(siteSecret))
            {
                throw new reCAPTCHAException("Could not find value for reCAPTCHA Secret in appsettings.json.");
            }

            using (var client = new HttpClient())
            {
                var values = new Dictionary<string, string>
                {
                   { "secret", siteSecret },
                   { "response", context.HttpContext.Request.Form["g-recaptcha-response"] },
                   { "remoteip", GetRemoteIp(context) }
                };
                var content = new FormUrlEncodedContent(values);

                HttpResponseMessage response;
                try {
                    response = await client.PostAsync(verificationUrl, content);
                }
                catch(HttpRequestException exc)
                {
                    throw new reCAPTCHAException("Could not reach Google's reCAPTCHA service for verification.", exc);
                }
                var responseString = await response.Content.ReadAsStringAsync();

                var converter = new ExpandoObjectConverter();
                try {
                    dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(responseString, converter);
                    bool isHuman = obj.success;

                    if (!isHuman)
                    {
                        context.ModelState.AddModelError("reCAPTCHAFailure", ErrorMessage);
                    }
                }
                catch(RuntimeBinderException exc)
                {
                    throw new reCAPTCHAException("Response from Google's verification service was in an unexpected format:" + responseString, exc);
                }
            }

            await next();
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets the name of the Twitter user.
        /// </summary>
        /// <param name="twitterUser">The Twitter user.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetTwitterUser( dynamic twitterUser, string accessToken = "" )
        {
            string username = string.Empty;
            string twitterId = twitterUser.id_str;
            string twitterLink = "https://twitter.com/" + twitterUser.screen_name;

            string userName = "******" + twitterId;
            UserLogin user = null;

            using ( var rockContext = new RockContext() )
            {

                // Query for an existing user
                var userLoginService = new UserLoginService( rockContext );
                user = userLoginService.GetByUserName( userName );

                // If no user was found, see if we can find a match in the person table
                if ( user == null )
                {
                    // Get name and email from twitterUser object and then split the name
                    string fullName = twitterUser.name;
                    string firstName = null;
                    string lastName = null;
                    var personService = new PersonService( rockContext );
                    personService.SplitName( fullName, out firstName, out lastName );
                    string email = string.Empty;
                    try { email = twitterUser.email; }
                    catch { }

                    Person person = null;

                    // If person had an email, get the first person with the same name and email address.
                    if ( !string.IsNullOrWhiteSpace( email ) )
                    {
                        var people = personService.GetByMatch( firstName, lastName, email );
                        if ( people.Count() == 1 )
                        {
                            person = people.First();
                        }
                    }

                    var personRecordTypeId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                    var personStatusPending = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid() ).Id;

                    rockContext.WrapTransaction( () =>
                    {
                        // If not an existing person, create a new one
                        if ( person == null )
                        {
                            person = new Person();
                            person.IsSystem = false;
                            person.RecordTypeValueId = personRecordTypeId;
                            person.RecordStatusValueId = personStatusPending;
                            person.FirstName = firstName;
                            person.LastName = lastName;
                            person.Email = email;
                            person.IsEmailActive = true;
                            person.EmailPreference = EmailPreference.EmailAllowed;
                            person.Gender = Gender.Unknown;
                            if ( person != null )
                            {
                                PersonService.SaveNewPerson( person, rockContext, null, false );
                            }
                        }

                        if ( person != null )
                        {
                            int typeId = EntityTypeCache.Read( typeof( Facebook ) ).Id;
                            user = UserLoginService.Create( rockContext, person, AuthenticationServiceType.External, typeId, userName, "Twitter", true );
                        }

                    } );
                }

                if ( user != null )
                {
                    username = user.UserName;

                    if ( user.PersonId.HasValue )
                    {
                        var converter = new ExpandoObjectConverter();

                        var personService = new PersonService( rockContext );
                        var person = personService.Get( user.PersonId.Value );
                        if ( person != null )
                        {
                            string twitterImageUrl = twitterUser.profile_image_url;
                            bool twitterImageDefault = twitterUser.default_profile_image;
                            twitterImageUrl = twitterImageUrl.Replace( "_normal", "" );
                            // If person does not have a photo, use their Twitter photo if it exists
                            if ( !person.PhotoId.HasValue && !twitterImageDefault && !string.IsNullOrWhiteSpace( twitterImageUrl ) )
                            {
                                // Download the photo from the url provided
                                var restClient = new RestClient( twitterImageUrl );
                                var restRequest = new RestRequest( Method.GET );
                                var restResponse = restClient.Execute( restRequest );
                                if ( restResponse.StatusCode == HttpStatusCode.OK )
                                {
                                    var bytes = restResponse.RawBytes;

                                    // Create and save the image
                                    BinaryFileType fileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid() );
                                    if ( fileType != null )
                                    {
                                        var binaryFileService = new BinaryFileService( rockContext );
                                        var binaryFile = new BinaryFile();
                                        binaryFileService.Add( binaryFile );
                                        binaryFile.IsTemporary = false;
                                        binaryFile.BinaryFileType = fileType;
                                        binaryFile.MimeType = "image/jpeg";
                                        binaryFile.FileName = user.Person.NickName + user.Person.LastName + ".jpg";
                                        binaryFile.ContentStream = new MemoryStream( bytes );

                                        rockContext.SaveChanges();

                                        person.PhotoId = binaryFile.Id;
                                        rockContext.SaveChanges();
                                    }
                                }
                            }

                            // Save the Twitter social media link
                            var twitterAttribute = AttributeCache.Read( Rock.SystemGuid.Attribute.PERSON_TWITTER.AsGuid() );
                            if ( twitterAttribute != null )
                            {
                                person.LoadAttributes( rockContext );
                                person.SetAttributeValue( twitterAttribute.Key, twitterLink );
                                person.SaveAttributeValues( rockContext );
                            }
                        }

                    }
                }

                return username;
            }
        }
Exemplo n.º 13
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( "The Lava command '{0}' is not configured for this template.", 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 = 12000;

                    // 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(Exception ex )
                {
                    result.Write( string.Format("An error occurred: {0}", ex.Message ) );
                }

                context.Scopes.Last()[parms["return"]] = responseData;
            }
            else {
                result.Write( "No url parameter was found." );
            }
            base.Render( context, result );
        }
Exemplo n.º 14
0
        /// <summary>
        /// Returns a dynamic object from a JSON string
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static object FromJSON( object input )
        {
            var converter = new ExpandoObjectConverter();
            object contentObject = null;
            var value = input as string;

            try
            {
                // first try to deserialize as straight ExpandoObject
                contentObject = JsonConvert.DeserializeObject<ExpandoObject>( value, converter );
            }
            catch
            {
                try
                {
                    // if it didn't deserialize as straight ExpandoObject, try it as a List of ExpandoObjects
                    contentObject = JsonConvert.DeserializeObject<List<ExpandoObject>>( value, converter );
                }
                catch
                {
                    // if it didn't deserialize as a List of ExpandoObject, try it as a List of plain objects
                    contentObject = JsonConvert.DeserializeObject<List<object>>( value, converter );
                }
            }

            return contentObject;
        }