コード例 #1
0
 public void Test_ConditionalNST_Serialization()
 {
     using (var stream = new MemoryStream())
     {
         var formater = new JSONSerializer();
         formater.Serialize(stream, _testCase);
         stream.Seek(0, SeekOrigin.Begin);
         Console.WriteLine(new StreamReader(stream).ReadToEnd());
     }
 }
コード例 #2
0
        public void EmotionalAppraisal_Serialization_Test()
        {
            var asset = BuildTestAsset();

            using (var stream = new MemoryStream())
            {
                var formater = new JSONSerializer();
                formater.Serialize(stream, asset);
                stream.Seek(0, SeekOrigin.Begin);
                Console.WriteLine(new StreamReader(stream).ReadToEnd());
            }
        }
コード例 #3
0
        public static void CustomClassSerializationTest()
        {
            SerializationServices.AssemblyLoader = assemblyLoader;
            SerializationServices.InstanceFactory = factory;

            var value = new SerializationTestClass();

            var serializer = new JSONSerializer();
            var json = serializer.SerializeToJson(value);
            json.Write(Console.Out, true);
            var other = serializer.DeserializeFromJson<SerializationTestClass>(json);

            Assert.IsNull(other.VolatileField);
        }
コード例 #4
0
        public void Test_ConditionalNST_Deserialization()
        {
            using (var stream = new MemoryStream())
            {
                var writer = new StreamWriter(stream);
                writer.Write(DESERIALIZATION_TEST_CASE);
                writer.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                var formater = new JSONSerializer();
                var obj = formater.Deserialize(stream);
                Assert.AreEqual(obj, _testCase);
            }
        }
コード例 #5
0
        public string SelectSeatByMessager(string studentNo, string seatNo, string roomNo)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.SelectSeatByMessager(studentNo, seatNo, roomNo);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #6
0
        public string CheckUser(string loginId, string password)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.CheckUser(loginId, password);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #7
0
        public string ConfirmSeat(string besapeakNo)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.ConfirmSeat(besapeakNo);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #8
0
        public string GetSeatBespeakInfo(string seatNo, string roomNo, string bespeakTime)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.GetSeatBespeakInfo(seatNo, roomNo, bespeakTime);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #9
0
        public string QRcodeOperation(string codeStr, string studentNo)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.QRcodeOperation(codeStr, studentNo);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #10
0
        public string CancelBesapeakByCardNo(string cardNo, string bespeakDate)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.CancelBesapeakByCardNo(cardNo, bespeakDate);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #11
0
        public string GetOftenSeat(string studentNo, int seatCount, int dayCount)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.GetOftenSeat(studentNo, seatCount, dayCount);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #12
0
 //serialize blackboard variables to json
 void ISerializationCallbackReceiver.OnBeforeSerialize()
 {
     if (_objectReferences != null && _objectReferences.Any(o => o != null))
     {
         hasDeserialized = false;
     }
                 #if UNITY_EDITOR
     if (JSONSerializer.applicationPlaying)
     {
         return;
     }
     _objectReferences     = new List <UnityEngine.Object>();
     _serializedBlackboard = JSONSerializer.Serialize(typeof(BlackboardSource), _blackboard, false, _objectReferences);
                 #endif
 }
コード例 #13
0
        public string GetAllRoomNowState()
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.GetAllRoomNowState();
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #14
0
        public string GetViolationLog(string studentNo, int pageIndex, int pageSize)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.GetViolationLog(studentNo, pageIndex, pageSize);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #15
0
ファイル: Listener.cs プロジェクト: cowtrix/musicvis
 public void OnBeforeSerialize()
 {
     if (CurrentListener != null)
     {
         ListenerJSON = new DerivedComponentJsonDataRow();
         ListenerJSON.AssemblyQualifiedName = CurrentListener.GetType().AssemblyQualifiedName;
         ListenerJSON.SerializedObjects     = new List <UnityEngine.Object>();
         ListenerJSON.JsonText = JSONSerializer.Serialize(CurrentListener.GetType(), CurrentListener,
                                                          false, ListenerJSON.SerializedObjects);
     }
     else
     {
         ListenerJSON = null;
     }
 }
コード例 #16
0
        public ActionResult GetViolationLog()
        {
            ViewBag.User = Session["User"] as tb_User;
            string msg;

            AppWebService.BasicAPI.GetViolationLog(ViewBag.User.SchoolNo, ViewBag.User.StudentNo, 0, 20, out msg);
            List <J_GetViolationLog> list = JSONSerializer.JSONStringToList <J_GetViolationLog>(msg);

            ViewBag.List = list;
            AppWebService.BasicAPI.GetBlacklist(ViewBag.User.SchoolNo, ViewBag.User.StudentNo, 0, 20, out msg);
            List <J_GetBlacklist> listBlack = JSONSerializer.JSONStringToList <J_GetBlacklist>(msg);

            ViewBag.ListBlack = listBlack;
            return(View());
        }
コード例 #17
0
        ///Saves the Blackboard in PlayerPrefs in the provided saveKey. You can use this for a Save system
        public string Save(string saveKey)
        {
            var json = this.Serialize();
            Dictionary <string, string> data = new Dictionary <string, string>();

            if (Parent != null)
            {
                data.Add("parent", Parent.Serialize());
            }
            data.Add("struct", json);
            var save = JSONSerializer.Serialize(typeof(Dictionary <string, string>), data, true);

            PlayerPrefs.SetString(saveKey, save);
            return(save);
        }
コード例 #18
0
 //serialize exposed parameters
 void ISerializationCallbackReceiver.OnBeforeSerialize()
 {
     if (exposedParameters == null || exposedParameters.Count == 0)
     {
         _serializedExposedParameters = null;
         return;
     }
     _serializedExposedParameters = new SerializationPair[exposedParameters.Count];
     for (var i = 0; i < _serializedExposedParameters.Length; i++)
     {
         var serializedParam = new SerializationPair();
         serializedParam._json           = JSONSerializer.Serialize(typeof(ExposedParameter), exposedParameters[i], serializedParam._references);
         _serializedExposedParameters[i] = serializedParam;
     }
 }
コード例 #19
0
 public BackupStatusReport GetBackupStatus(Guid siteId)
 {
     try
     {
         BitplateBackupServiceReference.BackupServiceClient backupClient = new BitplateBackupServiceReference.BackupServiceClient();
         return(JSONSerializer.Deserialize <BackupStatusReport>(backupClient.GetBackupStatus(siteId), true));
     }
     catch (Exception ex)
     {
         BackupStatusReport exceptioReport = new BackupStatusReport();
         exceptioReport.BackupCompleted = true;
         exceptioReport.StatusMessage   = "Kan BitBackupService niet vinden.\r\n" + ex.ToString();
         return(exceptioReport);
     }
 }
