Ejemplo n.º 1
0
        private static Response ReturnJsonError(NancyContext context, Exception ex)
        {
            Response response = null;

            if (context.Request.Headers.Accept.Any(a => a.Item1.IndexOf("application/json", StringComparison.InvariantCultureIgnoreCase) >= 0))
            {
                var serializer = new Nancy.Json.JavaScriptSerializer();
                response = new Response()
                {
                    StatusCode  = HttpStatusCode.InternalServerError,
                    ContentType = "application/json",
                    Contents    = s =>
                    {
                        StreamWriter writer = new StreamWriter(s, new UTF8Encoding(false))
                        {
                            AutoFlush = true
                        };                                                                                       // Don't dispose this!
                        writer.Write(serializer.Serialize(new { detail = ex.Message }));
                    }
                };
            }

            try
            {
                StringBuilder log = GetLogForRequest(context);
                log.AppendLine().AppendLine("error: ").Append(ex.ToString());
                TvLibrary.Log.Log.Error(log.ToString());
            }
            catch
            {
            }

            return(response);
        }
Ejemplo n.º 2
0
        public ExampleNancyModule()
        {
            Get["/logs"] = parameters =>
            {
                string feeds = string.Empty;
                using (StreamReader reader = new StreamReader("Output.json"))
                {
                    feeds = reader.ReadToEnd();
                    reader.Close();
                    return(Response.AsJson(feeds));
                }
            };

            Post["/postlog"] = parameters =>
            {
                var post = this.Bind <LogInformation>(); //Breakpoint
                logInformation = post;
                var json = new Nancy.Json.JavaScriptSerializer().Serialize(logInformation);

                using (StreamWriter writer = new StreamWriter("Output.json"))
                {
                    writer.Write(json);
                    writer.Close();
                    return("Success");
                }
            };
        }
Ejemplo n.º 3
0
        public HomeModule()
        {
            Get["/"] = p => {
                var configuration = Nancy.TinyIoc.TinyIoCContainer.Current.Resolve <ServantConfiguration>();

                var latestErrors = EventLogHelper.GetByDateTimeDescending(5).ToList();
                latestErrors = EventLogHelper.AttachSite(latestErrors, Page.Sites);
                Model.UnhandledExceptions = latestErrors;
                Model.HaveSeenNewsletter  = configuration.HaveSeenNewsletter;
                return(View["Index", Model]);
            };

            Post["/subscribetonewsletter"] = p => {
                var email     = Request.Form.Email;
                var firstname = Request.Form.Firstname;
                var lastname  = Request.Form.Lastname;

                try
                {
                    new System.Net.Mail.MailAddress(email);
                }
                catch
                {
                    AddPropertyError("email", "Looks like the email is not valid.");
                }

                var serializer = new Nancy.Json.JavaScriptSerializer();

                if (HasErrors)
                {
                    return(new { Type = MessageType.Error.ToString(), Errors = serializer.Serialize(Model.Errors) });;
                }

                var response = MailchimpHelper.Subscribe(email, firstname, lastname);

                if (response != "true")
                {
                    MailchimpResponse result = serializer.Deserialize <MailchimpResponse>(response);

                    if (result.Code == 214)
                    {
                        SetNewsletterRead();
                    }

                    if (result.Code == 502)
                    {
                        AddPropertyError("email", "Looks like the email is not valid.");
                        return(new { Type = MessageType.Error, Errors = serializer.Serialize(Model.Errors) });
                    }

                    return(new { Message = result.Error, Type = MessageType.Error.ToString() });
                }

                SetNewsletterRead();

                return(new { Message = response, Type = MessageType.Success.ToString() });
            };
        }
