Beispiel #1
0
 public override string Serialize(object serializable)
 {
     Initialize();
     using (var stream = new MemoryStream())
     {
         _serializer.WriteObject(stream, serializable);
         stream.Flush();
         stream.Position = 0;
         return(Convert.ToBase64String(stream.ToArray()));
     }
 }
Beispiel #2
0
 public static string Serialize<T>(T myObject)
 {
     var json = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
     var stream = new MemoryStream();
     json.WriteObject(stream, myObject);
     return Encoding.UTF8.GetString(stream.ToArray());
 }
Beispiel #3
0
        /// <summary>
        /// This Function is used to write the Missing Targets Vs Missing Business Class Data Passed to corresponding FilePath
        /// </summary>
        /// <param name="LoginId"></param>
        /// <param name="MissingTargetsVsBusinessClass"></param>
        private void WriteMissingTargetsVsBusinessClassChartCacheFile(string Instance, string LoginId, List <MissingTargetsVsBusinessClass> MissingTargetsVsBusinessClass)
        {
            const string FUNCTION_NAME = "WriteMissingTargetsVsBusinessClassChartCacheFile";

            SICTLogger.WriteInfo(CLASS_NAME, FUNCTION_NAME, "Start for LoginId -" + LoginId);
            try
            {
                string FilePath   = string.Empty;
                string FolderPath = string.Empty;
                string MissingTargetsandBusinessClassData = string.Empty;
                GetMissingTargetsVsBusinessClassChartsFilePath(Instance, LoginId, ref FilePath, ref FolderPath);
                Boolean IsFolderExists = System.IO.Directory.Exists(FolderPath);
                if (!IsFolderExists)
                {
                    System.IO.Directory.CreateDirectory(FolderPath);
                }
                SICTLogger.WriteVerbose(CLASS_NAME, FUNCTION_NAME, "MissingTargetsVsBusinessClass Charts cache file for AirportLoginId- " + LoginId);
                using (var MemoryStream = new MemoryStream())
                {
                    var Serlizer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List <MissingTargetsVsBusinessClass>));
                    Serlizer.WriteObject(MemoryStream, MissingTargetsVsBusinessClass);
                    MissingTargetsandBusinessClassData = System.Text.Encoding.UTF8.GetString(MemoryStream.GetBuffer(), 0, Convert.ToInt32(MemoryStream.Length));
                    WriteToFile(MissingTargetsandBusinessClassData, FilePath);
                }
            }
            catch (Exception Ex)
            {
                SICTLogger.WriteException(CLASS_NAME, FUNCTION_NAME, Ex);
            }
            SICTLogger.WriteInfo(CLASS_NAME, FUNCTION_NAME, "End for LoginId -" + LoginId);
        }
Beispiel #4
0
 public static System.IO.MemoryStream ObjectToBytes(object Input)
 {
     System.IO.MemoryStream mstream = new System.IO.MemoryStream();
     System.Runtime.Serialization.Json.DataContractJsonSerializer se = new System.Runtime.Serialization.Json.DataContractJsonSerializer(Input.GetType());
     se.WriteObject(mstream, Input);
     return(mstream);
 }
Beispiel #5
0
        public static void Main(string[] args)
        {
            var p = new CgProgram(args);

            try
            {
                p.StartConsole();

                if (p.PrintHelp())
                {
                    return;
                }

                p.ParseProgramArgs();

                var cgType = Etc.GetCgOfType(p.Assembly, p.TypeName, false, p.ResolveDependencies);

                var dcs = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(CgType));
                using (var std = Console.OpenStandardOutput())
                {
                    dcs.WriteObject(std, cgType);
                    std.Flush();
                    std.Close();
                }
            }
            catch (Exception ex)
            {
                p.PrintToConsole(ex);
            }
            Thread.Sleep(NfConfig.ThreadSleepTime);//slight pause
        }
Beispiel #6
0
        public static void Main(string[] args)
        {
            var p = new CgProgram(args);
            try
            {
                p.StartConsole();

                if (p.PrintHelp()) return;

                p.ParseProgramArgs();

                var cgType = Etc.GetCgOfType(p.Assembly, p.TypeName, false, p.ResolveDependencies);

                var dcs = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof (CgType));
                using (var std = Console.OpenStandardOutput())
                {
                    dcs.WriteObject(std, cgType);
                    std.Flush();
                    std.Close();
                }
            }
            catch (Exception ex)
            {
                p.PrintToConsole(ex);
            }
            Thread.Sleep(NfConfig.ThreadSleepTime);//slight pause
        }
Beispiel #7
0
        private void SaveWebPost(string fileName, PostModel model)
        {
            WebPostModel wPost = new WebPostModel()
            {
                PTitle = model.PTitle,
                PText = model.PText,
                PLink = model.PLink,
                PImage = model.PImage,
                PDate = model.PDate.ToString("yyyy-MM-ddTHH:mm:ss"),
                PPrice = model.PPrice
            };

            System.IO.MemoryStream msPost = new System.IO.MemoryStream();
            System.Runtime.Serialization.Json.DataContractJsonSerializer dcJsonPost =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(WebPostModel));
            dcJsonPost.WriteObject(msPost, wPost);

            using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create))
            {
                byte[] jsonArray = msPost.ToArray();

                using (System.IO.Compression.GZipStream gz =
                    new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress))
                {
                    gz.Write(jsonArray, 0, jsonArray.Length);
                }
            }
        }
Beispiel #8
0
        static void Serialization(List <MobileAccount> users)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List <MobileAccount>));//33ms

            using (var streamWriter = File.OpenWrite("XML.xml"))
            {
                serializer.Serialize(streamWriter, users);
            }

            var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List <MobileAccount>));
            {
                using (FileStream fs = new FileStream("json.json", FileMode.OpenOrCreate))//18ms
                {
                    ser.WriteObject(fs, users);
                }
                BinaryFormatter formatter = new BinaryFormatter();

                using (FileStream fs = new FileStream("binary.dat", FileMode.OpenOrCreate))//11ms
                {
                    formatter.Serialize(fs, users);
                }

                var q = 0;
            }
        }