コード例 #20
0
        public string SubmitBesapeskSeat(string seatNo, string roomNo, string studentNo, string besapeakTime, bool isNowBesapeak)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.SubmitBesapeskSeat(seatNo, roomNo, studentNo, besapeakTime, isNowBesapeak);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #21
0
ファイル: DB.cs プロジェクト: AlexErohin/test_back
        public string GetDataByCode(string table, string code)
        {
            string str = GetData(table);

            List <JObject> json = JSONSerializer.Deserialize <List <JObject> >(str);

            List <JObject> arr = json.FindAll(delegate(JObject b){ return(((JValue)b["code"]).Value + "" == code); });

            if (arr.Count == 0)
            {
                return("[]");
            }

            return("[" + arr[0].ToString() + "]");
        }
コード例 #22
0
        public void Unmarshal_Composite_Struct_Produces_Valid_Result()
        {
            var jsonSerializer = new JSONSerializer();
            var t1             = jsonSerializer.Unmarshal(Encoding.UTF8.GetBytes("{\"arg1\":\"bla\",\"arg2\":19,\"arg3\":{\"arg3\":\"ola\",\"arg4\":400}}"), typeof(TestClass1));

            Assert.Equal(new TestClass1
            {
                Arg1 = "bla",
                Arg2 = 19,
                Arg3 = new TestClass2
                {
                    Arg3 = "ola",
                    Arg4 = 400
                }
            }, t1);
        }
コード例 #23
0
        public ActionResult GetReserveLog()
        {
            ViewBag.User = Session["User"] as tb_User;
            string msg;

            if (AppWebService.BasicAPI.GetBesapsekLog(ViewBag.User.SchoolNo, ViewBag.User.StudentNo, 0, 20, out msg))
            {
                List <J_GetBesapsekLog> list = JSONSerializer.JSONStringToList <J_GetBesapsekLog>(msg);
                ViewBag.List = list;
                return(View());
            }
            else
            {
                return(Content(msg));
            }
        }
コード例 #24
0
        public string GetUserNowState(string studentNo, bool isCheckCode)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                string r = obtainProxy.GetUserNowStateV2(studentNo, isCheckCode);
                //SeatManage.SeatManageComm.WriteLog.Write("r"+r);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #25
0
        internal async Task <T> Post <T>(string url, dynamic requestData = null, bool isOAuthTokenRequest = false) where T : new()
        {
            var request = CreateHttpRequest(url, HttpMethod.Post, !isOAuthTokenRequest);

            if (isOAuthTokenRequest)
            {
                request.Content = new FormUrlEncodedContent(requestData);
            }
            else
            {
                var jsonString = JSONSerializer.Serilaize(requestData);
                request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            }

            return(await Request <T>(request));
        }
コード例 #26
0
ファイル: TypePrefs.cs プロジェクト: poqis-family/FAFproject
        ///<summary>Will try load from file found in DefaultEditorResources</summary>
        static bool TryLoadSyncFile(ref List <Type> result)
        {
            var absPath = SyncFilePath();

            if (!string.IsNullOrEmpty(absPath))
            {
                var json = System.IO.File.ReadAllText(absPath);
                var temp = JSONSerializer.Deserialize <List <Type> >(json);
                if (temp != null)
                {
                    result = temp;
                    return(true);
                }
            }
            return(false);
        }
コード例 #27
0
 public unsafe void AppRequest(string message, List <string> to, string data, string title, Action <bool, AppRequestResult> callback = null)
 {
     if (CheckAndSetActionExecuting())
     {
         OnActionCallback = delegate(bool success, string json)
         {
             AppRequestResult arg = null;
             if (success)
             {
                 arg = JSONSerializer.Deserialize <AppRequestResult>(json);
             }
             callback(success, arg);
         };
         FB.AppRequest(message, (IEnumerable <string>)to, (IEnumerable <object>)null, (IEnumerable <string>)null, (int?)null, data, title, new FacebookDelegate <IAppRequestResult>((object)this, (IntPtr)(void *) /*OpCode not supported: LdFtn*/));
     }
 }
コード例 #28
0
        public static void Main(string[] args)
        {
            var stapler = new Staplers
            {
                color      = "Red",
                brand      = "Swingline",
                stapleSize = 22
            };

            string filePath   = "C:\Users\BigJimbo\Desktop\AllMyStaplers.csv";
            string jsonString = JSONSerializer.Serialize(stapler);

            File.WriteAllText(filePath, jsonString);

            Console.WriteLine(File.ReadAllText(filePath));
        }
コード例 #29
0
        public Post getVKPost(string accessToken, string groupId, int numberOfPost)
        {
            Leaf.xNet.HttpResponse postResponse = null;
            Post result = new Post();

            using (var postRequest = new Leaf.xNet.HttpRequest())
            {
                postRequest.UserAgent = Http.ChromeUserAgent();
                postResponse          = postRequest.Get(
                    String.Format("https://api.vk.com/method/wall.get?extended=1&owner_id=-{0}&count=1&offset={1}&access_token={2}&v={3}"
                                  , groupId, numberOfPost, accessToken, version));
                result = JSONSerializer.getPost(postResponse.ToString());
                Thread.Sleep(200);
                return(result);
            }
        }
コード例 #30
0
        public string GetUserInfo(string studentNo)
        {
            if (headerCheck.CheckSoapHeader(myHeader, true))
            {
                IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy(myHeader.SchoolNum);
                // IMobileAppDataObtianProxy obtainProxy = new MobileAppDataWCFProxy("20171203");
                string r = obtainProxy.GetUserInfo(studentNo);
                obtainProxy.Dispose();
                return(r);
            }
            AJM_HandleResult result = new AJM_HandleResult();

            result.Result = false;
            result.Msg    = "权限验证失败!";
            return(JSONSerializer.Serialize(result));
        }
コード例 #31
0
 public void OnBeforeSerialize()
 {
     ComponentsJSON.Clear();
     foreach (var proceduralLayerComponent in Components)
     {
         var type    = proceduralLayerComponent.GetType();
         var jsonRow = new Common.Serialization.DerivedComponentJsonDataRow()
         {
             AssemblyQualifiedName = type.AssemblyQualifiedName,
             SerializedObjects     = new List <Object>(),
         };
         jsonRow.JsonText = JSONSerializer.Serialize(type, proceduralLayerComponent, false,
                                                     jsonRow.SerializedObjects);
         ComponentsJSON.Add(jsonRow);
     }
 }