Ejemplo n.º 4
0
        public HomeModule()
        {
            Get["/"] = p => {
                var configuration = Nancy.TinyIoc.TinyIoCContainer.Current.Resolve<ServantConfiguration>();

                var latestErrors = EventLogHelper.GetByDateTimeDescending(5).ToList();
                latestErrors = EventLogHelper.AttachSite(latestErrors, Page.Sites);
                Model.UnhandledExceptions = latestErrors;
                Model.HaveSeenNewsletter = configuration.HaveSeenNewsletter;
                return View["Index", Model];
            };

            Post["/subscribetonewsletter"] = p => {
                var email = Request.Form.Email;
                var firstname = Request.Form.Firstname;
                var lastname = Request.Form.Lastname;

                try
                {
                    new System.Net.Mail.MailAddress(email);
                }
                catch
                {
                    AddPropertyError("email", "Looks like the email is not valid.");
                }

                var serializer = new Nancy.Json.JavaScriptSerializer();

                if (HasErrors)
                {
                    return new { Type = MessageType.Error.ToString(), Errors = serializer.Serialize(Model.Errors) }; ;
                }

                var response = MailchimpHelper.Subscribe(email, firstname, lastname);

                if (response != "true")
                {
                    MailchimpResponse result = serializer.Deserialize<MailchimpResponse>(response);

                    if (result.Code == 214)
                    {
                        SetNewsletterRead();
                    }

                    if (result.Code == 502)
                    {
                        AddPropertyError("email", "Looks like the email is not valid.");
                        return new { Type = MessageType.Error, Errors = serializer.Serialize(Model.Errors) };
                    }

                    return new { Message = result.Error, Type = MessageType.Error.ToString() };
                }

                SetNewsletterRead();

                return new { Message = response, Type = MessageType.Success.ToString() };
            };
        }
Ejemplo n.º 5
0
 private static void refreshJSON()
 {
     Nancy.Json.JavaScriptSerializer js = new Nancy.Json.JavaScriptSerializer();
     StatsJSON         = js.Serialize(Stats);
     KeysJSON          = js.Serialize(Stats.Keys);
     ActiveplayersJSON = js.Serialize(Stats.ActivePlayers);
     MemoryUsageJSON   = js.Serialize(memoryUsage);
     RestartsJSON      = js.Serialize(Stats.Restarts);
 }
        public void Integer_dictionary_values_are_Json_serialized_as_integers()
        {
            dynamic value = 42;
            var     input = new DynamicDictionaryValue(value);

            var sut    = new Nancy.Json.JavaScriptSerializer();
            var actual = sut.Serialize(input);

            actual.ShouldEqual(@"42");
        }
        public void String_dictionary_values_are_Json_serialized_as_strings()
        {
            dynamic value = "42";
            var     input = new DynamicDictionaryValue(value);

            var sut    = new Nancy.Json.JavaScriptSerializer();
            var actual = sut.Serialize(input);

            actual.ShouldEqual(@"""42""");
        }
Ejemplo n.º 8
0
 Response Produce_output(object obj)
 {
     if (obj is string)
     {
         var response = (Response)(obj.ToString());
         response.ContentType = "text/plain";
         return(response);
     }
     else
     {
         var objJson  = new Nancy.Json.JavaScriptSerializer().Serialize(obj);
         var response = (Response)objJson;
         response.ContentType = "application/json";
         return(response);
     }
 }