Beispiel #9
0
        private void doWork()
        {
            while (true)
            {
                try
                {
                    List <Channel> channels;
                    lock (_in_queue)
                    {
                        while (_in_queue.Count == 0 && !doExit)
                        {
                            Monitor.Wait(_in_queue);
                        }
                        if (doExit)
                        {
                            break;
                        }
                        channels = _in_queue.Dequeue();
                    }

                    Regex regex;
                    lock (_sw)
                    {
                        regex = new Regex(_sw.val, RegexOptions.IgnoreCase);
                    }

                    List <Article> res = new List <Article>();
                    foreach (Channel channel in channels)
                    {
                        foreach (Article article in channel.articles)
                        {
                            if (regex.IsMatch(article.title) || regex.IsMatch(article.description))
                            {
                                res.Add(article);
                            }
                        }
                    }

                    var          ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List <Article>));
                    MemoryStream ms  = new MemoryStream();
                    ser.WriteObject(ms, res);
                    string res_str = Encoding.UTF8.GetString(ms.ToArray());
                    ms.Close();

                    HttpWebRequest request = WebRequest.Create("http://localhost:49714/WebService.svc/enqueue_mailer") as HttpWebRequest;
                    request.Method        = "POST";
                    request.ContentType   = "application/json";
                    request.ContentLength = Encoding.UTF8.GetByteCount(res_str);

                    StreamWriter sw = new StreamWriter(request.GetRequestStream());
                    sw.Write(res_str);
                    sw.Close();
                    request.GetResponse();
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.Message);
                }
            }
        }
Beispiel #10
0
        public int UpdateBoard(Board.Game board)
        {
            if (!IsInitialized())
            {
                logger_.Info("Engine is not initialized.");
                return(-1);
            }

            if (IsRunning())
            {
                logger_.Info("Engine is running. Please stop the runner before updaing the board.");
                return(-1);
            }

            System.Runtime.Serialization.Json.DataContractJsonSerializer ser =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Board.Game));
            MemoryStream ms = new MemoryStream();

            ser.WriteObject(ms, board);
            ms.Position = 0;

            StreamReader sr   = new StreamReader(ms);
            string       json = sr.ReadToEnd();

            return(engine_.UpdateBoard(json));
        }
Beispiel #11
0
        public static string call(string funcname, params string[] args)
        {
            sates.input.api_cmd cmd = new input.api_cmd();
            cmd.api = funcname;

            cmd.args = new string[args.Length];
            for (int i = 0; i < args.Length; i++)
            {
                cmd.args[i] = args[i];
            }

            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List <sates.input.api_cmd>));

            List <sates.input.api_cmd> cmdlist = new List <sates.input.api_cmd>();

            cmdlist.Add(cmd);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            serializer.WriteObject(ms, cmdlist);
            ms.Position = 0;
            System.IO.StreamReader sr = new System.IO.StreamReader(ms);

            string jsoncmd = sr.ReadToEnd();

            sates.util.string_transfer.send(client, jsoncmd, Encoding.UTF8);

            sates.util.string_transfer.receive(client, out string result, Encoding.UTF8);
            System.Console.WriteLine(result);
            return(result);
        }
Beispiel #12
0
        public void SaveMission(string path)
        {
            string dirPath     = Path.GetDirectoryName(path);
            string missionName = Path.GetFileNameWithoutExtension(path);

            // Save mission file
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    // Write mission file
                    System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(MissionRoot));
                    using (MemoryStream stream = new MemoryStream())
                    {
                        serializer.WriteObject(stream, mission);
                        stream.Position = 0;
                        using (StreamReader reader = new StreamReader(stream))
                            writer.Write(Utility.JsonFormatter.Format(reader.ReadToEnd()));
                    }
                }
            //MissionReader.WriteMissionData(path, mission);

            // Save map file
            map.Write(Path.Combine(dirPath, mission.levelDetails.mapName));

            // Save plugin file
            PluginExporter.ExportPlugin(Path.Combine(dirPath, missionName + ".dll"), mission.sdkVersion, mission.levelDetails);
        }
Beispiel #13
0
            public async Task SaveAsync(TValue value)
            {
                var kts = _knownTypes;
                await await Task.Factory.StartNew(
                    async() =>
                {
                    var ms  = new MemoryStream();
                    var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(TValue), kts);
                    Value   = value;
                    ser.WriteObject(ms, value);
                    ms.Position = 0;
                    using (var strm = await _streamOpener(StreamOpenType.Write))
                    {
                        await ms.CopyToAsync(strm);
                        await strm.FlushAsync();
                    }
                },
                    CancellationToken.None,
                    TaskCreationOptions.None,
#if NET45
                    _sch.ExclusiveScheduler
#else
                    _sch
#endif


                    );
            }
Beispiel #14
0
        // ''' <summary>
        // ''' Erstellt eine vollständige Kopie (deep clone) dieser Instanz.
        // ''' </summary>
        // ''' <typeparam name="bbType"></typeparam>
        // ''' <returns></returns>
        // ''' <remarks></remarks>
        public bbType DeepClone <bbType>()
        {
            MemoryStream memStream    = new MemoryStream();
            var          js           = new System.Runtime.Serialization.Json.DataContractJsonSerializer(this.GetType(), TypeDetector.GetTypes(this));
            bbType       clonedObject = default(bbType);

            //Als JSon in den Speicher serialisieren
            try
            {
                js.WriteObject(memStream, this);
            }
            catch
            {
                throw;
            }

            //Die Kopie wieder zurückserialisieren.
            try
            {
                memStream.Seek(0, SeekOrigin.Begin);
                clonedObject = (bbType)js.ReadObject(memStream);
            }
            catch
            {
                throw;
            }

            return(clonedObject);
        }
Beispiel #15
0
 public void Save()
 {
     if (System.IO.File.Exists(path))
     {
         System.IO.File.Move(path, path + ".old");
     }
     System.Runtime.Serialization.Json.DataContractJsonSerializer sr = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(SettingObj));
     using (System.IO.FileStream sw = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate))
     {
         try
         {
             sr.WriteObject(sw, this);
         }
         catch (System.Exception ex)
         {
             if (System.IO.File.Exists(path + ".old"))
             {
                 System.IO.File.Move(path + ".old", path);
             }
             System.Windows.Forms.MessageBox.Show(ex.Message, "Error while writting setting files.");
         }
     }
     System.IO.File.SetAttributes(path, System.IO.File.GetAttributes(path) | System.IO.FileAttributes.Hidden);
     if (System.IO.File.Exists(path + ".old"))
     {
         System.IO.File.Delete(path + ".old");
     }
 }
        public string SerializeToString <T>(T obj)
        {
            if (TextSerializer != null)
            {
                return(TextSerializer.SerializeToString(obj));
            }

            if (!UseBcl)
            {
                return(JsonSerializer.SerializeToString(obj));
            }

            if (obj == null)
            {
                return(null);
            }
            var type = obj.GetType();

            try
            {
                using (var ms = MemoryStreamFactory.GetStream())
                {
                    var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(type);
                    serializer.WriteObject(ms, obj);
                    return(ms.ReadToEnd());
                }
            }
            catch (Exception ex)
            {
                throw new SerializationException("JsonDataContractSerializer: Error converting type: " + ex.Message, ex);
            }
        }