コード例 #32
0
        /// <summary>
        /// 获取预约记录
        /// </summary>
        /// <param name="studentNo">学号</param>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <returns></returns>
        public string GetBesapsekLog(string studentNo, int pageIndex, int pageSize)
        {
            AJM_HandleResult result = new AJM_HandleResult();

            try
            {
                if (string.IsNullOrEmpty(studentNo))
                {
                    result.Result = false;
                    result.Msg    = "学号不能为空!";
                    return(JSONSerializer.Serialize(result));
                }
                if (pageIndex < 0 || pageSize < 0)
                {
                    result.Result = false;
                    result.Msg    = "页数和每页显示数目必须大于等于0";
                    return(JSONSerializer.Serialize(result));
                }
                List <BespeakLogInfo> logInfos       = SeatManageDateService.GetBespeakLogsByPage(studentNo, pageIndex, pageSize);
                List <AJM_BespeakLog> ajmBespeakLogs = new List <AJM_BespeakLog>();
                for (int i = 0; i < logInfos.Count; i++)
                {
                    AJM_BespeakLog ajmBespeakLog = new AJM_BespeakLog();
                    ajmBespeakLog.Id             = logInfos[i].BsepeaklogID;
                    ajmBespeakLog.BookTime       = logInfos[i].BsepeakTime.ToString("yyyy-MM-dd HH:mm:ss");
                    ajmBespeakLog.IsValid        = logInfos[i].BsepeakState == BookingStatus.Waiting;
                    ajmBespeakLog.Remark         = logInfos[i].Remark;
                    ajmBespeakLog.RoomName       = logInfos[i].ReadingRoomName;
                    ajmBespeakLog.RoomNo         = logInfos[i].ReadingRoomNo;
                    ajmBespeakLog.SeatShortNo    = logInfos[i].ShortSeatNum;
                    ajmBespeakLog.SeatNo         = logInfos[i].SeatNo;
                    ajmBespeakLog.SubmitDateTime = logInfos[i].SubmitTime.ToString("yyyy-MM-dd HH:mm:ss");
                    ajmBespeakLog.CancelTime     = logInfos[i].CancelTime.ToString("yyyy-MM-dd HH:mm:ss");
                    ajmBespeakLogs.Add(ajmBespeakLog);
                }
                result.Result = true;
                result.Msg    = JSONSerializer.Serialize(ajmBespeakLogs);
                return(JSONSerializer.Serialize(result));
            }
            catch (Exception ex)
            {
                WriteLog.Write(string.Format("获取预约记录遇到异常:{0}", ex.Message));
                result.Result = false;
                result.Msg    = "获取预约记录执行异常!";
                return(JSONSerializer.Serialize(result));
            }
        }
コード例 #33
0
        private void LoadButton_Click(object sender, EventArgs e)
        {
            if (FilesList.SelectedIndex > -1)
            {
                switch (SerializerTypes.SelectedItem)
                {
                case Serializers.Binary:
                    if (FilesList.SelectedItem.ToString().Contains("Transport"))
                    {
                        BinarySerializer serializer = new BinarySerializer();
                        Transport.Cars = ConvertData.ListToDict(serializer.Load <Transport>(files[FilesList.SelectedIndex]));
                    }
                    else if (FilesList.SelectedItem.ToString().Contains("Routes"))
                    {
                        BinarySerializer serializer = new BinarySerializer();
                        Route.Routes = ConvertData.ListToDict(serializer.Load <Route>(files[FilesList.SelectedIndex]));
                    }
                    break;

                case Serializers.XML:
                    if (FilesList.SelectedItem.ToString().Contains("Transport"))
                    {
                        XMLSerializer serializer = new XMLSerializer();
                        Transport.Cars = ConvertData.ListToDict(serializer.Load <Transport>(files[FilesList.SelectedIndex]));
                    }
                    else if (FilesList.SelectedItem.ToString().Contains("Routes"))
                    {
                        XMLSerializer serializer = new XMLSerializer();
                        Route.Routes = ConvertData.ListToDict(serializer.Load <Route>(files[FilesList.SelectedIndex]));
                    }
                    break;

                case Serializers.JSON:
                    if (FilesList.SelectedItem.ToString().Contains("Transport"))
                    {
                        JSONSerializer serializer = new JSONSerializer();
                        Transport.Cars = ConvertData.ListToDict(serializer.Load <Transport>(files[FilesList.SelectedIndex]));
                    }
                    else if (FilesList.SelectedItem.ToString().Contains("Routes"))
                    {
                        JSONSerializer serializer = new JSONSerializer();
                        Route.Routes = ConvertData.ListToDict(serializer.Load <Route>(files[FilesList.SelectedIndex]));
                    }
                    break;
                }
            }
        }
コード例 #34
0
 public void TestInitialize()
 {
     dataFiller = new RandomDataFiller()
     {
         NumberOfBooks       = 1000,
         NumberOfBookStates  = 1000,
         NumberOfBookReaders = 1000,
         NumberOfEvents      = 1000
     };
     context = new DataContext();
     dataFiller.Fill(ref context);
     fileName       = "json_data.json";
     jsonSerializer = new JSONSerializer()
     {
         FileName = fileName
     };
 }
コード例 #35
0
        /// <summary>
        /// Returns an error response to the client from a callback. Code
        /// should exit after this call.
        /// </summary>
        /// <param name="ErrorMessage"></param>
        public void WriteErrorResponse(string errorMessage, string stackTrace)
        {
            CallbackException Error = new CallbackException();
            Error.message = errorMessage;
            Error.isCallbackError = true;
            Error.stackTrace = stackTrace;

            JSONSerializer Serializer = new JSONSerializer();
            string result = null;
            SerializationUtils.SerializeObject(Error, out result);

            HttpResponse Response = HttpContext.Current.Response;
            Response.ContentType = WebResources.STR_XmlContentType;

            Response.TrySkipIisCustomErrors = true;

            if (Response.StatusCode == 200)
                Response.StatusCode = 500;

            Response.Write(result);
            //HttpContext.Current.ApplicationInstance.CompleteRequest();
            Response.End();
        }