Ejemplo n.º 9
0
 public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
 {
     using (var sr = new StreamReader(context.Request.Body))
     {
         var json = sr.ReadToEnd();
         if (json.Contains("SomeTriangleOnlyProp"))
         {
             var triangle = new Nancy.Json.JavaScriptSerializer().Deserialize <Triangle>(json);
             return(triangle);
         }
         else if (json.Contains("SomeSquareOnlyProp"))
         {
             var square = new Nancy.Json.JavaScriptSerializer().Deserialize <Square>(json);
             return(square);
         }
         else
         {
             var shape = new Nancy.Json.JavaScriptSerializer().Deserialize <Shape>(json);
             return(shape);
         }
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// get channel list from HDHomeRunPlus (from first device in list)
        /// </summary>
        /// <param name="ipaddr"></param>
        /// <returns>List of cChannels</returns>
        public static List<cChannels> getChannels(List<cHDHomeRunPlus> HDHDRPs)
        {
            try
            {
                List<cChannels> channels = new List<cChannels>();
                String json = string.Empty;

                //use webclient to request channel JSON from HDHomeRunPLus
                using (var client = new WebClient())
                {
                    //get channels using first HDHomeRunPlus device
                    json = client.DownloadString("http://" + HDHDRPs[0].IP + "/lineup.json");
                }
                //deserialize JSON into cChannel
                var serializer = new Nancy.Json.JavaScriptSerializer();
                channels = serializer.Deserialize<List<cChannels>>(json);

                return channels;
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("cChannel.getChannels, Error: {0}", ex.Message));
            }
        }
Ejemplo n.º 11
0
        public ServiceModule(ServiceManager serviceManager)
        {
            // Find all service methods having a ServiceGetContractAttribute attached to it.
            var bindQuery = from service in serviceManager.Services
                            from method in service.GetType().GetMethods()
                            from attribute in method.GetCustomAttributes(true)
                            where attribute is ServiceBase.ServiceGetContractAttribute
                            select new { service, method, attribute };

            foreach (var bindData in bindQuery)
            {
                var service   = bindData.service;
                var method    = bindData.method;
                var attribute = bindData.attribute;

                var contract = attribute as ServiceBase.ServiceGetContractAttribute;
                if (contract == null)
                {
                    continue;
                }

                bool isPut = contract is ServiceBase.ServicePutContractAttribute;

                var    mapper = new ContractMapper("/" + service.Name + "/" + contract.uri, method);
                string uri    = mapper.GetMappedUri();

                Func <dynamic, dynamic> lambda = parameters =>
                {
                    var arguments = new List <object>();

                    mapper.MapArguments(parameters, Request.Query, arguments);

                    if (mapper.BindBody && mapper.DynamicBody)
                    {
                        // Bind manually for now until I've fixed the dynamic type.

                        // Attempt to deserialize body from Json

                        Nancy.DynamicDictionary body = null;
                        if (Request.Body.Length > 0)
                        {
                            var buffer = new byte[Request.Body.Length];
                            Request.Body.Position = 0;
                            Request.Body.Read(buffer, 0, (int)Request.Body.Length);
                            string bodyStr = Encoding.Default.GetString(buffer);
                            Log.Debug("Got body data:\n{0}", bodyStr);

                            var serializer = new Nancy.Json.JavaScriptSerializer();
                            try
                            {
                                var bodyJson = serializer.DeserializeObject(bodyStr) as System.Collections.Generic.Dictionary <string, object>;
                                if (bodyJson != null)
                                {
                                    body = Nancy.DynamicDictionary.Create(bodyJson);
                                }
                            }
                            catch (System.ArgumentException)
                            {
                                // Just eat it.
                                Log.Warning("Got request with invalid json body for url: " + Request.Url);
                                return(null);
                            }
                        }

                        arguments.Add(body);
                    }

                    else if (mapper.BindBody)
                    {
                        // Bind specific type.

                        var config = new BindingConfig();
                        config.BodyOnly     = true;
                        config.IgnoreErrors = false;

                        // The Bind<> method exists on the ModuleExtension rather than the NancyModule.
                        var extensionMethods = typeof(ModuleExtensions).GetMethods();
                        var methodList       = new List <MethodInfo>(extensionMethods);

                        // Get correct generic bind method
                        var bindMethod    = methodList.Find(x => x.Name == "Bind" && x.GetParameters().Length == 1 && x.IsGenericMethod == true);
                        var genericMethod = bindMethod.MakeGenericMethod(mapper.BodyType);

                        // Bind our object.
                        var boundBody = genericMethod.Invoke(null, new object[] { this });
                        arguments.Add(boundBody);
                    }

                    try
                    {
                        object result = method.Invoke(service, arguments.ToArray());

                        return(Response.AsJson(result));
                    }
                    catch (TargetInvocationException e)
                    {
                        Log.Error(
                            "Invocation exception of uri: " + uri + "\n"
                            + "Exception: " + e.Message + "\n"
                            + "Callstack:" + e.StackTrace + "\n"
                            + "Inner: " + e.InnerException.Message + "\n"
                            + "Callstack: " + e.InnerException.StackTrace);

                        // TODO - A better way to unwrap this? Just throwing inner exception will cause an ObjectDisposedException
                        throw new Exception(e.InnerException.Message);
                    }
                };

                if (isPut)
                {
                    //Log.Debug("Adding PUT binding for {0}", uri);
                    Put[uri]  = lambda;
                    Post[uri] = lambda;
                }
                else
                {
                    //Log.Debug("Adding GET binding for {0}", uri);
                    Get[uri] = lambda;
                }
            }
        }
Ejemplo n.º 12
0
        public ServiceModule(ServiceManager serviceManager)
        {
            // Find all service methods having a ServiceGetContractAttribute attached to it.
            var bindQuery = from service in serviceManager.Services
                        from method in service.GetType().GetMethods()
                        from attribute in method.GetCustomAttributes(true)
                        where attribute is ServiceBase.ServiceGetContractAttribute
                        select new { service, method, attribute };

            foreach (var bindData in bindQuery)
            {
                var service = bindData.service;
                var method = bindData.method;
                var attribute = bindData.attribute;

                var contract = attribute as ServiceBase.ServiceGetContractAttribute;
                if (contract == null)
                    continue;

                bool isPut = contract is ServiceBase.ServicePutContractAttribute;

                var mapper = new ContractMapper("/" + service.Name + "/" + contract.uri, method);
                string uri = mapper.GetMappedUri();

                Func<dynamic, dynamic> lambda = parameters =>
                {
                    var arguments = new List<object>();

                    mapper.MapArguments(parameters, Request.Query, arguments);

                    if (mapper.BindBody && mapper.DynamicBody)
                    {
                        // Bind manually for now until I've fixed the dynamic type.

                        // Attempt to deserialize body from Json

                        Nancy.DynamicDictionary body = null;
                        if (Request.Body.Length > 0)
                        {
                            var buffer = new byte[Request.Body.Length];
                            Request.Body.Position = 0;
                            Request.Body.Read(buffer, 0, (int)Request.Body.Length);
                            string bodyStr = Encoding.Default.GetString(buffer);
                            Log.Debug("Got body data:\n{0}", bodyStr);

                            var serializer = new Nancy.Json.JavaScriptSerializer();
                            try
                            {
                                var bodyJson = serializer.DeserializeObject(bodyStr) as System.Collections.Generic.Dictionary<string, object>;
                                if (bodyJson != null)
                                    body = Nancy.DynamicDictionary.Create(bodyJson);
                            }
                            catch (System.ArgumentException)
                            {
                                // Just eat it.
                                Log.Warning("Got request with invalid json body for url: " + Request.Url);
                                return null;
                            }
                        }

                        arguments.Add(body);
                    }

                    else if (mapper.BindBody)
                    {
                        // Bind specific type.

                        var config = new BindingConfig();
                        config.BodyOnly = true;
                        config.IgnoreErrors = false;

                        // The Bind<> method exists on the ModuleExtension rather than the NancyModule.
                        var extensionMethods = typeof(ModuleExtensions).GetMethods();
                        var methodList = new List<MethodInfo>(extensionMethods);

                        // Get correct generic bind method
                        var bindMethod = methodList.Find(x => x.Name == "Bind" && x.GetParameters().Length == 1 && x.IsGenericMethod == true);
                        var genericMethod = bindMethod.MakeGenericMethod(mapper.BodyType);

                        // Bind our object.
                        var boundBody = genericMethod.Invoke(null, new object[] { this });
                        arguments.Add(boundBody);
                    }

                    try
                    {
                        object result = method.Invoke(service, arguments.ToArray());

                        return Response.AsJson(result);
                    }
                    catch (TargetInvocationException e)
                    {
                        Log.Error(
                            "Invocation exception of uri: " + uri + "\n"
                            + "Exception: " + e.Message + "\n"
                            + "Callstack:" + e.StackTrace + "\n"
                            + "Inner: " + e.InnerException.Message + "\n"
                            + "Callstack: " + e.InnerException.StackTrace);

                        // TODO - A better way to unwrap this? Just throwing inner exception will cause an ObjectDisposedException
                        throw new Exception(e.InnerException.Message);
                    }
                };

                if (isPut)
                {
                    //Log.Debug("Adding PUT binding for {0}", uri);
                    Put[uri] = lambda;
                    Post[uri] = lambda;
                }
                else
                {
                    //Log.Debug("Adding GET binding for {0}", uri);
                    Get[uri] = lambda;
                }
            }
        }
Ejemplo n.º 13
0
 private static void refreshJSON()
 {
     Nancy.Json.JavaScriptSerializer js = new Nancy.Json.JavaScriptSerializer();
     StatsJSON = js.Serialize(Stats);
     KeysJSON = js.Serialize(Stats.Keys);
     ActiveplayersJSON = js.Serialize(Stats.ActivePlayers);
     MemoryUsageJSON = js.Serialize(memoryUsage);
     RestartsJSON = js.Serialize(Stats.Restarts);
 }
Ejemplo n.º 14
0
        public void Integer_dictionary_values_are_Json_serialized_as_integers()
        {
            dynamic value = 42;
            var input = new DynamicDictionaryValue(value);

            var sut = new Nancy.Json.JavaScriptSerializer();
            var actual = sut.Serialize(input);

            actual.ShouldEqual(@"42");
        }
Ejemplo n.º 15
0
        public void String_dictionary_values_are_Json_serialized_as_strings()
        {
            dynamic value = "42";
            var input = new DynamicDictionaryValue(value);

            var sut = new Nancy.Json.JavaScriptSerializer();
            var actual = sut.Serialize(input);

            actual.ShouldEqual(@"""42""");
        }