Beispiel #17
0
        // GET: Api/Post/Add3
        public JsonResult Add3()
        {
            PostModel model = new PostModel();
            model.PDate = DateTime.Now;

            string fileName = Server.MapPath("~/App_Data/test3.json");
            model.PText = fileName;

            System.Runtime.Serialization.Json.DataContractJsonSerializer ser =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(PostModel));

            System.IO.MemoryStream stream1 = new System.IO.MemoryStream();

            ser.WriteObject(stream1, model);

            using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create))
            {
                byte[] jsonArray = stream1.ToArray();

                using (System.IO.Compression.GZipStream gz =
                    new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress))
                {
                    gz.Write(jsonArray, 0, jsonArray.Length);
                }
            }

            return Json(model, JsonRequestBehavior.AllowGet);
        }
Beispiel #18
0
        public ActionResult GetBookList(int num, int page)
        {
            List <pagedata>      list     = new List <pagedata>();
            Random               rand     = new Random();
            IList <Inpinke_Book> bookList = DBBookBLL.GetUserBooks(UserSession.CurrentUser.ID);

            if (bookList != null)
            {
                foreach (Inpinke_Book b in bookList)
                {
                    pagedata p = new pagedata()
                    {
                        img   = b.BookCover,
                        title = b.BookName
                    };
                    list.Add(p);
                }
            }

            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(list.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, list);
                return(Content(Encoding.UTF8.GetString(ms.ToArray())));
            }
        }
Beispiel #19
0
        static void SendObject(object obj)
        {
            try
            {
                TcpClient client = new TcpClient("77.47.204.176", 85);

                NetworkStream stream = client.GetStream();

                System.Runtime.Serialization.Json.DataContractJsonSerializer serializator = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());

                serializator.WriteObject(stream, obj);

                byte[] data = new byte[1024];

                string responseData = String.Empty;
                int bytes = stream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                Console.WriteLine("Received: {0}", responseData);
                stream.Close();
                client.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("Argument null exception: {0}", e.ToString());
            }
            catch (SocketException e)
            {
                Console.WriteLine("Socket exception: {0}", e.ToString());
            }
            Console.WriteLine("End of send message...");
        }
Beispiel #20
0
        static void Main(string[] args)
        {
            Person p = new Person();

            p.Name = "John";
            p.Age  = 42;

            //serialization
            MemoryStream stream1 = new MemoryStream();
            var          ser     = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Person));

            ser.WriteObject(stream1, p);

            stream1.Position = 0;
            StreamReader sr = new StreamReader(stream1);

            Console.Write("JSON form of Person object: ");
            Console.WriteLine(sr.ReadToEnd());


            //deserialization
            stream1.Position = 0;
            Person p2 = (Person)ser.ReadObject(stream1);

            Console.Write("Deserialized back, Person name: {0}, age: {1}", p2.Name, p2.Age);

            Console.ReadKey();
        }
Beispiel #21
0
        public void SerializeToStream <T>(T obj, Stream stream)
        {
            if (obj == null)
            {
                return;
            }

            if (TextSerializer != null)
            {
                var streamSerializer = TextSerializer as IStringStreamSerializer;
                if (streamSerializer != null)
                {
                    streamSerializer.SerializeToStream(obj, stream);
                }
            }
#if !(SL5 || __IOS__ || XBOX || ANDROID || PCL || NETSTANDARD1_1)
            else if (UseBcl)
            {
                var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(stream, obj);
            }
#endif
            else
            {
                JsonSerializer.SerializeToStream(obj, stream);
            }
        }
Beispiel #22
0
        public void Write(Stream stream)
        {
            var nodes      = SerializerHelper.CreateSerializableNodes(Tree);
            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(CommonLibs.ExceptionManager.SerializerHelper.SerializableNode[]));

            serializer.WriteObject(stream, nodes);
        }
 private static void SerializeToFile(T obj, string filepath)
 {
     using (Stream stream = File.OpenWrite(filepath))
     {
         System.Runtime.Serialization.Json.DataContractJsonSerializer seria = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
         seria.WriteObject(stream, obj);
     }
 }
Beispiel #24
0
        private static void SerializeJSON(HttpContext context, object o)
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(o.GetType());
            MemoryStream ms = new MemoryStream();

            serializer.WriteObject(ms, o);
            context.Response.Write(Encoding.UTF8.GetString(ms.ToArray()));
        }
Beispiel #25
0
        public void DataContractJsonSerializer1()
        {
            using Stream stream = new MemoryStream();

            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));

            serializer.WriteObject(stream, Model);
        }
Beispiel #26
0
            public static Stream ObjectToJsonStream(object obj)
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                MemoryStream stream = new MemoryStream();

                serializer.WriteObject(stream, obj);
                return(stream);
            }
        public static void Dump <T>(T obj)
        {
            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
            var ms         = new MemoryStream();

            serializer.WriteObject(ms, obj);
            Console.WriteLine(Encoding.Default.GetString(ms.ToArray()));
        }
Beispiel #28
0
        public static string Serialize <T>(T serializeObject)
        {
            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(serializeObject.GetType());
            var ms         = new MemoryStream();

            serializer.WriteObject(ms, serializeObject);
            return(Encoding.Default.GetString(ms.ToArray()));
        }
Beispiel #29
0
        async void Run()
        {
            Console.WriteLine("Hello World!");

            Employee emp = new Employee {
                Code = "6", Name = "abe kiyotaka", BirthdayText = "2011/01/17", SalaryText = "3000000"
            };

            if (emp.Validation())
            {
                List <Employee> emps = new List <Employee> {
                    emp
                };
                using (var client = new HttpClient())
                {
#if false
                    System.Runtime.Serialization.Json.DataContractJsonSerializer jsonSerializor = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List <Employee>));
                    using (var mem = new MemoryStream())
                    {
                        jsonSerializor.WriteObject(mem, emps);
                        var json = Encoding.UTF8.GetString(mem.ToArray());
                        Console.Out.WriteLine("json=" + json);
                        var content = new StringContent(json, Encoding.UTF8, "application/json");

                        var ret = await client.PostAsync("http://localhost:40294/api/Employee/Update", content);

                        Console.Out.WriteLine($"{ret}");
                    }
#else
                    //Nuget Libraryを取込簡略化
                    client.BaseAddress = new Uri("http://localhost:40294/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    //var context = JsonConvert.SerializeObject(emps);
                    var ret = await client.PostAsJsonAsync <List <Employee> >("api/Employee/Update", emps);


                    Console.Out.WriteLine($"{ret}");
#endif
                }
                //var ret = await client.GetAsync("");

                //			Microsoft.AspNetCore.Blazor.JsonUtil.Serialize()
                //↓
                // Json.Serialize()
                //  を使うといい
                //new HttpClient
            }
            else
            {
                emp.ErrorMessage.All(em =>
                {
                    Console.Out.WriteLine($"field name={em.Key}, error message={em.Value}");
                    return(true);
                });
            }
        }