コード例 #36
0
        /// <summary>
        /// Generic method that handles processing a Callback request by routing to
        /// a method in a provided target object.
        /// 
        /// </summary>
        /// <param name="target">The target object that is to be called. If null this is used</param>
        public void ProcessCallbackMethodCall(object target, string methodToCall)
        {
            if (target == null)
                target = this;

            HttpRequest Request = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;
            Response.Charset = null;

            // check for Route Data method name
            if (target is CallbackHandler)
            {
                var routeData = ((CallbackHandler)target).RouteData;                
                if (routeData != null)
                    methodToCall = ((CallbackHandlerRouteHandler)routeData.RouteHandler).MethodName;
            }

            CallbackMethodProcessorHelper helper = new CallbackMethodProcessorHelper(this);
            
            List<string> parameterList = null;
            
            string contentType = Request.ContentType.ToLower();

            // Allow for a single JSON object to be POSTed rather than POST variables
            if (contentType.StartsWith(WebResources.STR_JavaScriptContentType) ||
                contentType.StartsWith(WebResources.STR_JsonContentType))
            {
                if (string.IsNullOrEmpty(methodToCall))
                    methodToCall = Request.Params["Method"];

                if (string.IsNullOrEmpty(methodToCall))
                {
                    WriteErrorResponse("No method to call specified.",null);
                    return;
                }

                // Pass a Parameter List with our JSON encoded parameters
                parameterList = new List<string>();

                if (Request.ContentLength > 0L)
                {
                    // Pick up single unencoded JSON parameter
                    string singleParm;
                    using (StreamReader sr = new StreamReader(Request.InputStream))
                    {
                        singleParm = sr.ReadToEnd();
                    }

                    if (!string.IsNullOrEmpty(singleParm))
                        parameterList.Add(singleParm);
                }
            }
            // Post AjaxMethodCallback style interface            
            else if (contentType.StartsWith(WebResources.STR_UrlEncodedContentType) && Request.Params["CallbackMethod"] != null)
                // Only pick up the method name - Parameters are parsed out of POST buffer during method calling
                methodToCall = Request.Params["CallbackMethod"];                
            else
            {
                JsonPMethod = Request.QueryString["jsonp"] ?? Request.QueryString["callback"];

                // Check for querystring method parameterList
                if (string.IsNullOrEmpty(methodToCall)) 
                    methodToCall = Request.QueryString["Method"];               

                // No method - no can do
                if (string.IsNullOrEmpty(methodToCall))
                {
                    WriteErrorResponse("No method to call specified.",null);
                    return;
                }
            }

            // Explicitly set the content type here - set here so the method 
            // can override it if it so desires
            Response.ContentType = WebResources.STR_JsonContentType;
            
            object result = null;
            string stringResult = null;
            CallbackMethodAttribute attr = new CallbackMethodAttribute();
            try
            {
                if (parameterList != null)
                    // use the supplied parameter list
                    result = helper.ExecuteMethod(methodToCall, target, parameterList.ToArray(),
                        CallbackMethodParameterType.Json, ref attr);
                else
                // grab the info out of QueryString Values or POST buffer during parameter parsing 
                // for optimization
                    result = helper.ExecuteMethod(methodToCall, target, null,
                        CallbackMethodParameterType.Json, ref attr);
            }
            catch (CallbackException ex)
            {
                WriteErrorResponse(ex.Message,
                                  (HttpContext.Current.IsDebuggingEnabled ? ex.StackTrace : null),
                                  ex.StatusCode);
            }
            catch (Exception ex)
            {                
                WriteErrorResponse(ex.GetBaseException().Message,
                                  ( HttpContext.Current.IsDebuggingEnabled ? ex.StackTrace : null ) );
                return;
            }

            // Special return type handling: Stream, Bitmap, byte[] and raw string results
            // are converted and returned directly
            HandleSpecialReturnTypes(result, attr, Request, Response);
            
            // Standard json formatting            
            try
            {
                JSONSerializer Serializer = new JSONSerializer();
                Serializer.DateSerializationMode = JsonDateEncoding;               

                // In debug mode show nicely formatted JSON 
                // In release normal packed JSON is used
                if (HttpContext.Current.IsDebuggingEnabled)
                    Serializer.FormatJsonOutput = true;

                if (result == null)
                    stringResult = "null";
                else
                    stringResult = Serializer.Serialize(result);
            }            
            catch (Exception ex)
            {
                WriteErrorResponse(ex.Message, HttpContext.Current.IsDebuggingEnabled ? ex.StackTrace : null);
                return;
            }
            
           
            if (!string.IsNullOrEmpty(JsonPMethod))            
                stringResult = JsonPMethod + "( " + stringResult + " );";
            
            Response.Write(stringResult);
            Response.End();
        }
コード例 #37
0
        /// <summary>
        /// Returns an error response to the client from a callback. Code
        /// should exit after this call.
        /// </summary>
        /// <param name="ErrorMessage"></param>
        public void WriteErrorResponse(string errorMessage, string stackTrace, int statusCode = 500)
        {
            CallbackErrorResponseMessage Error = new CallbackErrorResponseMessage(errorMessage);
            Error.detail = stackTrace;
            Error.statusCode = statusCode;

            JSONSerializer Serializer = new JSONSerializer( SupportedJsonParserTypes.JavaScriptSerializer);            
            string result = Serializer.Serialize(Error);

            if (!string.IsNullOrEmpty(JsonPMethod))
                result = JsonPMethod + "( " + result + " );";

            HttpResponse Response = HttpContext.Current.Response;
            Response.ContentType = WebResources.STR_JsonContentType;

            Response.TrySkipIisCustomErrors = true;
            
            // override status code but only if it wasn't set already
            if (Response.StatusCode == 200)
                Response.StatusCode = statusCode;
            
            Response.Write(result);            
            Response.End();
        }
コード例 #38
0
 public WebExtensionsJavaScriptSerializer(JSONSerializer serializer) : base(serializer)
 {}
コード例 #39
0
        public void DoComponetsContentTest()
        {
            AppInernalsManager_Accessor target = new AppInernalsManager_Accessor();
            string name = "buildinfo";
            string actual;
            //HttpRequest request = new HttpRequest("~/", "http://localhost/test/appinternals/components/buildinfo", "");

            //HttpResponse response = new HttpResponse(new StringWriter());
            //HttpContext context = new HttpContext(request, response);



            Thread.GetDomain().SetData(".appPath", AppDomain.CurrentDomain.BaseDirectory);
            Thread.GetDomain().SetData(".appVPath", "/");
            Thread.GetDomain().SetData(".appDomain", "*");
            TextWriter tw = new StringWriter();
            TestWorkerRequest wr = new TestWorkerRequest("/test/appinternals/components/buildinfo", "", tw);
            wr.SetRemoteAddress("127.0.0.1");

            HttpContext.Current = new HttpContext(wr);
            ISerializer serializer = new JSONSerializer();
            actual = target.DoComponetsContent(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);
            serializer = new HTMLSerializer();
            actual = target.DoComponetsContent(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);
            serializer = new XMLSerializer();
            actual = target.DoComponetsContent(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);

        }
コード例 #40
0
        /// <summary>
        /// Retrieves an oAuth authentication token to be used on the translate
        /// API request. The result string needs to be passed as a bearer token
        /// to the translate API.
        /// 
        /// You can find client ID and Secret (or register a new one) at:
        /// https://datamarket.azure.com/developer/applications/
        /// </summary>
        /// <param name="clientId">The client ID of your application</param>
        /// <param name="clientSecret">The client secret or password</param>
        /// <returns></returns>
        public string GetBingAuthToken(string clientId = null, string clientSecret = null)
        {
            string authBaseUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";

            if (string.IsNullOrEmpty(clientId))
                clientId = DbResourceConfiguration.Current.BingClientId;
            if (string.IsNullOrEmpty(clientSecret))
                clientSecret = DbResourceConfiguration.Current.BingClientSecret;

            if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret))
            {
                ErrorMessage = Resources.Resources.Client_Id_and_Client_Secret_must_be_provided;
                return null;
            }
            
            var postData = string.Format("grant_type=client_credentials&client_id={0}" +
                                         "&client_secret={1}" +
                                         "&scope=http://api.microsofttranslator.com",
                                         HttpUtility.UrlEncode(clientId),
                                         HttpUtility.UrlEncode(clientSecret));

            // POST Auth data to the oauth API
            string res, token;

            try
            {
                var web = new WebClient();
                web.Encoding = Encoding.UTF8;
                res = web.UploadString(authBaseUrl, postData);
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.GetBaseException().Message;
                return null;
            }

            var ser = new JSONSerializer();
            var auth = ser.Deserialize<BingAuth>(res);
            if (auth == null)
                return null;
            
            token = auth.access_token;

            return token;
        }
