コード例 #1
0
        public RazorExtensionSerializationTest()
        {
            var converters = new JsonConverterCollection();

            converters.Add(RazorExtensionJsonConverter.Instance);
            Converters = converters.ToArray();
        }
コード例 #2
0
        public ProjectSnapshotHandleSerializationTest()
        {
            var converters = new JsonConverterCollection();

            converters.RegisterRazorConverters();
            Converters = converters.ToArray();
        }
コード例 #3
0
        public void ProjectSnapshotHandleProxy_RoundTripsProperly()
        {
            // Arrange
            var tagHelpers = new[]
            {
                TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly").Build(),
                TagHelperDescriptorBuilder.Create("TestTagHelper2", "TestAssembly2").Build(),
            };
            var projectWorkspaceState = new ProjectWorkspaceState(tagHelpers);
            var expectedConfiguration = RazorConfiguration.Default;
            var expectedRootNamespace = "project";
            var handle = new ProjectSnapshotHandleProxy(new Uri("vsls://some/path/project.csproj"), RazorConfiguration.Default, expectedRootNamespace, projectWorkspaceState);
            var converterCollection = new JsonConverterCollection();

            converterCollection.RegisterRazorLiveShareConverters();
            var converters       = converterCollection.ToArray();
            var serializedHandle = JsonConvert.SerializeObject(handle, converters);

            // Act
            var deserializedHandle = JsonConvert.DeserializeObject <ProjectSnapshotHandleProxy>(serializedHandle, converters);

            // Assert
            Assert.Equal("vsls://some/path/project.csproj", deserializedHandle.FilePath.ToString());
            Assert.Equal(projectWorkspaceState, deserializedHandle.ProjectWorkspaceState);
            Assert.Equal(expectedConfiguration.ConfigurationName, deserializedHandle.Configuration.ConfigurationName);
            Assert.Equal(expectedConfiguration.Extensions.Count, deserializedHandle.Configuration.Extensions.Count);
            Assert.Equal(expectedConfiguration.LanguageVersion, deserializedHandle.Configuration.LanguageVersion);
            Assert.Equal(expectedRootNamespace, deserializedHandle.RootNamespace);
        }
コード例 #4
0
        public RazorConfigurationSerializationTest()
        {
            var converters = new JsonConverterCollection();

            converters.RegisterRazorConverters();
            Converters = converters.ToArray();
        }
コード例 #5
0
        public RazorConfigurationSerializationTest()
        {
            var converters = new JsonConverterCollection
            {
                RazorExtensionJsonConverter.Instance,
                RazorConfigurationJsonConverter.Instance
            };

            Converters = converters.ToArray();
        }
コード例 #6
0
 public SerializationTest()
 {
     var languageVersion = RazorLanguageVersion.Experimental;
     var extensions = new RazorExtension[]
     {
         new SerializedRazorExtension("TestExtension"),
     };
     Configuration = RazorConfiguration.Create(languageVersion, "Custom", extensions);
     ProjectWorkspaceState = new ProjectWorkspaceState(new[]
     {
         TagHelperDescriptorBuilder.Create("Test", "TestAssembly").Build(),
     },
     LanguageVersion.LatestMajor);
     var converterCollection = new JsonConverterCollection();
     converterCollection.RegisterRazorConverters();
     Converters = converterCollection.ToArray();
 }