Beispiel #30
0
 public static string Serialize <T>(T data)
 {
     System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
     using (MemoryStream ms = new MemoryStream())
     {
         serializer.WriteObject(ms, data);
         return(Encoding.UTF8.GetString(ms.ToArray()));
     }
 }
Beispiel #31
0
 public static string Serialize(Object data, Encoding encoding)
 {
     System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         serializer.WriteObject(ms, data);
         return(encoding.GetString(ms.ToArray()));
     }
 }
Beispiel #32
0
        // SETTINS SAVING & LOADING

        // Save Settings
        public void saveSettings()
        {
            MemoryStream stream = new MemoryStream();

            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List <HKSound>));
            serializer.WriteObject(stream, soundFiles);
            byte[] json = stream.ToArray();
            System.IO.File.WriteAllBytes("settings.ini", json);
        }
Beispiel #33
0
        public static void Save(Pattern pattern, System.IO.Stream saveTarget)
        {
            var data       = ToData(pattern);
            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(PatternData));

            using (saveTarget)
            {
                serializer.WriteObject(saveTarget, data);
            }
        }
Beispiel #34
0
        private string Serialize <T>(T obj)
        {
            var stream     = new System.IO.MemoryStream();
            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));

            serializer.WriteObject(stream, obj);
            byte[] json = stream.ToArray();
            stream.Close();
            return(System.Text.Encoding.UTF8.GetString(json, 0, json.Length));
        }
 private void Send(BaseReturn ret,HttpContext context)
 {
     System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
        new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(BaseReturn));
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
        serializer.WriteObject(ms, ret);
        byte[] b = ms.ToArray();
        context.Response.OutputStream.Write(b, 0, b.Length);
        context.Response.Flush();
     }
 }
Beispiel #36
0
        private void doWork()
        {
            while (true)
            {
                try
                {
                    List<Channel> channels;
                    lock (_in_queue)
                    {
                        while (_in_queue.Count == 0 && !doExit)
                            Monitor.Wait(_in_queue);
                        if (doExit)
                            break;
                        channels = _in_queue.Dequeue();
                    }

                    Regex regex;
                    lock (_sw)
                    {
                        regex = new Regex(_sw.val, RegexOptions.IgnoreCase);
                    }

                    List<Article> res = new List<Article>();
                    foreach (Channel channel in channels)
                        foreach (Article article in channel.articles)
                        {
                            if (regex.IsMatch(article.title) || regex.IsMatch(article.description))
                                res.Add(article);
                        }

                    var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<Article>));
                    MemoryStream ms = new MemoryStream();
                    ser.WriteObject(ms, res);
                    string res_str = Encoding.UTF8.GetString(ms.ToArray());
                    ms.Close();

                    HttpWebRequest request = WebRequest.Create("http://localhost:49714/WebService.svc/enqueue_mailer") as HttpWebRequest;
                    request.Method = "POST";
                    request.ContentType = "application/json";
                    request.ContentLength = Encoding.UTF8.GetByteCount(res_str);

                    StreamWriter sw = new StreamWriter(request.GetRequestStream());
                    sw.Write(res_str);
                    sw.Close();
                    request.GetResponse();
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.Message);
                }
            }
        }
Beispiel #37
0
 public void SaveStore()
 {
     lock (this)
     {
         using (var filesystem = IsolatedStorageFile.GetUserStoreForApplication())
         {
             using (var fs = new IsolatedStorageFileStream(this.storeName, FileMode.Create, filesystem))
             {
                 var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(TaskCollection));
                 serializer.WriteObject(fs, this.AllTasks);
             }
         }
     }
 }
Beispiel #38
0
        private const string STORAGE_ID = "H2O"; // H2O

        #endregion Fields

        #region Methods

        public static void WriteBriefs()
        {
            using (var service = new ExecutionBrokerService.ExecutionBrokerServiceClient())
            {
                var briefs = service.GetBriefTaskList();
                var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(briefs.GetType());
                var memStream = new MemoryStream();
                serializer.WriteObject(memStream, (object) briefs);
                string json = Encoding.UTF8.GetString(memStream.ToArray());
                memStream.Close();

                Console.WriteLine();
                Console.WriteLine(json);
                Console.WriteLine();
            }
        }
        public Stream AdvancedSearchJSONP(string mode, string terms, string key, string callback)
        {
            List<vwar.service.host.SearchResult> md = AdvancedSearch(mode, terms, key);
            MemoryStream stream1 = new MemoryStream();
            System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<vwar.service.host.SearchResult>));
            ser.WriteObject(stream1, md);
            stream1.Seek(0, SeekOrigin.Begin);
            System.IO.StreamReader sr = new StreamReader(stream1);
            string data = sr.ReadToEnd();
            data = callback + "(" + data + ");";

            byte[] a = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(data);

            WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
            return new MemoryStream(a);
        }
Beispiel #40
0
        public static string Serialize(object obj)
        {
            if (obj == null) return null;

            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());

            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, obj);

                stream.Seek(0, SeekOrigin.Begin);

                using (var reader = new StreamReader(stream, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }
Beispiel #41
0
        private void button1_Click(object sender, EventArgs e)
        {
            var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(string[]));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, emails.ToArray());
            string email_str = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();

            WebRequest paramsWebRequest = WebRequest.Create("http://localhost:49714/WebService.svc/set_params?emails=" +
                    Uri.EscapeDataString(email_str) + "&filter_regex=" + Uri.EscapeDataString(regexTextBox.Text));
            paramsWebRequest.GetResponse();

            foreach (String channel_url in URLlistBox.Items)
            {
                WebRequest urlWebRequest = WebRequest.Create("http://localhost:49714/WebService.svc/enqueue_url?url=" +
                    Uri.EscapeDataString(channel_url));
                urlWebRequest.GetResponse();
            }
        }