コード例 #41
0
        /// <summary>
        /// Creates an global JavaScript object object that holds all non-control 
        /// local string resources as property values.
        /// 
        /// All resources are returned in normalized fashion from most specifc
        /// to more generic (de-ch,de,invariant depending on availability)
        /// </summary>
        /// <param name="javaScriptVarName">Name of the JS object variable to createBackupTable</param>
        /// <param name="ResourceSet">ResourceSet name. Pass NULL for locale Resources</param>
        /// <param name="LocaleId"></param>
        public string GetResourcesAsJavascriptObject(string javaScriptVarName, string ResourceSet, string LocaleId)
        {
            if (LocaleId == null)
                LocaleId = CultureInfo.CurrentUICulture.IetfLanguageTag;
            if (ResourceSet == null)
                ResourceSet = WebUtils.GetAppRelativePath();

            IDictionary resources = GetResourceSetNormalizedForLocaleId(
                LocaleId, ResourceSet);

            // Filter the list to non-control resources 
            Dictionary<string, string> localRes = new Dictionary<string, string>();
            foreach (string key in resources.Keys)
            {
                // We're only interested in non control local resources 
                if (!key.Contains(".") && resources[key] is string)
                    localRes.Add(key, resources[key] as string);
            }

            JSONSerializer ser = new JSONSerializer();
            ser.FormatJsonOutput = HttpContext.Current.IsDebuggingEnabled;
            string json = ser.Serialize(localRes);

            return "var " + javaScriptVarName + " = " + json + ";\r\n";
        }
コード例 #42
0
 public void ReadTest()
 {
     ISerializer serializer = new JSONSerializer();
     string expected = serializer.Serializer( myComponent, Encoding.UTF8 );
     string actual = myComponent.Read( serializer );
     Assert.AreEqual( expected, actual );
 }
コード例 #43
0
        /// <summary>
        /// Parses a single object value from the Request input stream into the
        /// specified type
        /// </summary>
        /// <param name="dataType"></param>
        /// <returns></returns>
        protected internal object ParseObjectFromPostData(Type dataType)
        {
            StreamReader sr = new StreamReader(Request.InputStream);
            string data = sr.ReadToEnd();
            sr.Close();

            object result = null;

            if (Request.ContentType == "text/javascript" || Request.ContentType == "application/json")
            {
                JSONSerializer ser = new JSONSerializer(SupportedJsonParserTypes.WestWindJsonSerializer);
                result = ser.Deserialize(data, dataType);
            }
            else if (Request.ContentType == "text/xml")
            {
                result = SerializationUtils.DeSerializeObject(data, dataType);
            }
            else
                return ExceptionResult("Unsuppported data input format. Please provide input content-type as text/javascript, application/json or text/xml.");

            return result;
        }
コード例 #44
0
        public void DoFeatureContingencyEntityTest()
        {
            FeatureContingency.FCManager.Current.GetFCS();
            AppInernalsManager_Accessor target = new AppInernalsManager_Accessor(); // TODO: Initialize to an appropriate value
            //HttpRequest request = new HttpRequest("", "http://localhost/appinternals", "action=change");
            //HttpResponse response = new HttpResponse(new StringWriter());
            //HttpContext context = new HttpContext(request, response);
            //HttpContext.Current = context;

            Thread.GetDomain().SetData(".appPath", AppDomain.CurrentDomain.BaseDirectory);
            Thread.GetDomain().SetData(".appVPath", "/");
            Thread.GetDomain().SetData(".appDomain", "*");
            TextWriter tw = new StringWriter();
            TestWorkerRequest wr = new TestWorkerRequest("/appinternals", "action=change", tw);
            wr.SetRemoteAddress("127.0.0.1");

            HttpContext.Current = new HttpContext(wr);

            string name = "centrallogging";
            ISerializer serializer = new JSONSerializer(); // TODO: Initialize to an appropriate value
            string actual;
            actual = target.DoFeatureContingencyEntity(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);

            //request = new HttpRequest("", "http://localhost/appinternals", "action=view");

            //context = new HttpContext(request, response);
            //HttpContext.Current = context;

            tw = new StringWriter();
            wr = new TestWorkerRequest("/appinternals", "action=view", tw);
            wr.SetRemoteAddress("127.0.0.1");


            actual = target.DoFeatureContingencyEntity(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);
            //request = new HttpRequest("", "http://localhost/appinternals", "format=json");

            //context = new HttpContext(request, response);
            //HttpContext.Current = context;

            tw = new StringWriter();
            wr = new TestWorkerRequest("/appinternals", "format=json", tw);
            wr.SetRemoteAddress("127.0.0.1");

            actual = target.DoFeatureContingencyEntity(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);
        }
コード例 #45
0
        public void DoDefaultTest()
        {
            AppInernalsManager_Accessor target = new AppInernalsManager_Accessor(); // TODO: Initialize to an appropriate value
            ISerializer serializer = new HTMLSerializer();
            //HttpRequest request = new HttpRequest("~/", "http://localhost/test/appinternals/configurations/beans/appsettingsbean", "action=view");

            //HttpResponse response = new HttpResponse(new StringWriter());
            //HttpContext context = new HttpContext(request, response);
            //HttpContext.Current = context;

            Thread.GetDomain().SetData(".appPath", AppDomain.CurrentDomain.BaseDirectory);
            Thread.GetDomain().SetData(".appVPath", "/");
            Thread.GetDomain().SetData(".appDomain", "*");
            TextWriter tw = new StringWriter();
            TestWorkerRequest wr = new TestWorkerRequest("/test/appinternals/configurations/beans/appsettingsbean", "action=view", tw);
            wr.SetRemoteAddress("127.0.0.1");


            HttpContext.Current = new HttpContext(wr);

            string actual;
            actual = target.DoDefault(serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);
            serializer = new JSONSerializer();
            actual = target.DoDefault(serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);
        }