コード例 #7
0
        public void ProcessRequest(HttpContext context)
        {
            var Response = context.Response;
            var Request  = context.Request;

            var execTimeNow = new TimeSpan(DateTime.Now.Ticks);

            if (bool.Parse(getWebConfigValue("jsonbridge.AuthEnabled").ToString()) && String.IsNullOrEmpty(Request.Headers["Authorization"]))
            {
                Response.Write(JsonConvert.SerializeObject(new InvokationErrorType {
                    message = "Authorization failed. No Authorization HTTP headers sent", execTime = (new TimeSpan(DateTime.Now.Ticks - execTimeNow.Ticks).TotalSeconds)
                }));
                return;
            }

            if (bool.Parse(getWebConfigValue("jsonbridge.AuthEnabled").ToString()) && !String.IsNullOrEmpty(Request.Headers["Authorization"]))
            {
                var authHeader = Request.Headers["Authorization"];
                var authMethod = Request.Headers["Authorization"].Split(' ')[0].ToLower();

                var assembly = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "bin\\JBAP." + authMethod + ".dll");
                var type     = assembly.GetType("JBAP." + authHeader.Split(' ')[0]);
                if (type == null)
                {
                    Response.Write(JsonConvert.SerializeObject(new InvokationErrorType
                    {
                        message  = "Authorization failed. Wrong Authorization handler name",
                        execTime = (new TimeSpan(DateTime.Now.Ticks - execTimeNow.Ticks).TotalSeconds)
                    }));
                    return;
                }
                var obj            = Activator.CreateInstance(type);
                var jbapClassName  = authHeader.Split(' ')[0];
                var validateArgs   = authHeader.Substring(jbapClassName.Length + 1);
                var validateResult = (bool)type.InvokeMember("validate", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, new object[] { validateArgs });
                if (validateResult)
                {
                    return;
                }
                Response.Write(JsonConvert.SerializeObject(new InvokationErrorType
                {
                    message  = "Authorization failed",
                    execTime = (new TimeSpan(DateTime.Now.Ticks - execTimeNow.Ticks).TotalSeconds)
                }));
                return;
            }
            if (context.Application["__assemblies"] == null)
            {
                context.Application["__assemblies"] = browseAssemblies();
            }

            var loaddedAssemblies = (Dictionary <string, Assembly>)context.Application["__assemblies"];

            switch (classpath.ToLower())
            {
            case "jquery.jsonbridge.js":
                Response.ContentType = ContentTypes.JAVASCRIPT;
                Response.Write(getEmbeddedContent("jquery.jsonbridge.js"));
                break;

            case "_browse":
                var listOfAssemblies = loaddedAssemblies.Select(assembly => assembly.Value.FullName.Split(',')[0]).ToList();

                Response.ContentType = ContentTypes.JSON;
                Response.Write(JsonConvert.SerializeObject(new InvokationResultType()
                {
                    result   = listOfAssemblies,
                    execTime = (new TimeSpan(DateTime.Now.Ticks - execTimeNow.Ticks).TotalSeconds)
                }));
                break;

            case "_browseclasses":
                var listOfClasses = new List <string>();

                try
                {
                    foreach (var assembly in loaddedAssemblies)
                    {
                        foreach (var type in assembly.Value.GetTypes())
                        {
                            listOfClasses.Add(type.FullName);
                        }
                    }
                }
                catch (Exception)
                {
                    //Response.Write(ex.ToString() + "<hr/>");
                }

                Response.ContentType = ContentTypes.JSON;
                Response.Write(JsonConvert.SerializeObject(new InvokationResultType
                {
                    result   = listOfClasses,
                    execTime = (new TimeSpan(DateTime.Now.Ticks - execTimeNow.Ticks).TotalSeconds)
                }));
                break;

            default:
                if (!String.IsNullOrEmpty(method))
                {
                    if (isValidClass(classpath))
                    {
                        if (method.ToLower() == "_methods")
                        {
                            // Browse for all methods within a class
                            Response.Write(JsonConvert.SerializeObject(browseClassMethods(classpath)));
                        }
                        else
                        {
                            // Class path is valid, check if method is valid

                            var possibleMethods = new List <MethodInfo>();

                            possibleMethods = getOverloadsByName(getClassAssemblyQualifiedName(classpath), method);

                            if (possibleMethods.Count == 0)
                            {
                                Response.Write(JsonConvert.SerializeObject(new InvokationErrorType()
                                {
                                    execTime = (new TimeSpan(DateTime.Now.Ticks - execTimeNow.Ticks).TotalSeconds),
                                    message  = classpath + " does not contain any method " + method
                                }));
                                return;
                            }

                            if (Request.RequestType == "POST")
                            {
                                // Check if user actually sent any params by analizyng inout stream
                                if (Request.InputStream.Length == 0)
                                {
                                    Response.Write("Request body missing");
                                }
                                else
                                {
                                    var stream      = new StreamReader(Request.InputStream);
                                    var requestBody = stream.ReadToEnd();

                                    var jsonSettings = new JsonSerializerSettings
                                    {
                                        DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                                        DateFormatHandling   = DateFormatHandling.IsoDateFormat,
                                        DateFormatString     = "{0:s}",
                                        DateParseHandling    = DateParseHandling.DateTime
                                    };

                                    var invokeParams = JsonConvert.DeserializeObject <object[]>(requestBody, jsonSettings);

                                    for (var index = possibleMethods.Count - 1; index >= 0; index--)
                                    {
                                        if (possibleMethods[index].GetParameters().Length != invokeParams.Length)
                                        {
                                            possibleMethods.RemoveAt(index);
                                        }
                                    }
                                    switch (possibleMethods.Count)
                                    {
                                    case 0:
                                        Response.Write(JsonConvert.SerializeObject(new InvokationErrorType()
                                        {
                                            execTime = (new TimeSpan(DateTime.Now.Ticks - execTimeNow.Ticks).TotalSeconds),
                                            message  = "There is no overload of the method with the specified number of params"
                                        }));
                                        return;

                                    case 1:
                                    {
                                        var methodInfo = possibleMethods[0];

                                        var correctParams = new List <object>();

                                        for (var index = 0; index < invokeParams.Length; index++)
                                        {
                                            if (invokeParams[index].GetType().FullName != "Newtonsoft.Json.Linq.JObject")
                                            {
                                                correctParams.Add(invokeParams[index]);
                                            }
                                            else
                                            {
                                                var paramType = methodInfo.GetParameters()[index].ParameterType;

                                                var serializer = new JsonSerializer();

                                                var o = serializer.Deserialize(new JTokenReader((JObject)invokeParams[index]), paramType);

                                                correctParams.Add(o);
                                            }
                                        }

                                        var invokeResult = invokeAssemblyMethod(classpath, methodInfo, correctParams.ToArray());

                                        Response.ContentType = ContentTypes.JSON;

                                        //Response.Write(JsonConvert.SerializeObject(invokeResult, new JavaScriptDateTimeConverter()));
                                        var converters = new JsonConverterCollection
                                        {
                                            new StringEnumConverter(),
                                            new IsoDateTimeConverter()
                                        };
                                        Response.Write(JsonConvert.SerializeObject(invokeResult, converters.ToArray()));
                                    }
                                    break;

                                    default:
                                    {
                                        //Response.Write("Before anything else");
                                        //return;
                                        //trying to build the possibly correct argument list for each overload
                                        var correctFinalParams = new List <object>();
                                        var debug = "";
                                        for (var index = possibleMethods.Count - 1; index >= 0; index--)
                                        {
                                            var correctParams = new List <object>();
                                            var validParams   = true;
                                            //try to deserialize each possible type. if it f***s up, it's clearly not the overload we're looking for
                                            //Response.Write("Before the loop");
                                            //return;

                                            for (var index2 = 0; index2 < invokeParams.Length; index2++)
                                            {
                                                debug += "Front of the loop; ";
                                                //return;
                                                if (invokeParams[index2].GetType().FullName != "Newtonsoft.Json.Linq.JObject")
                                                {
                                                    correctParams.Add(invokeParams[index2]);
                                                    debug += "Added normal type to param arr; ";
                                                }
                                                else
                                                {
                                                    var paramType = possibleMethods[index].GetParameters()[index2].ParameterType;
                                                    debug += "Proceeding to deserialize from " + paramType.ToString() + "; ";
                                                    var serializer = new JsonSerializer();
                                                    // Response.Write(debug);
                                                    // return;
                                                    var o = serializer.Deserialize(new JTokenReader((JObject)invokeParams[index2]), paramType);
                                                    debug += "Done serializing; ";
                                                    if (o == null)
                                                    {
                                                        //couldn't deserialize to this type, so it's not the good overload
                                                        validParams = false;
                                                        debug      += "Failed serializing; ";
                                                        break;
                                                    }
                                                    correctParams.Add(o);
                                                }
                                                debug += "End of the loop; ";
                                            }
                                            //Response.Write(debug);
                                            //return;
                                            if (!validParams)
                                            {
                                                possibleMethods.RemoveAt(index);
                                                debug += "Not a valid overload; ";
                                                continue;
                                            }

                                            var curMethodParamInfoArr = possibleMethods[index].GetParameters();
                                            var curMethodTypeArr      = curMethodParamInfoArr.Select(param => param.ParameterType).ToList();

                                            //since all complex types are ok now, we've gotta check whether all types are matching. If they do, it's a valid overload
                                            for (var index2 = 0; index2 < curMethodTypeArr.Count; index2++)
                                            {
                                                debug += "Checking " + correctParams[index2].GetType() + " and " + curMethodTypeArr[index2] + ": ";
                                                if (correctParams[index2].GetType() == curMethodTypeArr[index2])
                                                {
                                                    debug += "equal; ";
                                                }
                                                else if ((correctParams[index2].GetType() == Type.GetType("System.Int64")) && isValidInt32(Int64.Parse(correctParams[index2].ToString())) && (curMethodTypeArr[index2] == Type.GetType("System.Int32")))
                                                {
                                                    debug += "Could cast from Int64 to Int32;";
                                                }
                                                else
                                                {
                                                    debug      += "different; ";
                                                    validParams = false;
                                                    break;
                                                }
                                            }

                                            if (!validParams)
                                            {
                                                possibleMethods.RemoveAt(index);
                                                debug += "Not a valid overload; ";
                                                continue;
                                            }
                                            correctFinalParams = correctParams;
                                        }
                                        //Response.Write(debug);
                                        //return;
                                        if (possibleMethods.Count == 0)
                                        {
                                            Response.Write("No valid overload afterall.");
                                        }
                                        else if (possibleMethods.Count >= 2)
                                        {
                                            Response.Write(JsonConvert.SerializeObject(new InvokationErrorType()
                                                {
                                                    execTime = (new TimeSpan(DateTime.Now.Ticks - execTimeNow.Ticks).TotalSeconds),
                                                    message  = "Ambiguous call: " + possibleMethods.Count + " valid overloads"
                                                }));
                                        }
                                        else
                                        {
                                            var invokeResult = invokeAssemblyMethod(classpath, possibleMethods[0], correctFinalParams.ToArray());

                                            Response.ContentType = ContentTypes.JSON;

                                            var converters = new JsonConverterCollection
                                            {
                                                new StringEnumConverter(),
                                                new IsoDateTimeConverter()
                                            };
                                            Response.Write(JsonConvert.SerializeObject(invokeResult, converters.ToArray()));
                                        }
                                    }
                                    break;
                                    }
                                }
                            }
                            else
                            {
                                var methodInfo = possibleMethods[0];
                                if (methodInfo.GetParameters().Length > 0)
                                {
                                    Response.Write(JsonConvert.SerializeObject(new InvokationErrorType
                                    {
                                        execTime = (new TimeSpan(DateTime.Now.Ticks - execTimeNow.Ticks).TotalSeconds),
                                        message  = "This method requires " + methodInfo.GetParameters().Length + " parameter(s)"
                                    }));
                                }
                                else
                                {
                                    var invokeResult = invokeAssemblyMethod(classpath, methodInfo, null);

                                    var converters = new JsonConverterCollection
                                    {
                                        new StringEnumConverter(),
                                        new JavaScriptDateTimeConverter()
                                    };

                                    Response.Write(JsonConvert.SerializeObject(invokeResult, converters.ToArray()));
                                }
                            }
                        }
                    }
                    else
                    {
                        // User specified wrong class path, should be valid type name
                        Response.Write(JsonConvert.SerializeObject(new InvokationErrorType
                        {
                            execTime = (new TimeSpan(DateTime.Now.Ticks - execTimeNow.Ticks).TotalSeconds),
                            message  = "Invalid class path: " + classpath
                        }));
                    }
                }
                else
                {
                    // Class specified but method is missing
                    //Response.Write("--not implemented, " + classpath);
                    Response.Write(JsonConvert.SerializeObject(browseClassMethods(classpath)));
                }
                break;
            }
        }