Beispiel #42
0
        private void doWork()
        {
            while (true)
            {
                try
                {
                    string url = "";
                    lock (_in_queue)
                    {
                        while (_in_queue.Count == 0 && !doExit)
                            Monitor.Wait(_in_queue);
                        if (doExit)
                            break;
                        url = _in_queue.Dequeue();
                    }

                    List<Channel> res = RssFetcher.getFeedFromURL(url);

                    var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<Channel>));
                    MemoryStream ms = new MemoryStream();
                    ser.WriteObject(ms, res);
                    string res_str = Encoding.UTF8.GetString(ms.ToArray());
                    ms.Close();

                    HttpWebRequest request = WebRequest.Create("http://localhost:49714/WebService.svc/enqueue_filter") as HttpWebRequest;
                    request.Method = "POST";
                    request.ContentType = "application/json";
                    request.ContentLength = Encoding.UTF8.GetByteCount(res_str);

                    StreamWriter sw = new StreamWriter(request.GetRequestStream());
                    sw.Write(res_str);
                    sw.Close();
                    request.GetResponse();
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.Message);
                }
            }
        }
Beispiel #43
0
        static void SendServerMessage(string message)
        {
            try
            {
                TcpClient _client = new TcpClient("77.47.204.176", 85);

                byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

                NetworkStream stream = _client.GetStream();

                System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(string));
                ser.WriteObject(stream, message);

                //stream.Write(data, 0, data.Length);
                Console.WriteLine("Sent: {0}", message);

                data = new byte[256];

                string responseData = String.Empty;

                int bytes = stream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                Console.WriteLine("Received {0}", responseData);

                stream.Close();
                _client.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("Argument null exception: {0}", e.ToString());
            }
            catch (SocketException e)
            {
                Console.WriteLine("Socket exception: {0}", e.ToString());
            }
            Console.WriteLine("Message will send..");
        }
        /**
         * example from 
         * http://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx
         * */
        public void testDataMemberSimple()
        {
            Person p = new Person();
            p.name = "John";
            p.age = 42;
            p.title = "Mr";

            MemoryStream stream1 = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));

            ser.WriteObject(stream1, p);

            StreamReader sr = new StreamReader(stream1);

            stream1.Position=0;
            string strBuiltInJson = sr.ReadToEnd();
            //Console.WriteLine(sr.ReadToEnd());
            Console.WriteLine("inbuilt json=" + strBuiltInJson);

            Object2Json o2j = new Object2Json();
            o2j.NodeExpander = new DataContractFieldNodeExpander();
            string strJson =  o2j.toJson(p);
            System.Console.WriteLine("json:" + strJson);

            // analyze with JsonExplorer
            JSONExplorerImpl jsonExplorer = new JSONExplorerImpl();
            TestListener inbuiltListener = new TestListener();
            TestListener listener = new TestListener();
            jsonExplorer.explore(strBuiltInJson, inbuiltListener);
            jsonExplorer.explore(strJson, listener);

            Assert.AreEqual(inbuiltListener.leaves.Keys.Count, listener.leaves.Keys.Count, "leaf count");            

            compareMaps(inbuiltListener.leaves, "inbuilt", listener.leaves, "local");
            compareMaps(listener.leaves, "local", inbuiltListener.leaves, "inbuilt");

        }
Beispiel #45
0
 /// <summary>
 /// String to JSON string.
 /// </summary>
 /// <param name="sValue">The s value.</param>
 /// <returns></returns>
 public static string StringToJSONString(string sValue)
 {
     System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(sValue.GetType());
     MemoryStream ms = new MemoryStream();
     serializer.WriteObject(ms, sValue);
     string json = Encoding.Default.GetString(ms.ToArray());
     return json;
 }
Beispiel #46
0
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered "+_activityName+".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                executionContext.ActivityInstanceId,
                executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                context.CorrelationId,
                context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                //create a new myjsonrequest object from which data will be serialized
                MyJsonRequest myRequest = new MyJsonRequest
                {
                    Input1 = Input1.Get(executionContext),
                    Input2 = Input2.Get(executionContext)                    
                };

                //serialize the myjsonrequest to json
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myRequest.GetType());
                MemoryStream ms = new MemoryStream();
                serializer.WriteObject(ms, myRequest);
                string jsonMsg = Encoding.Default.GetString(ms.ToArray());

                //create the webrequest object and execute it (and post jsonmsg to it)
                System.Net.WebRequest req = System.Net.WebRequest.Create(_webAddress);

                //must set the content type for json
                req.ContentType = "application/json";

                //must set method to post
                req.Method = "POST";

                //create a stream
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(jsonMsg.ToString());
                req.ContentLength = bytes.Length;
                System.IO.Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);
                os.Close();

                //get the response
                System.Net.WebResponse resp = req.GetResponse();

                //deserialize the response to a myjsonresponse object
                MyJsonResponse myResponse = new MyJsonResponse();
                System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myResponse.GetType());
                myResponse = deserializer.ReadObject(resp.GetResponseStream()) as MyJsonResponse;

                //set output values from the fields of the deserialzed myjsonresponse object
                Output1.Set(executionContext, myResponse.Output1);
                Output2.Set(executionContext, myResponse.Output2);

            }

            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader =
                        new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                        "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                    "A Web exception ocurred while attempting to issue the request. {0}: {1}",
                    exception.Message, str), exception);
            }
            catch (FaultException<OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _activityName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }
 public override void Serialize(Stream stream, object obj)
 {
     var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
     serializer.WriteObject(stream, obj);
 }
        public void TestElcSettingsSerialization()
        {
            // Create ELC settings object with default parameter values.
            var settings = new ElcSettings();
            Assert.IsFalse(string.IsNullOrWhiteSpace(settings.Url));
            Assert.IsFalse(string.IsNullOrWhiteSpace(settings.FindRouteLocationOperationName));
            Assert.IsFalse(string.IsNullOrWhiteSpace(settings.FindNearestRouteLocationOperationName));
            Assert.IsFalse(string.IsNullOrWhiteSpace(settings.RoutesResourceName));

            // Note that for this test the URL will not actually be queried.
            const string testUrl = "http://hqolymgis99t/arcgis/rest/services/Shared/ElcRestSOE/MapServer/exts/ElcRestSoe";

            var settings2 = new ElcSettings(testUrl, null, null, null);

            Assert.AreNotEqual<ElcSettings>(settings, settings2, "Settings with differing URLs passed to constructors should not be equal.");

            // Deserialize to JSON using JSON.NET.
            var jsonDotNetJson = Newtonsoft.Json.JsonConvert.SerializeObject(settings);
            Assert.IsFalse(string.IsNullOrWhiteSpace(jsonDotNetJson));

            // Deserialize using built-in .NET methods.
            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ElcSettings));
            string json;
            byte[] bytes;
            using (MemoryStream memStream = new MemoryStream())
            {
                serializer.WriteObject(memStream, settings);
                bytes = memStream.GetBuffer();
                json = Encoding.Default.GetString(bytes);
            }
            Assert.IsFalse(string.IsNullOrWhiteSpace(json));

            // Serialize using both built-in and JSON.NET and compare results.
            using (MemoryStream memStream = new MemoryStream(bytes))
            {
                settings = (ElcSettings)serializer.ReadObject(memStream);
            }
            settings2 = Newtonsoft.Json.JsonConvert.DeserializeObject<ElcSettings>(jsonDotNetJson);

            Assert.AreEqual<ElcSettings>(settings, settings2, "ElcSettings deserialized via different methods should be equal.");
        }