コード例 #46
0
 /// <summary>
 /// 得到序列化器
 /// </summary>
 /// <param name="request">HttpRequest</param>
 /// <returns>序列化器</returns>
 private ISerializer GetSerializer(HttpRequest request)
 {
     string serType = (request.QueryString[AppConst.QueryFormat] ?? string.Empty).ToLowerInvariant();
     ISerializer serializer;
     if (!formatStr.Contains(serType) && string.IsNullOrEmpty(request.UserAgent)) serType = "json";
     switch (serType)
     {
         case "xml":
             serializer = new XMLSerializer();
             break;
         case "json":
             serializer = new JSONSerializer();
             break;
         case "text":
             serializer = new TextSerializer();
             break;
         default:
             serializer = new HTMLSerializer();
             break;
     }
     return serializer;
 }
コード例 #47
0
        public void DoLocalLogTest()
        {
            AppInernalsManager_Accessor target = new AppInernalsManager_Accessor(); // TODO: Initialize to an appropriate value
            string name = string.Empty;
            ISerializer serializer = new JSONSerializer(); // TODO: Initialize to an appropriate value
            string expected = string.Empty; // TODO: Initialize to an appropriate value
            //HttpRequest request = new HttpRequest("~/", "http://localhost/test/appinternals/locallog/iislog/123", "");

            //HttpResponse response = new HttpResponse(new StringWriter());
            //HttpContext context = new HttpContext(request, response);
            //HttpContext.Current = context;

            Thread.GetDomain().SetData(".appPath", AppDomain.CurrentDomain.BaseDirectory);
            Thread.GetDomain().SetData(".appVPath", "/");
            Thread.GetDomain().SetData(".appDomain", "*");
            TextWriter tw = new StringWriter();
            TestWorkerRequest wr = new TestWorkerRequest("test/appinternals/locallog/iislog/123", "", tw);
            wr.SetRemoteAddress("127.0.0.1");

            HttpContext.Current = new HttpContext(wr);

            string actual;
            actual = target.DoLocalLog(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);
            name = "iislog";
            actual = target.DoLocalLog(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);

            name = "applog";
            actual = target.DoLocalLog(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);
        }
コード例 #48
0
ファイル: Program.cs プロジェクト: AkariAkaori/NBTExtractor
		static void Main(string[] args)
		{
			if (args.Length < 2)
			{
				Console.WriteLine("USAGE: NBTExtractor <region dir> <output json>");
				Console.WriteLine("USAGE: NBTExtractor <backup tar.gz> <world json> <nether json> <end json>");
				return;
			}
			//args = new string[] { @"A:\Games\MC18DJ\saves\Civcraft\region", @"A:\Games\MC18DJ\saves\Civcraft\tiles.json" };
			

			if (File.GetAttributes(args[0]).HasFlag(FileAttributes.Directory))
			{
				var allTileEntities = new List<object>();
				var files = Directory.GetFiles(args[0], "*.mca");
				for (int i = 0; i < files.Length; i++)
				{
					var file = files[i];
					Console.WriteLine("[{0,4}/{1,4}] {2}", i + 1, files.Length, file);
					using (var fs = new FileStream(file, FileMode.Open))
					{
						foreach (var lst1 in ExtractRegion(fs))
						{
							var lst = (List<KeyValuePair<string, object>>)lst1.Where(x => x.Key == "Level").Single().Value;
							
							foreach (var tileEntities in lst.Where(x => x.Key == "TileEntities" && x.Value is List<KeyValuePair<string, object>>).Select(x => (List<KeyValuePair<string, object>>)x.Value))
							{
								allTileEntities.AddRange(tileEntities.Select(x => x.Value));
							}
							foreach (var tileEntities in lst.Where(x => x.Key == "TileEntities" && x.Value is object[]).Select(x => (object[])x.Value))
							{
								allTileEntities.AddRange(tileEntities);
							}

						}
					}
				}

				Console.WriteLine("{0} TileEntities gathered", allTileEntities.Count);
				Console.WriteLine("Converting to JSON...");
				var js = new JSONSerializer();
				using (var sw = new StreamWriter(args[1]))
					js.Serialize(ConvertObject(allTileEntities), sw);
				Console.WriteLine("Successfully exported to {0}", args[1]);
			}
			else
			{
				if (args.Length < 4)
				{
					Console.WriteLine("USAGE: NBTExtractor <backup tar.gz> <world json> <nether json> <end json>");
					return;
				}

				var allTileEntities = new SortedDictionary<string, List<Object>>();
				var outputStreams = new SortedDictionary<string, TextWriter>();
				var firsts = new SortedDictionary<string, bool>();
				
				string[] worlds = { "world", "world_nether", "world_the_end" };

				foreach (var world in worlds)
				{
					allTileEntities[world] = new List<object>();
					firsts[world] = true;
				}

				for (int i = 0; i < worlds.Length; i++)
				{
					var sw = new StreamWriter(args[i + 1]);
					outputStreams[worlds[i]] = sw;
					sw.WriteLine("[");
				}

				using (var fs = new FileStream(args[0], FileMode.Open))
				using (var gis = new GZipInputStream(fs))
				using(var tis = new TarInputStream(gis))
				{
					//Console.WriteLine("Start");

					TarEntry tarEntry;
					
					while((tarEntry = tis.GetNextEntry()) != null)
					{
						//Console.WriteLine(tarEntry.Name);
						if (tarEntry.IsDirectory)
							continue;

						foreach(var world in worlds)
						{
							FlushStreams(worlds, firsts, outputStreams, allTileEntities, 4096);
							if (tarEntry.Name.Contains("/" + world + "/") && tarEntry.Name.EndsWith(".mca"))
							{
								Console.WriteLine("[/] {0}", tarEntry.Name);
								var currentList = allTileEntities[world];


								using (var fss = new MemoryStream())
								{
									int numRead;
									byte[] buffer = new byte[4096];
									numRead = tis.Read(buffer, 0, buffer.Length);

									while(numRead > 0)
									{
										fss.Write(buffer, 0, numRead);
										numRead = tis.Read(buffer, 0, buffer.Length);
									}
									fss.Seek(0, SeekOrigin.Begin);

									foreach (var lst1 in ExtractRegion(fss))
									{
										var lst = (List<KeyValuePair<string, object>>)lst1.Where(x => x.Key == "Level").Single().Value;

										foreach (var tileEntities in lst.Where(x => x.Key == "TileEntities" && x.Value is List<KeyValuePair<string, object>>).Select(x => (List<KeyValuePair<string, object>>)x.Value))
										{
											currentList.AddRange(tileEntities.Select(x => x.Value));
										}
										foreach (var tileEntities in lst.Where(x => x.Key == "TileEntities" && x.Value is object[]).Select(x => (object[])x.Value))
										{
											currentList.AddRange(tileEntities);
										}

									}
								}

								break;
							}
						}
					}

					Console.WriteLine("Done");
					FlushStreams(worlds, firsts, outputStreams, allTileEntities, 0);
					foreach(var kvp in outputStreams)
					{
						kvp.Value.WriteLine("]");
						kvp.Value.Close();
					}
				}
			}

			
		}