Beispiel #49
0
        public string ToJsonString()
        {
            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(this.GetType());
            var memStream = new MemoryStream();
            serializer.WriteObject(memStream, (object) this);
            string json = Encoding.UTF8.GetString(memStream.ToArray());
            memStream.Close();

            return json;
        }
Beispiel #50
0
        private static IEnumerable<TaskSchedule> Reschedule(
            IEnumerable<Task> tasks, IEnumerable<Resource> resources,
            IEnumerable<TaskDependency> dependencies,
            //IDictionary<ulong, IEnumerable<string>> permissionsForTask,
            IDictionary<ulong, Dictionary<NodeConfig, Estimation>> estimationsForTask)
        {
            IEnumerable<TaskSchedule> result = null;
            ServiceProxies.SchedulerService.LaunchPlan schedResult;

            var scheduler = Discovery.GetSchedulerService();
            try
            {
                var urgentTask = tasks.FirstOrDefault(t => t.Priority == TaskPriority.Urgent &&
                    (t.State == TaskState.ReadyToExecute || t.State == TaskState.Scheduled));

                if (urgentTask != null)
                {
                    string urgentWfId = urgentTask.WfId;
                    var tasksForUrgentWf = tasks.Where(t =>
                           t.WfId == urgentWfId // urgent to plan
                        || t.State == TaskState.Started // already running
                        || (t.State == TaskState.ReadyToExecute && t.Priority == TaskPriority.Urgent &&
                            t.CurrentSchedule != null && !String.IsNullOrEmpty(t.CurrentSchedule.ResourceName)) // scheduled urgent
                    );

                    var filteredDependencies = dependencies.Where(d =>
                        tasksForUrgentWf.Any(t => t.TaskId == d.ChildTaskId && t.WfId == urgentWfId) && // todo: [!] ma ny "||", not "&&"?
                        tasksForUrgentWf.Any(t => t.TaskId == d.ParentTaskId && t.WfId == urgentWfId)
                    );

                    Log.Info(String.Format("WF '{0}' is urgent. Now scheduling only it.", urgentWfId));
                    Log.Debug("Tasks in urgent WF + active tasks: " + String.Join(", ", tasksForUrgentWf.Select(t => t.TaskId)));

                    /***** wf time bounds *****/
                    DateTime whenDefined = tasksForUrgentWf.Where(t => t.WfId == urgentWfId).Min(t => t.Time.WhenStarted[TaskTimeMetric.Postponed]);
                    double timeElapsed = (DateTime.Now - whenDefined).TotalSeconds;  // todo : DateTime.Now is different from when estimations was calculated

                    double minTimeInSec = Math.Max(0, double.Parse(urgentTask.ExecParams["MinTime"], System.Globalization.CultureInfo.InvariantCulture));
                    double maxTimeInSec = Math.Max(minTimeInSec, double.Parse(urgentTask.ExecParams["MaxTime"], System.Globalization.CultureInfo.InvariantCulture));

                    double minTimeRemained = Math.Max(0, minTimeInSec - timeElapsed);
                    double maxTimeRemained = Math.Max(0, maxTimeInSec - timeElapsed);

                    Log.Debug(String.Format("Time bounds for urgent WF '{0}' are [{1} - {2}] seconds (WF was defined {3} seconds ago)",
                        urgentWfId, minTimeRemained, maxTimeRemained, timeElapsed
                    ));

                    var wf = new ServiceProxies.SchedulerService.EstimatedUrgentWorkflow()
                    {
                        MinExecutionTime = minTimeRemained,
                        MaxExecutionTime = maxTimeRemained,
                    };

                    SetWorkflowDescription(wf, tasksForUrgentWf, resources, filteredDependencies, estimationsForTask, urgentWfId);

                    // todo : do no write every schedule to file
                    var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ServiceProxies.SchedulerService.EstimatedUrgentWorkflow));
                    var memStream = new System.IO.MemoryStream();
                    serializer.WriteObject(memStream, wf);
                    string json = Encoding.UTF8.GetString(memStream.ToArray());
                    memStream.Close();
                    Log.Debug("wf to Scheduler: " + json);

                    schedResult = scheduler.RescheduleEstimated((ServiceProxies.SchedulerService.EstimatedUrgentWorkflow)wf);
                }
                else
                {
                    var wf = new ServiceProxies.SchedulerService.EstimatedWorkflow();
                    SetWorkflowDescription(wf, tasks, resources, dependencies, estimationsForTask);

                    Log.Debug("WF is non-urgent. Sending it to scheduler");
                    schedResult = scheduler.RescheduleEstimated(wf);
                }

                scheduler.Close();
            }
            catch (Exception e)
            {
                scheduler.Abort();
                Log.Warn("Exception in scheduler: " + e.ToString());
                throw;
            }

            if (schedResult == null)
            {
                Log.Warn("Scheduler returned null");
            }
            else
            {
                var actionConvert = new Func<ServiceProxies.SchedulerService.TaskSchedulerTaskState, ScheduledAction>(
                    actionByScheduler =>
                    {
                        switch (actionByScheduler)
                        {
                            case ServiceProxies.SchedulerService.TaskSchedulerTaskState.ABORTED:
                                return ScheduledAction.Abort;

                            case ServiceProxies.SchedulerService.TaskSchedulerTaskState.LAUNCHED:
                                return ScheduledAction.Run;

                            case ServiceProxies.SchedulerService.TaskSchedulerTaskState.SCHEDULED:
                                return ScheduledAction.None;

                            default:
                                throw new Exception(String.Format(
                                    "Could not map scheduler's task action ({0}) to executor's task action",
                                    actionByScheduler.ToString()
                                ));
                        }
                    }
                );

                var now = DateTime.Now;

                var paramsByScheduler = new Dictionary<ulong, Dictionary<string, string>>();
                foreach (var activeTask in schedResult.Plan)
                {
                    ulong taskId = activeTask.Id;

                    try
                    {
                        // ModifiedParams = new Dictionary<string, string>(activeTask.Parameters),
                        paramsByScheduler[taskId] = activeTask.Estimation.Result.Parameters.ToDictionary(p => p.Name, p => p.NewValue);
                        if (!paramsByScheduler[taskId].ContainsKey("P"))
                            paramsByScheduler[taskId]["P"] = "0";
                    }
                    catch (Exception e)
                    {
                        paramsByScheduler[taskId] = new Dictionary<string, string>();
                        paramsByScheduler[taskId]["P"] = "0";
                        // todo : nodesCount from scheduler's params

                        Log.Warn(String.Format(
                            "Exception while assigning scheduler's parameters for task {0}: {1}\n{2}",
                            taskId, e.Message, e.StackTrace
                        ));
                    }
                }

                result = schedResult.Plan.Select(activeTask => new TaskSchedule()
                {
                    TaskId = activeTask.Id,
                    Action = actionConvert(activeTask.State),

                    Estimation = new Estimation(
                        estimationsForTask[activeTask.Id].Single(pair =>
                            pair.Key.ResourceName == activeTask.Estimation.Destination.ResourceName &&
                            pair.Key.NodeName == activeTask.Estimation.Destination.NodeNames.Single()
                        ).Value)
                    {
                        CalcStart = now + TimeSpan.FromSeconds(activeTask.Estimation.LaunchTime),
                        //CalcDuration = TimeSpan.FromSeconds(activeTask.Estimation.Result.Time)
                        CalcDuration = TimeSpan.FromSeconds(activeTask.Estimation.Result.CalculationTime)
                    },

                    /*
                    EstimatedStartTime  = now + TimeSpan.FromSeconds(activeTask.Estimation.LaunchTime),
                    EstimatedFinishTime = now + TimeSpan.FromSeconds(activeTask.Estimation.LaunchTime
                        + activeTask.Estimation.Result.CalculationTime),
                    */

                    ModifiedParams = paramsByScheduler[activeTask.Id],

                    Nodes = activeTask.Estimation.Destination.NodeNames.Select(nodeName => new NodeConfig()
                    {
                        NodeName = nodeName,
                        //Cores = Int32.Parse(activeTask.Estimation.Result.Parameters.First(par => par.Name == "P").NewValue),
                        Cores = UInt32.Parse(paramsByScheduler[activeTask.Id]["P"]),
                        ResourceName = activeTask.Estimation.Destination.ResourceName,
                    }).ToArray()
                });
            }

            return result;
        }
Beispiel #51
0
        private static string CreateRecipientRequest()
        {
            string request;
            Status.UpdateDate = null;
            RecipientStatusRequest r = new RecipientStatusRequest() { OrganizationId = Status.OrgId }; //{ UpdateDate = Status.UpdateDate.Value, OrganizationId = Status.OrgId };

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(RecipientStatusRequest));
                ser.WriteObject(ms, r);
                ms.Position = 0;
                using (System.IO.StreamReader rdr = new System.IO.StreamReader(ms))
                {
                    request = rdr.ReadToEnd();
                }
            }

            return request;
        }
Beispiel #52
0
        protected string Serialize(object o)
        {
            string returnVal;
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(o.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, o);
                returnVal = Encoding.Default.GetString(ms.ToArray());

                if (returnVal == "[]")
                {
                    throw new Exception("No Information Found");
                }
            }
            return returnVal;
        }
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered " + _activityName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                executionContext.ActivityInstanceId,
                executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                context.CorrelationId,
                context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                string inputText = Content.Get(executionContext);
                if (inputText != string.Empty)
                {
                    inputText = HtmlTools.StripHTML(inputText);

                    IndexDocument myDoc = new IndexDocument
                    {
                     Content = inputText,
                      Reference = (Email.Get(executionContext)).Id.ToString(),
                      Subject = Subject.Get(executionContext),
                      Title = Subject.Get(executionContext)
                    };

                    DocumentWrapper myWrapper = new DocumentWrapper();
                    myWrapper.Document = new List<IndexDocument>();
                    myWrapper.Document.Add(myDoc);

                    //serialize the myjsonrequest to json
                    System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myWrapper.GetType());
                    MemoryStream ms = new MemoryStream();
                    serializer.WriteObject(ms, myWrapper);
                    string jsonMsg = Encoding.Default.GetString(ms.ToArray());

                    //create the webrequest object and execute it (and post jsonmsg to it)
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(_webAddress);

                    //set request content type so it is treated as a regular form post
                    req.ContentType = "application/x-www-form-urlencoded";

                    //set method to post
                    req.Method = "POST";

                    StringBuilder postData = new StringBuilder();

                    //HttpUtility.UrlEncode
                    //set the apikey request value
                    postData.Append("apikey=" + System.Uri.EscapeDataString(_apiKey) + "&");
                    //postData.Append("apikey=" + _apiKey + "&");

                    //set the json request value
                    postData.Append("json=" + jsonMsg + "&");

                    //set the index name request value
                    postData.Append("index=" + _indexName);

                    //create a stream
                    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData.ToString());
                    req.ContentLength = bytes.Length;
                    System.IO.Stream os = req.GetRequestStream();
                    os.Write(bytes, 0, bytes.Length);
                    os.Close();

                    //get the response
                    System.Net.WebResponse resp = req.GetResponse();

                    //deserialize the response to a ResponseBody object
                    ResponseBody myResponse = new ResponseBody();
                    System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myResponse.GetType());
                    myResponse = deserializer.ReadObject(resp.GetResponseStream()) as ResponseBody;

                }
            }

            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader =
                        new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                        "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                    "A Web exception ocurred while attempting to issue the request. {0}: {1}",
                    exception.Message, str), exception);
            }
            catch (FaultException<OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _activityName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }
        public Stream SearchJSONP(string terms, string key, string callback)
        {
            if (HandleHttpOptionsRequest()) return null;

            List<vwar.service.host.SearchResult> md = Search(terms, key);
            MemoryStream stream1 = new MemoryStream();
            System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<vwar.service.host.SearchResult>));
            ser.WriteObject(stream1, md);
            stream1.Seek(0, SeekOrigin.Begin);
            System.IO.StreamReader sr = new StreamReader(stream1);
            string data = sr.ReadToEnd();
            data = callback + "(" + data + ");";

            byte[] a = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(data);

            WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
            WebOperationContext.Current.OutgoingResponse.Headers["Access-Control-Allow-Origin"] = WebOperationContext.Current.IncomingRequest.Headers["Origin"];
            return new MemoryStream(a);
        }
        protected void testInBuiltAndNativeJson(Object o, JsonExpectationBlock jsonExpectation, string testDescription)
        {
            System.Console.WriteLine("starting " + testDescription + " ************");

            MemoryStream stream1 = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer( o.GetType());
            ser.WriteObject(stream1, o);

            StreamReader sr = new StreamReader(stream1);
            stream1.Position = 0;
            string strBuiltInJson = sr.ReadToEnd();
            var mocks = new MockRepository();
            JsonExploreListener theMock = null;
            RhinoMocks.Logger = new TextWriterExpectationLogger(Console.Out);

            Object2Json o2j = new Object2Json();
            o2j.NodeExpander = new DataContractFieldNodeExpander();
            o2j.isDefaultLeafValue = DataContractDefaultUtil.isDefaultLeafValue;
            o2j.OmitDefaultLeafValuesInJs = true;
            string nativejson = o2j.toJson(o);
            JSONExplorerImpl jsonExplorerImpl = new JSONExplorerImpl();

            string json = null;
            Func<string> runWithMocks = () =>
            {
                theMock = mocks.StrictMock<JsonExploreListener>();
                using (mocks.Ordered())
                {
                    jsonExpectation(theMock, json);
                }
                theMock.Replay();
                jsonExplorerImpl.explore(json, theMock);
                theMock.VerifyAllExpectations();
                return null;
            };

            Console.WriteLine("testing inbuilt json=" + strBuiltInJson);
            json = strBuiltInJson;
            runWithMocks();

            Console.WriteLine("testing json=" + nativejson);
            json = nativejson;
            runWithMocks();

            System.Console.WriteLine("completed " + testDescription + " ************");
        }