コード例 #49
0
        /// <summary>
        /// Executes the requested method. 
        /// to the proper types for execution.
        /// </summary>
        /// <param name="Method"></param>
        /// <param name="methodParameters">An array of the string json parameters to </param>
        /// <param name="target">The object to call the method on</param>
        /// <param name="parameters">An array of json Strings that make up the parameters for the method call. This value can be null in which case parms are parsed out of GET QueryString or POST values</param>
        /// <param name="callbackMethodAttribute">An optional instance of an CallbackAttribute that is set by this method</param>
        /// <returns>the result of the method execution</returns>
        internal object ExecuteMethod(string method, object target, string[] parameters,
                                      CallbackMethodParameterType paramType,
                                      ref CallbackMethodAttribute callbackMethodAttribute)
        {
            HttpRequest Request = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;

            object Result = null;

            // Stores parsed parameters (from string JSON or QUeryString Values)
            object[] adjustedParms = null;

            Type PageType = target.GetType();
            MethodInfo MI = PageType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (MI == null)
                throw new InvalidOperationException();

            object[] methods = MI.GetCustomAttributes(typeof(CallbackMethodAttribute), false);
            if (methods.Length < 1)
                throw new InvalidOperationException();

            if (callbackMethodAttribute != null)
                callbackMethodAttribute = methods[0] as CallbackMethodAttribute;

            // Check for supported HTTP Verbs
            if (callbackMethodAttribute.AllowedHttpVerbs != HttpVerbs.All &&
                !string.IsNullOrEmpty(Request.HttpMethod))
            {
                HttpVerbs val = HttpVerbs.None;
                Enum.TryParse<HttpVerbs>(Request.HttpMethod, out val);
                if (val == HttpVerbs.None || !callbackMethodAttribute.AllowedHttpVerbs.HasFlag(val))
                {
                    Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                    Response.StatusDescription = string.Format("NotAllowedMethodExpectsVerb");
                    throw new UnauthorizedAccessException(Response.StatusDescription);
                }
            }

            ParameterInfo[] parms = MI.GetParameters();

            JSONSerializer serializer = new JSONSerializer();

            RouteData routeData = null;
            if (target is CallbackHandler)
                routeData = ((CallbackHandler)target).RouteData;

            int parmCounter = 0;
            adjustedParms = new object[parms.Length];
            foreach (ParameterInfo parameter in parms)
            {
                // Retrieve parameters out of QueryString or POST buffer
                if (parameters == null)
                {
                    // look for parameters in the route
                    if (routeData != null)
                    {
                        string parmString = routeData.Values[parameter.Name] as string;
                        adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType);
                    }
                    // GET parameter are parsed as plain string values - no JSON encoding
                    else if (HttpContext.Current.Request.HttpMethod == "GET")
                    {
                        // Look up the parameter by name
                        string parmString = Request.QueryString[parameter.Name];
                        adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType);
                    }
                    // POST parameters are treated as methodParameters that are JSON encoded
                    else
                        if (paramType == CallbackMethodParameterType.Json)
                            //string newVariable = methodParameters.GetValue(parmCounter) as string;
                            adjustedParms[parmCounter] = serializer.Deserialize(Request.Params["parm" + (parmCounter + 1).ToString()], parameter.ParameterType);
                        else
                            adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject(
                                Request.Params["parm" + (parmCounter + 1).ToString()],
                                parameter.ParameterType);
                }
                else
                    if (paramType == CallbackMethodParameterType.Json)
                        adjustedParms[parmCounter] = serializer.Deserialize(parameters[parmCounter], parameter.ParameterType);
                    else
                        adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject(parameters[parmCounter], parameter.ParameterType);

                parmCounter++;
            }

            Result = MI.Invoke(target, adjustedParms);

            return Result;
        }
コード例 #50
0
 /// <summary>
 ///  Force a master Serializer to be passed for settings
 /// </summary>
 /// <param name="serializer"></param>
 public JSONSerializerBase(JSONSerializer serializer)
 {
     masterSerializer = serializer;
 }
コード例 #51
0
ファイル: Chat.xaml.cs プロジェクト: jcteague/dtt
 private void SendMessage()
 {
     ISerializeJSON jsonSerializer = new JSONSerializer();
     applicationGlobalState.IsEditingCode = false;
     var messagesToSend = messageTextBox.GetTextEditorMessages();
     chatRoomControlService.SendMessages(messagesToSend, roomId);
     foreach(var message in messagesToSend)
         chatRoomControlService.AddReceivedMessage(GetChatUIElements(), messageScroll, jsonSerializer.Serialize(new ChatMessageModel { body = jsonSerializer.Serialize(message), chatMessageBody = message, user_id = userProvider.GetUser().id.ToString(), username = userProvider.GetUser().first_name, date = DateTime.Now.ToString()}));
     messageTextBox.Clear();
     messageTextBox.Resources.Clear();
 }
コード例 #52
0
        public void GetContentTest()
        {
            AppInernalsManager_Accessor target = new AppInernalsManager_Accessor(); // TODO: Initialize to an appropriate value
            ISerializer serializer = new JSONSerializer(); // TODO: Initialize to an appropriate value
            string expected = string.Empty; // TODO: Initialize to an appropriate value
            HttpRequest request = new HttpRequest("~/", "http://localhost/test/appinternals/configurations/beans/appsettingsbean", "action=view");

            HttpResponse response = new HttpResponse(new StringWriter());
            HttpContext context = new HttpContext(request, response);
            HttpContext.Current = context;
            string actual;
            actual = target.GetContent(request, serializer);
            Assert.AreNotEqual(expected, actual);
             
        }
コード例 #53
0
        public void Test_Tell_Pass_Add_With_Perspective(string nativePerspective, string tellPerdicate, string tellPerspective, string queryPerdicate, string queryPerspective)
        {
            var kb = new KB(Name.BuildName(nativePerspective));
            kb.Tell(Name.BuildName(tellPerdicate), Name.BuildName(true), Name.BuildName(tellPerspective));

            using (var stream = new MemoryStream())
            {
                var formater = new JSONSerializer();
                formater.Serialize(stream, kb);
                stream.Seek(0, SeekOrigin.Begin);
                Console.WriteLine(new StreamReader(stream).ReadToEnd());
            }

            var r = kb.AskProperty(Name.BuildName(queryPerdicate), Name.BuildName(queryPerspective));
            bool b;
            if (!r.TryConvertToValue(out b))
                Assert.Fail();

            Assert.IsTrue(b);
        }