Beispiel #56
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="indata"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public Stream GetReviewsJSONP(string pid, string key, string callback)
        {
            List<Review> md = GetReviewsJSON(pid, key);
            MemoryStream stream1 = new MemoryStream();
            System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<Review>));
            ser.WriteObject(stream1, md);
            stream1.Seek(0, SeekOrigin.Begin);
            System.IO.StreamReader sr = new StreamReader(stream1);
            string data = sr.ReadToEnd();
            data = callback + "(" + data + ");";

            byte[] a = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(data);

            WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
            return new MemoryStream(a);
        }
Beispiel #57
0
        private static void Test2()
        {
            #if NETCORE

            //ProtoBufTest.Test();
            {
                object exobj = null;
                try
                {
                    var b = 3;
                    b = 0;
                    var c = 2 / b;
                }
                catch (Exception exs)
                {
                    exobj = exs;
                }
                //var ex = new Exception("test ex");
                var ex = exobj;
                //var ex = new ServiceTest.Contract.Product
                //{
                //	Id = 223,
                //	Name = "abc book",
                //	Category = "Book",
                //	ListDate = DateTime.Now,
                //	Price = 34,
                //	Tags = new List<string>
                //	{
                //		"book",
                //		"tech",
                //		"new"
                //	}
                //};

                {
                    try
                    {
                        var setting = new JsonSerializerSettings
                        {
                            Formatting = Formatting.Indented,
                            ContractResolver = new SerializeContractResolver()
                        };
                        var json = JsonConvert.SerializeObject(ex, setting);
                        Console.WriteLine(json);
                        var dex = JsonConvert.DeserializeObject(json, ex.GetType(), setting);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }

                var dcs = new DataContractSerializer(ex.GetType());
                var ms = new MemoryStream();
                dcs.WriteObject(ms, ex);

                ms.Position = 0;
                var dex3 = dcs.ReadObject(ms);
                var xml = Encoding.UTF8.GetString(ms.ToArray());

                var jss = new System.Runtime.Serialization.Json.DataContractJsonSerializer(ex.GetType());
                var jsms = new MemoryStream();
                jss.WriteObject(jsms, ex);

                ms.Position = 0;
                var dexjs = dcs.ReadObject(ms);
                var jsss = Encoding.UTF8.GetString(ms.ToArray());

                var product = new ServiceTest.Contract.Product
                {
                    Id = 223,
                    Name = "abc book",
                    Category = "Book",
                    ListDate = DateTime.Now,
                    Price = 34,
                    Tags = new List<string>
                    {
                        "book",
                        "tech",
                        "new"
                    }
                };
                var xmlSeriaizer = new System.Xml.Serialization.XmlSerializer(product.GetType());
                var stringWriter = new StringWriter();
                //var xmlWriter = new XmlWriter();
                xmlSeriaizer.Serialize(stringWriter, (object)product);
            }
            #endif
        }
Beispiel #58
0
 private static void SerializeJSON(HttpContext context, object o)
 {
     System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(o.GetType());
     MemoryStream ms = new MemoryStream();
     serializer.WriteObject(ms, o);
     context.Response.Write(Encoding.UTF8.GetString(ms.ToArray()));
 }
Beispiel #59
0
        private static string CreateRequest()
        {
            ClientRequest c = new ClientRequest();

            c.ClientName = "etf705";
            c.SiteId = "7005";
            c.PrimaryContact = "Scott Carnley";
            c.BulkEmailRoute = new Guid("0379ECCC-B0B8-475E-9FD1-D68632B9184C").ToString();
            c.TransactionalEmailRoute = new Guid("0379ECCC-B0B8-475E-9FD1-D68632B9184C").ToString();
            c.EmailAddress = "*****@*****.**";
            c.PhoneNumber = "843-654-2882";
            c.UseDKIM = false;
            c.UseFeedbackLoop = false;

            string request;

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ClientRequest));
                ser.WriteObject(ms, c);
                ms.Position = 0;
                using (System.IO.StreamReader rdr = new System.IO.StreamReader(ms))
                {
                    request = rdr.ReadToEnd();
                }
            }

            return request;
        }
Beispiel #60
0
 public void WriteConfig()
 {
     lock (Settings)
     {
         System.IO.MemoryStream ms = new System.IO.MemoryStream();
         System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Dictionary<string, string>));
         ser.WriteObject(ms, Settings);
         System.IO.File.WriteAllText(ConfigPath, Encoding.Default.GetString(ms.ToArray()));
     }
 }