コード例 #54
0
ファイル: Chat.xaml.cs プロジェクト: jcteague/dtt
        public void ChatMessageArrived(string channel, string payload)
        {
            if (channel == currentChannel)
            {
                logger.TryOrLog(() => {
                    ISerializeJSON jsonSerializer = new JSONSerializer();
                    var chatMessageModel = jsonSerializer.Deserialize<ChatMessageModel>(payload);
                        
                    if(userProvider.GetUser().id == Convert.ToInt32(chatMessageModel.user_id) && chatMessageModel.chatMessageBody.source=="vs plugin") return;

                    var receivedMessage = chatRoomControlService.AddReceivedMessage(GetChatUIElements(), messageScroll, payload);

                    var activeWindow = GetForegroundWindow();
                    var mainWindowHandle = (IntPtr)dteStore.dte.MainWindow.HWnd;
                    if ((Convert.ToInt32(receivedMessage.user_id) != userProvider.GetUser().id) && (activeWindow != mainWindowHandle))
                    {
                        taskbarNotifierWindow.Dispatcher.Invoke(new Action(() =>{
                            if ((bool) (!chkMute.IsChecked))
                                System.Media.SystemSounds.Beep.Play();
                            var msg = (receivedMessage.chatMessageBody.message.Length > 8)?receivedMessage.chatMessageBody.message.Remove(8)+"...":receivedMessage.chatMessageBody.message;
                            taskbarNotifierWindow.NotifyContent.Clear();
                            taskbarNotifierWindow.Show();
                            taskbarNotifierWindow.NotifyContent.Add(new NotifyObject(msg, receivedMessage.name+" says:"));
                            taskbarNotifierWindow.Notify();
                        }));
                    }
                });
            }
        }
コード例 #55
0
 /// <summary>
 ///  Force a master Serializer to be passed for settings
 /// </summary>
 /// <param name="serializer"></param>
 public JsonNetJsonSerializer(JSONSerializer serializer)
 {
     masterSerializer = serializer;
 }
コード例 #56
0
 private string DoHealthCheck(string name, ISerializer serializer)
 {
     var response = HttpContext.Current.Response;
     HealthCheckResult result = HealthCheckManager.Current.CheckResult();
     if (serializer.GetType() == typeof(HTMLSerializer)) { serializer = new JSONSerializer(); }
     response.StatusCode = result.StatusCode;
     if (name.ToLower() == "getmessage")
     {
         response.StatusCode = 200;
     }
     response.Write(serializer.Serializer(result, response.ContentEncoding));
     return string.Empty;
 }
コード例 #57
0
        public void DoComponetsContentTest()
        {
            AppInernalsManager_Accessor target = new AppInernalsManager_Accessor();
            string name = "buildinfo";
            string actual;
            HttpRequest request = new HttpRequest("~/", "http://localhost/test/appinternals/components/buildinfo", "");

            HttpResponse response = new HttpResponse(new StringWriter());
            HttpContext context = new HttpContext(request, response);
            HttpContext.Current = context;
            ISerializer serializer = new JSONSerializer();
            actual = target.DoComponetsContent(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);
            serializer = new HTMLSerializer();
            actual = target.DoComponetsContent(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);
            serializer = new XMLSerializer();
            actual = target.DoComponetsContent(name, serializer);
            Assert.IsNotNull(actual);
            Assert.IsTrue(actual.Length > 0);

        }
コード例 #58
0
        public void GetContentTest()
        {
            AppInernalsManager_Accessor target = new AppInernalsManager_Accessor(); // TODO: Initialize to an appropriate value
            ISerializer serializer = new JSONSerializer(); // TODO: Initialize to an appropriate value
            string expected = string.Empty; // TODO: Initialize to an appropriate value
            //HttpRequest request = new HttpRequest("~/", "http://localhost/test/appinternals/configurations/beans/appsettingsbean", "action=view");

            //HttpResponse response = new HttpResponse(new StringWriter());
            //HttpContext context = new HttpContext(request, response);
            //HttpContext.Current = context;


            Thread.GetDomain().SetData(".appPath", AppDomain.CurrentDomain.BaseDirectory);
            Thread.GetDomain().SetData(".appVPath", "/");
            Thread.GetDomain().SetData(".appDomain", "*");
            TextWriter tw = new StringWriter();
            TestWorkerRequest wr = new TestWorkerRequest("test/appinternals/configurations/beans/appsettingsbean", "action=view", tw);
            wr.SetRemoteAddress("127.0.0.1");

            HttpContext.Current = new HttpContext(wr);

            string actual;

            HttpRequest request = HttpContext.Current.Request;
            actual = target.GetContent(request, serializer);
            Assert.AreNotEqual(expected, actual);

        }
コード例 #59
0
        public void GetLogContentTest1()
        {
            LocalLogManager target = LocalLogManager.Current;
            ISerializer serializer = new JSONSerializer();
            string actual = target.GetLogContent( "AppLog", serializer );

            Assert.AreEqual( "{\"Category\":\"AppLog\",\"Path\":\"D:\\\\log\\\\\",\"LocalLogs\":[]}", actual );
        }
コード例 #60
0
ファイル: Program.cs プロジェクト: AkariAkaori/NBTExtractor
		static void Main(string[] args)
		{
			if (args.Length < 2)
			{
				Console.WriteLine("USAGE: BookExtractor <json output> <json inputs...>");
				return;
			}

			var json = new JSONSerializer();

			var booksOutput = new ConfigList();

			var sb = new StringBuilder();
			
			for (int i = 1; i < args.Length; i++)
			{
				long fsz = new FileInfo(args[i]).Length;
				using (var sr = new StreamReader(args[i]))
				{
					Console.WriteLine("Reading {0}", args[i]);
					string line;
					int lastPercent = 0;
					bool skip = true;

					while ((line = sr.ReadLine()) != null)
					{
						int newPercent = (int)((sr.BaseStream.Position * 100L) / fsz);

						if (newPercent != lastPercent)
						{
							lastPercent = newPercent;
							Console.WriteLine("{0}: {1,3}%", args[i], lastPercent);
						}

						if (line.StartsWith("\t{"))
						{
							sb.Clear();
							sb.AppendLine("{");
							skip = true;
						}
						else if (line.StartsWith("\t}"))
						{
							if (skip)
								continue;

							sb.AppendLine("}");
							var lst = json.Deserialize(sb.ToString());

							if (lst.ContainsKey("Items"))
							{
								var lstt = lst["Items"] as ConfigList;
								if (lstt != null)
								{
									foreach (ConfigPair pair in lstt)
									{
										ConfigList pairData = (ConfigList)pair.Value;

										string pdi = pairData["id"] as string;
										if (pdi == null)
											continue;
										if (pdi == "minecraft:written_book")
											booksOutput.Add(null, pairData["tag"]);
									}
								}
							}
						}
						else
						{
							if (line.StartsWith("\t\t\"Items\":"))
								skip = false;
							sb.AppendLine(line);
						}
					}
				}
			}

			using (var sw = new StreamWriter(args[0]))
				json.Serialize(booksOutput, sw);
		}