Exemple #1
0
        // THIS WORKS
        // so, when to use....
        // from a file-menu, I suppose....
        private void SaveTexts(List <Text> texts)
        {
            // TODO: ah, the name!
            var name = "texts.xml";

            File.WriteAllText(name, texts.ToXml());
        }
        static void Main(string[] args)
        {
            // dll list
            "Test Stub --> Repository File Manager".title();
            List <string> dllList = new List <string>();

            dllList.Add("TestDriver2.dll");
            dllList.Add("CodeToTest2.dll");
            repoFileManager manager = new repoFileManager();

            manager.Repository_folder = @"..\..\..\..\Stub Testing";
            string           message_content = dllList.ToXml();
            HashSet <string> filesList       = message_content.FromXml <HashSet <string> >();


            string toSendFilesPath = manager.Repo_Manager(filesList);

            if (toSendFilesPath == null)
            {
                // if all files are not found, a null will be returned
                Console.WriteLine("All requested DLLs are Not found ");
            }
            else
            {
                Console.WriteLine("found and are at {0} ", toSendFilesPath);
                manager.assignChannel("http://localhost:8000/StreamService");
                Console.WriteLine("\n Opened channel to stream File, but as it is test stub running independently there would not be any receiver");
                manager.callUploader(filesList, toSendFilesPath);
            }
            Console.ReadKey();
        }
Exemple #3
0
        static void Main(string[] args)
        {
            // Test Stub
            "This is a title test without parameter".title();
            Console.Write("\n\n");
            "This is a title test with parameter".title('=');
            Console.Write("\n\n");

            List <string> dllList = new List <string>();

            dllList.Add("TestDriver2.dll");
            dllList.Add("CodeToTest2.dll");
            string message_content = dllList.ToXml();

            Console.WriteLine("After using ToXml--> \n{0}", message_content);

            HashSet <string> filesList = message_content.FromXml <HashSet <string> >();

            Console.WriteLine("\n\nAfter using FromXml() --> \n");
            foreach (var x in filesList)
            {
                Console.WriteLine(x);
            }
            Console.ReadKey();
        }
Exemple #4
0
    protected void lbtnDelte_Command(object sender, CommandEventArgs e)
    {
        List <CustomWorkflowUserInfo> userList     = UserList.ToUserList();
        CustomWorkflowUserInfo        beDeleteInfo = userList.FirstOrDefault(x => x.LoginName == e.CommandArgument.ToString());

        userList.Remove(beDeleteInfo);
        UserList = userList.ToXml();
        InitUserNames();
    }
Exemple #5
0
        private static void ExportToXml()
        {
            var con = new MySQLWrapper("dbc_406", false);

            var areatable = con.ExecuteGetDataTable("select * from areatable");
            var areatableList = new List<AreaTable>();
            foreach (System.Data.DataRow row in areatable.Rows)
            {
                areatableList.Add(new AreaTable()
                {
                    Id = int.Parse(row[0].ToString()),
                    MapId = int.Parse(row[1].ToString()),
                    ZoneId = int.Parse(row[2].ToString()),
                    Name = row[11].ToString()
                });
            }

            using (var sw = new System.IO.StreamWriter("AreaTable.xml"))
            {
                sw.Write(areatableList.ToXml());
            }

            var map = con.ExecuteGetDataTable("select * from map");
            var mapList = new List<Map>();
            foreach (System.Data.DataRow row in map.Rows)
            {
                mapList.Add(new Map()
                {
                    Id = int.Parse(row[0].ToString()),
                    Name = row[1].ToString(),
                    LongName = row[6].ToString()
                });
            }


            using (var sw = new System.IO.StreamWriter("Map.xml"))
            {
                sw.Write(mapList.ToXml());
            }

            var gameobjectdisplayinfo = con.ExecuteGetDataTable("select * from gameobjectdisplayinfo");
            var gameobjectdisplayinfoList = new List<GameObjectDisplayInfo>();
            foreach (System.Data.DataRow row in gameobjectdisplayinfo.Rows)
            {
                gameobjectdisplayinfoList.Add(new GameObjectDisplayInfo()
                {
                    Id = int.Parse(row[0].ToString()),
                    FileName = row[1].ToString(),
                });
            }

            using (var sw = new System.IO.StreamWriter("GameObjectDisplayInfo.xml"))
            {
                sw.Write(gameobjectdisplayinfoList.ToXml());
            }
        }
    protected override bool AfterWorkflowApproval(string action, string option, bool isSuccess)
    {
        if (isSuccess)
        {
            ///对于加签
            if (action == "提交")
            {
                return(true);
            }

            ///更新当前步骤审批人处理记录
            var currentStep = SysContext.WF_Custom_InstanceItems.FirstOrDefault(x => x.StepID == CurrentStep);
            List <CustomWorkflowUserInfo> userinfos = currentStep.PartUsers.ToUserList();
            var currentParter = userinfos.FirstOrDefault(x => x.UserInfo.LoginName == _BPMContext.CurrentUser.LoginId);
            if (currentParter != null)
            {
                currentParter.IsApproval = true;
                currentStep.PartUsers    = userinfos.ToXml();
                SysContext.SubmitChanges();
            }

            if (userinfos.Count(x => !x.IsApproval) == 0)
            {
                //本步骤所有人已经执行审批

                ///更新当前自定义实例步骤
                if (action == "同意")
                {
                    var list       = CustomWorkflowDataProcess.GetWorkItemsData(_BPMContext.ProcID, FormId);
                    var nextInfo   = list.Where(x => x.StepID > CurrentStep && !string.IsNullOrEmpty(x.PartUsers)).OrderBy(x => x.OrderId).FirstOrDefault();
                    var updateInfo = BizContext.OA_CustomWorkFlowInstance.FirstOrDefault(x => x.FormID == FormId);
                    if (nextInfo != null)
                    {
                        updateInfo.CurrentStepId = nextInfo.StepID;
                    }
                    else
                    {
                        updateInfo.CurrentStepId = -1;//没有后续节点,流程结束
                    }
                    BizContext.SubmitChanges();
                }
                else
                {
                    var updateInfo = BizContext.OA_CustomWorkFlowInstance.FirstOrDefault(x => x.FormID == FormId);

                    updateInfo.CurrentStepId = -1;//不同意,流程结束

                    BizContext.SubmitChanges();
                }
            }
        }


        return(true);
    }
        public int Deserialize_msg(Messages msg)
        {
            (" [[ Displaying Requirement 4 ---->>> Processing Dequeued Request Concurrently ]]").title('=');
            Messages      receivedTestrequest;
            List <string> dllList;
            string        time    = null;
            string        dirPath = null;

            lock (locker)
            {
                xmlParser           = new XMLParser.XMLParser();
                receivedTestrequest = new Messages();
                receivedTestrequest = msg;
                dllList             = new List <string>();
                time    = msg.time.ToString("MM-dd-yyyy") + " " + msg.time.Hour + "-" + msg.time.Minute + "-" + msg.time.Second + " " + msg.time.ToString("tt");
                dirPath = @"..\..\..\..\" + msg.author + "-" + time;
            }
            Console.WriteLine("creating director with name: {0}", dirPath); // creates a temporary directory
            Directory.CreateDirectory(dirPath);
            // TempDir.Add(dirPath);
            Queue <KeyValuePair <string, string> > xml_Info_queue;
            int nu, count;

            lock (locker)
            {
                xml_Info_queue    = new Queue <KeyValuePair <string, string> >();
                xml_Info_queue    = xmlParser.Parse(msg.message_content); // call parser
                testRequest_Queue = new Queue <KeyValuePair <string, string> >();
                savePath          = Path.GetFullPath(dirPath);            // this is the path of the temporary directory where the repo will upload files
                Console.WriteLine("Parsed in App domain manager");
                nu = xml_Info_queue.Count;
            }
            for (int i = 0; i < nu; i++)
            {
                var de = xml_Info_queue.Dequeue();
                testRequest_Queue.Enqueue(new KeyValuePair <string, string>(de.Key, de.Value));
                Console.WriteLine("key is: {0}  and val is: {1}", de.Key, de.Value);
                if (de.Key != "author")
                {
                    dllList.Add(de.Value); // makes a dll list to be retrived for testing from the repository
                }
            }
            lock (locker)
            {           // now the manager will ask the repository to send these files in this local directory..
                count = dllList.Count;
                Messages message_for_Repo = makeMessage("Repository", endPoint, RepositoryEndPoint);
                message_for_Repo.command         = "DLL_Request";
                message_for_Repo.message_content = dllList.ToXml();
                comm.sndr.PostMessage(message_for_Repo);
            }
            Console.WriteLine("waiting for repository to upload files: \n");
            lock (locker)
                receiveFiles(); // opens host for receiving files
            return(count);
        }
        public static async Task CreateTables()
        {
            // Demo rodut
            List <Subrace> Subraces;
            List <Race>    Races = new List <Race>();
            Race           race  = new Race("Human", 1, 1, 1, 1, 1, 1, 30, size.Medium, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false);

            Races.Add(race);
            race     = new Race("Dwarf", 0, 0, 2, 0, 0, 0, 25, size.Medium, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false);
            Subraces = new List <Subrace>();
            Subraces.Add(new Subrace("Mountain Dwarf", 2, 0, 2, 0, 0, 0));
            Subraces.Add(new Subrace("Hill Dwarf", 0, 0, 2, 0, 1, 0));
            race.AddSubrace(new Subrace("Mountain Dwarf", 2, 0, 2, 0, 0, 0));
            race.AddSubrace(new Subrace("Hill Dwarf", 0, 0, 2, 0, 1, 0));
            Races.Add(race);



            string temp = Races.ToXml();
            await Task.Run(() => temp.SaveToFile("Races.xml", "Tables", NameCollisionOption.ReplaceExisting));

            temp = Subraces.ToXml();
            await Task.Run(() => temp.SaveToFile("Subraces.xml", "Tables", NameCollisionOption.ReplaceExisting));

            Debug.WriteLine("Races done");
            // Demo luokat
            List <Class> Classes = new List <Class>();

            Class cls = new Class("Fighter", "d10", true, false, true, false, false, false);

            cls.AddArchetype("Champion");
            Classes.Add(cls);
            cls = new Class("Cleric", "d8", false, false, false, false, true, true);
            cls.AddArchetype("Life");
            Classes.Add(cls);

            temp = Classes.ToXml();
            await Task.Run(() => temp.SaveToFile("Classes.xml", "Tables", NameCollisionOption.ReplaceExisting));

            Debug.WriteLine("Classes done");
            // Demo Backgroundit
            List <Background> Backgrounds = new List <Background>();
            Background        bck         = new Background("Acolyte", false, false, false, false, false, false, true, false, false, false, false, false, false, false, true, false, false, false);

            Backgrounds.Add(bck);
            bck = new Background("Criminal", false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, true, false);
            Backgrounds.Add(bck);



            temp = Backgrounds.ToXml();
            await Task.Run(() => temp.SaveToFile("Backgrounds.xml", "Tables", NameCollisionOption.ReplaceExisting));

            Debug.WriteLine("Backgrounds done");
        }
Exemple #9
0
        public static void SaveProfile(Profile profile)
        {
            if (profiles == null)
            {
                profiles = new List <Profile>();
            }

            Profile existing = profiles.Where(p => p.Id == profile.Id).FirstOrDefault();

            if (existing != null)
            {
                profiles.Remove(existing);
            }


            profiles.Add(profile);


            File.WriteAllText(filePath, profiles.ToXml <List <Profile> >());
        }
Exemple #10
0
        public void Setup()
        {
            testList = new List();
            testList.Id = "1";
            testList.Name = "Test List";

            listXml = testList.ToXml();

            testListRequest = new ListRequest();
            testListRequest.Name = "Test Note";

            listRequestXml = testListRequest.ToXml();
        }
        //----< make TestResults Message >-------------------------------
        /// <summary>
        /// generate FilesRequest Message from RequestInfo
        /// </summary>
        Message makeFilesRequestMessage(RequestInfo rqi)
        {
            Message trMsg = new Message();

            trMsg.author = "TestHarness";
            trMsg.to     = repUrl;
            trMsg.from   = endPoint;
            trMsg.type   = "FilesRequest";
            List <string> files = extractCode(rqi.requestInfo);

            files.Add(rqi.tempDirName);
            trMsg.body = files.ToXml();
            return(trMsg);
        }
Exemple #12
0
        protected override bool AfterApproval(string instanceId, string option, string action)
        {
            ///对于加签
            if (IsAddSign())
            {
                return(true);
            }
            var context    = DBContext.GetSysContext();
            var bizContext = DBContext.GetBizContext();
            ///更新当前步骤审批人处理记录
            ///
            var bizInfo = bizContext.OA_CustomWorkFlowInstance.FirstOrDefault(x => x.FormID == _BPMContext.ProcInst.FormId);

            var currentStep = context.WF_Custom_InstanceItems.FirstOrDefault(x => x.StepID == bizInfo.CurrentStepId.Value);
            List <CustomWorkflowUserInfo> userinfos = currentStep.PartUsers.ToUserList();
            var currentParter = userinfos.FirstOrDefault(x => x.UserInfo.LoginName == _BPMContext.CurrentUser.LoginId);

            if (currentParter != null)
            {
                currentParter.IsApproval = true;
                currentStep.PartUsers    = userinfos.ToXml();
                context.SubmitChanges();
            }

            if (userinfos.Count(x => !x.IsApproval) == 0)
            {
                //本步骤所有人已经执行审批

                ///更新当前自定义实例步骤
                if (action == "同意")
                {
                    var list     = CustomWorkflowDataProcess.GetWorkItemsData(_BPMContext.ProcID, "");
                    var nextInfo = list.Where(x => x.StepID > bizInfo.CurrentStepId.Value && !string.IsNullOrEmpty(x.PartUsers)).OrderBy(x => x.OrderId).FirstOrDefault();
                    if (nextInfo != null)
                    {
                        bizInfo.CurrentStepId = nextInfo.StepID;
                    }
                    else
                    {
                        bizInfo.CurrentStepId = -1;//没有后续节点,流程结束
                    }
                }
                else
                {
                    bizInfo.CurrentStepId = -1;//不同意,流程结束
                }
                bizContext.SubmitChanges();
            }
            return(true);
        }
Exemple #13
0
        public string ObtenerXML(string sCadenaGuardar)
        {
            List <MedDAL.DAL.bitacora> lstBitacora = new List <MedDAL.DAL.bitacora>();//odalBitacora.Buscar();

            lstBitacora.AddRange(odalBitacora.Buscar());

            string sXML = lstBitacora.ToXml();

            StreamWriter swrXml = new StreamWriter(sCadenaGuardar);

            swrXml.Write(sXML);
            swrXml.Flush();
            swrXml.Close();

            return(sCadenaGuardar);
        }
Exemple #14
0
    public void AddUser(string loginName)
    {
        List <CustomWorkflowUserInfo> userList = UserList.ToUserList();
        CustomWorkflowUserInfo        info     = userList.FirstOrDefault(x => x.UserInfo.LoginName == loginName);

        if (info == null)
        {
            userList.Add(new CustomWorkflowUserInfo()
            {
                UserInfo   = CustomWorkflowHelper.GetUserByLoginId(loginName),
                IsApproval = false
            });
            UserList = userList.ToXml();
            InitUserNames();
        }
    }
Exemple #15
0
        public void ToXml_List()
        {
            var list = new List <Orders>()
            {
                new Orders()
                {
                    Id       = 110,
                    Name     = "Orders",
                    describe = DateTime.Now.ToShortDateString(),
                    Order    = new Order()
                    {
                        Id             = 110111,
                        Name           = "Orders",
                        describe       = DateTime.Now.ToShortDateString(),
                        UsersLoginInfo = new UsersLoginInfo()
                        {
                            Id    = 110112000,
                            name  = "guojiaqiu",
                            phone = "11222222",
                            city  = DateTime.Now.ToShortDateString(),
                        }
                    }
                },
                new Orders()
                {
                    Id       = 110,
                    Name     = "Orders",
                    describe = DateTime.Now.ToShortDateString(),
                    Order    = new Order()
                    {
                        Id             = 110111,
                        Name           = "Orders",
                        describe       = DateTime.Now.ToShortDateString(),
                        UsersLoginInfo = new UsersLoginInfo()
                        {
                            Id    = 110112000,
                            name  = "guojiaqiu",
                            phone = "11222222",
                            city  = DateTime.Now.ToShortDateString(),
                        }
                    }
                }
            };
            var xml = list.ToXml();

            Assert.IsNotNull(xml);
        }
Exemple #16
0
        public void TestTaskXmlRoundTrip()
        {
            foreach (var task in TestUtil.GetTasks())
            {
                IDictionary <Folder, Guid> folderMap;
                var folders = new List <Folder>();
                if (task.Folder != null)
                {
                    folders.Add(task.Folder);
                }
                folders.ToXml(out folderMap);

                var xml = task.ToXml(f => folderMap[f]);
                Debug.WriteLine(xml);

                var newTask = XmlHelper.GetTask(xml, g => folderMap.First(kvp => kvp.Value == g).Key);
                Assert.IsTrue(TestUtil.ArraysEqual(TestUtil.GetArray(task), TestUtil.GetArray(newTask)));
            }
        }
        public void TestResultReplyToClient(Message msg, List <Logger> testLogs)
        {
            Message replyMsgToClient = makeMessage("Server", msg.to, msg.from, "TestResult");

            Console.WriteLine("\nTest Harness is Sending results back to the Client using Async Channel -----> Requirement 6,7 (Reference: TestHarnessServer.cs line number 117-126)");
            foreach (Logger log in testLogs)
            {
                replyMsgToClient.body += log.testName + ":" + log.TestResult + "\n";
            }
            Console.WriteLine("--> {0}", replyMsgToClient.body);
            comm.sndr.PostMessage(replyMsgToClient); //Sending Results back to Client
            Thread.Sleep(100);
            Console.WriteLine("\n Sending Test Logs to the Repository in xml format: -----> REquirement 7(Reference: TestHarnessServer.cs Line Number 131");
            Message msgToRepo = makeMessage("Server", endPoint, repoAddress, "SaveTestLogs");

            msgToRepo.body = testLogs.ToXml();
            Console.WriteLine("\n{0}", msgToRepo.body);
            comm.sndr.PostMessage(msgToRepo); //Sending Logs to Repository
        }
        public void TestXml()
        {
            var users = new List <StudentInfo>()
            {
                new StudentInfo()
                {
                    UserName = "******", Age = 18
                },
                new StudentInfo()
                {
                    UserName = "******", Age = 22
                }
            };
            var xml = users.ToXml();

            Console.WriteLine("user to json:" + xml);
            var users2 = xml.XmlToObject <List <StudentInfo> >();

            Assert.AreEqual("jsonlee", users2[0].UserName);
        }
Exemple #19
0
        public static void Save()
        {
            try
            {
                // IDictionary cannot be serialized, convert to a List first
                List <ConfValue> settings = new List <ConfValue>();

                foreach (var entry in Data)
                {
                    settings.Add(new ConfValue {
                        Key = entry.Key, Value = entry.Value
                    });
                }
                File.WriteAllText(FullPath, settings.ToXml());
            }
            catch (Exception ex)
            {
                Trace.WriteLine("DavuxLib2/Settings/ Can't Save: " + ex);
            }
        }
Exemple #20
0
        protected override void SaveItems(IEnumerable <KeyValuePair <TKey, TValue> > items, IEnumerable <KeyValuePair <TKey, TValue> > newItems, IEnumerable <KeyValuePair <TKey, TValue> > updItems, IEnumerable <KeyValuePair <TKey, TValue> > delItems)
        {
            string filePath = FilePath;

            var repositoryItems = new List <Pair <TKey, TValue> >();

            items.ForEach(item => repositoryItems.Add(new Pair <TKey, TValue>()
            {
                Key = item.Key, Value = item.Value
            }));

            if (repositoryItems.Count <= 0)
            {
                File.Delete(filePath);
            }
            else
            {
                using (var memoryStream = repositoryItems.ToXml())
                    memoryStream.Save(filePath);
            }
        }
Exemple #21
0
        public string BatchAddCustomer(BatchSubmitCustomer input)
        {
            List <Customer> list = new List <Customer>();

            for (int i = 0; i < input.Name.Length; i++)
            {
                if (input.Name[i].Length > 0 && TryToInt(input.Age[i]) > 0 && input.Tel[i].Length > 0)
                {
                    Customer c = new Customer {
                        Name    = input.Name[i],
                        Age     = TryToInt(input.Age[i]),
                        Address = input.Address[i],
                        Tel     = input.Tel[i],
                        Email   = input.Email[i]
                    };
                    list.Add(c);
                }
            }

            return(list.ToXml());
        }
        /// <summary>
        /// search key words in file names, store wanted file names in a ContentReply Msg
        /// </summary>
        public Message queryFileNames(Message origin)
        {
            string path = System.IO.Path.GetFullPath(repoStoragePath);

            string[]      files     = System.IO.Directory.GetFiles(repoStoragePath, origin.body);
            List <string> fileNames = new List <string>();

            foreach (string file in files)
            {
                string fileName = Path.GetFileName(file);
                fileNames.Add(fileName);
            }

            string  namelist = fileNames.ToXml();
            Message rpMsg    = new Message();

            rpMsg.author = "Repository";
            rpMsg.to     = origin.from;
            rpMsg.from   = origin.to;
            rpMsg.type   = "ContentReply";
            rpMsg.body   = namelist;
            return(rpMsg);
        }
Exemple #23
0
        public string ObtenerXML(string sCadenaGuardar) 
        {
            List<MedDAL.DAL.bitacora> lstBitacora = new List<MedDAL.DAL.bitacora>();//odalBitacora.Buscar();
            lstBitacora.AddRange(odalBitacora.Buscar());

            string sXML = lstBitacora.ToXml();

            StreamWriter swrXml = new StreamWriter(sCadenaGuardar);
            swrXml.Write(sXML);
            swrXml.Flush();
            swrXml.Close();

            return sCadenaGuardar;
        }
Exemple #24
0
 private string GenerateHmacValue(string accessKey, List<ExportKeyInfo> keys)
 {
     byte[] data = Constants.DefaultEncoding.GetBytes(keys.ToXml(true,true));
     return HashHelper.CreateHmac<HMACSHA256>(accessKey, data);
 }
        public void Execute()
        {
            var  scripts = new List <Script>();
            bool retry   = true;

            for (int id = 0; id < 30000; id++)
            {
                var script = new Script();
                using (var webClient = new WebClient()
                {
                    Encoding = System.Text.Encoding.UTF8
                })
                {
                    try
                    {
                        {
                            var          text     = webClient.DownloadString(@"https://70.wowfan.net/en/?npc=" + id);
                            HtmlDocument document = new HtmlDocument();
                            document.LoadHtml(text);
                            var documentNode = document.DocumentNode;
                            var headerNode   = documentNode.Descendants("h1").FirstOrDefault();
                            if (headerNode == null)
                            {
                                continue;
                            }

                            var titleNode = documentNode.Descendants("div")
                                            .FirstOrDefault(n =>
                                                            n.HasAttributes && n.Attributes["id"] != null &&
                                                            n.Attributes["id"].Value == "quotes-generic");

                            if (titleNode == null)
                            {
                                continue;
                            }

                            script.NpcId  = id.ToString();
                            script.NameEN = headerNode.InnerText;
                            foreach (var div in titleNode.Descendants("div"))
                            {
                                script.ScriptListEN.Add(div.InnerText);
                            }
                        }


                        {
                            var          text     = webClient.DownloadString(@"https://70.wowfan.net/?npc=" + id);
                            HtmlDocument document = new HtmlDocument();
                            document.LoadHtml(text);
                            var documentNode = document.DocumentNode;
                            var headerNode   = documentNode.Descendants("h1").FirstOrDefault();
                            if (headerNode == null)
                            {
                                continue;
                            }

                            var titleNode = documentNode.Descendants("div")
                                            .FirstOrDefault(n =>
                                                            n.HasAttributes && n.Attributes["id"] != null &&
                                                            n.Attributes["id"].Value == "quotes-generic");

                            if (titleNode == null)
                            {
                                Console.Write(true);
                                continue;
                            }

                            script.NpcId  = id.ToString();
                            script.NameCN = headerNode.InnerText;
                            foreach (var div in titleNode.Descendants("div"))
                            {
                                script.ScriptListCN.Add(div.InnerText);
                            }
                        }

                        Console.WriteLine(id);
                    }
                    catch (Exception e)
                    {
                        if (e.Message.Contains("404"))
                        {
                            continue;
                        }

                        if (retry)
                        {
                            retry = false;
                            id--;
                        }
                        else
                        {
                            retry = true;
                        }

                        continue;
                    }

                    scripts.Add(script);
                }
            }

            var xmlText = scripts.ToXml();

            File.WriteAllText(@"C:\Users\qqytqqyt\OneDrive\Documents\OneDrive\OwnProjects\WoWTranslator\Data\scripts\dbscripts3.xml", xmlText);
        }
Exemple #26
0
        public ActionResult ChemicalLibrary(string identifier)
        {
            Server.ScriptTimeout = 600;
            //No role based authentication needed, just make sure they have a valid credential for Library services.
            var authResult = CERSSecurityManager.AuthenticateHttpAuthorizationHeader();

            if (authResult.Result.Status == AuthenticationStatus.Success)
            {
                using (EDTTransactionScope transScope = new EDTTransactionScope(authResult.Account, EDTEndpoint.ChemicalLibraryQuery, Request.UserHostAddress, authenticationRequestID: authResult.EDTAuthenticationRequestID))
                {
                    try
                    {
                        if (!string.IsNullOrWhiteSpace(identifier))
                        {
                            List <Chemical> chemicals = new List <Chemical>();
                            Chemical        chemical  = null;

                            //1.) Check one.  Check cerskey
                            //Guid key = new Guid(identifier);
                            chemical = transScope.Repository.Chemicals.GetByCCLID(identifier);

                            //2.) Check two. Check CAS
                            if (chemical == null)
                            {
                                chemical = transScope.Repository.Chemicals.GetByCAS(identifier);

                                if (chemical == null)
                                {
                                    //3.) Check 3. Check USEpaSRSNumber
                                    chemical = transScope.Repository.Chemicals.GetByUSEPASRSNumber(identifier);
                                }
                            }

                            if (chemical != null)
                            {
                                chemicals.Add(chemical);
                            }

                            var xmlResult = chemicals.ToXml();
                            transScope.WriteActivity("Generated XML Package Successfully");
                            return(XmlElement(xmlResult));
                        }
                        else
                        {
                            var xmlResult = transScope.Repository.Chemicals.Search().ToXml();
                            transScope.WriteActivity("Generated XML Package Successfully");
                            return(XmlElement(xmlResult));
                        }
                    }
                    catch (Exception ex)
                    {
                        transScope.WriteActivity("Exception Occurred", ex);
                        transScope.WriteMessage("Exception Occurred. " + ex.Format(), EDTTransactionMessageType.Error);
                        transScope.Complete(EDTTransactionStatus.ErrorProcessing);
                        return(HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message));
                    }
                }
            }
            else
            {
                return(HttpStatusCodeResult(HttpStatusCode.Unauthorized, authResult));
            }
        }
Exemple #27
0
        public int Run(RunArgs ra)
        {
            bool interactive = !ra.InArgs.ContainsKey("-ni");

            var srcDirs          = new List <DirectoryInfo>();
            var srcs             = string.Empty;
            var skipLessThanSize = 1;
            var skipMoreThanSize = -1;
            var ignExt           = string.Empty;
            var iExt             = new List <string>();
            var compHash         = false;
            var recursive        = false;
            var inParallel       = 1;
            var delete           = false;
            var saveas           = string.Empty;
            var saveType         = string.Empty;

            ra.State.SearchPattern = "*.*";

            if (interactive)
            {
                Utils.ReadString("Enter folders to search into, separated by semicolon: ", ref srcs, true);
                Utils.ReadString("Search pattern (*.*): ", ref ra.State.SearchPattern);
                recursive = !Utils.ReadWord("Recursive search? (n/*): ", "n");
                Utils.ReadInt($"Skip if size < 1Kb: ", ref skipLessThanSize, false);
                Utils.ReadInt($"Skip if size > #Kb: ", ref skipMoreThanSize, false);
                Utils.ReadString("Skip extensions (.xyz): ", ref ignExt, false);
                compHash = Utils.ReadWord("Compare file names (default) or MD5 hashes? (h/*): ", "h");
            }
            else
            {
                if (ra.InArgs.ContainsKey("-dirs"))
                {
                    srcs = ra.InArgs.GetFirstValue("-dirs");
                }
                else
                {
                    throw new ArgumentNullException("-dirs");
                }
                if (ra.InArgs.ContainsKey("-sp"))
                {
                    ra.State.SearchPattern = ra.InArgs.GetFirstValue("-sp");
                }
                if (ra.InArgs.ContainsKey("-rec"))
                {
                    recursive = true;
                }
                if (ra.InArgs.ContainsKey("-j"))
                {
                    inParallel = int.Parse(ra.InArgs.GetFirstValue("-j"));
                }
                if (ra.InArgs.ContainsKey("-hash"))
                {
                    compHash = true;
                }
                if (ra.InArgs.ContainsKey("-del"))
                {
                    delete = true;
                }
                if (ra.InArgs.ContainsKey("-save"))
                {
                    saveas   = ra.InArgs.GetFirstValue("-save");
                    saveType = Path.GetExtension(saveas).Replace(".", "");
                }
            }

            if (!string.IsNullOrEmpty(ignExt))
            {
                foreach (var ext in ignExt.Split(';'))
                {
                    iExt.Add(ext.Trim());
                }
            }

            var useStreamReduction = false;
            var take = 4000;
            var skip = 10000;

            if (compHash && interactive)
            {
                Utils.ReadInt($"Concurrent readers (1-{Environment.ProcessorCount}): ", ref inParallel);
                "By default the hash is computed over the whole file.".PrintLine();
                "You can use skip and take parameters to read a portion of the file.".PrintLine();
                useStreamReduction = Utils.ReadWord("Do you want to use skip/take? (y/*): ", "y");

                if (useStreamReduction)
                {
                    "The reader always starts with a TAKE (position 0).".PrintLine();
                    Utils.ReadInt($"Take bytes ({take}): ", ref take, false);
                    Utils.ReadInt($"Skip bytes ({skip}): ", ref skip, false);

                    if (skip < 0 || take < 0)
                    {
                        throw new ArgumentOutOfRangeException("Negative skip or take value.");
                    }
                }
            }

            if (inParallel < 1 || inParallel > Environment.ProcessorCount)
            {
                throw new ArgumentOutOfRangeException("inParallel", $"The concurrent readers should be between 0 and {Environment.ProcessorCount}");
            }

            foreach (var p in srcs.Split(';'))
            {
                if (Directory.Exists(p))
                {
                    srcDirs.Add(new DirectoryInfo(p));
                }
                else
                {
                    throw new DirectoryNotFoundException(p);                 // will throw if the path is invalid
                }
            }
            var All       = new List <List <FileInfo> >();
            var searchOpt = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;

            // Some subdirectories may be restricted and the GetFiles will throw with AccesDenied
            // so loop the individual folders separately.
            foreach (var d in srcDirs)
            {
                try
                {
                    foreach (var sd in d.EnumerateDirectories("*", searchOpt).Union(new DirectoryInfo[] { d }))
                    {
                        try
                        {
                            var L = new List <FileInfo>();

                            foreach (var file in sd.EnumerateFiles(ra.State.SearchPattern, SearchOption.TopDirectoryOnly))
                            {
                                if (iExt.Count > 0 && iExt.Contains(file.Extension))
                                {
                                    continue;
                                }
                                if (skipLessThanSize > 0 && file.Length < skipLessThanSize)
                                {
                                    continue;
                                }
                                if (skipMoreThanSize > 0 && file.Length > skipMoreThanSize)
                                {
                                    continue;
                                }

                                L.Add(file);
                            }

                            All.Add(L);
                        }
                        catch (Exception ex)
                        {
                            ex.Message.PrintLine(ConsoleColor.Red);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ex.Message.PrintLine(ConsoleColor.Red);
                }
            }

            var dict              = new Dictionary <string, List <FileInfo> >();
            var sb                = new StringBuilder();
            var totalFiles        = 0;
            var totalFilesChecked = 0;

            // In all cases the length will be the same
            foreach (var src in All)
            {
                foreach (var fi in src)
                {
                    var key = $"{fi.Length}";
                    if (!dict.ContainsKey(key))
                    {
                        dict.Add(key, new List <FileInfo>());
                    }
                    else
                    {
                        totalFiles++;
                    }

                    totalFilesChecked++;
                    dict[key].Add(fi);
                }
            }


            totalFiles += totalFiles;

            // Either compare the names or the data hashes
            var hashDict        = new Dictionary <string, List <FileInfo> >();
            var totalDuplicates = 0;
            var counter         = 0;
            var hashDictSpin    = new SpinLock();

            $"{Environment.NewLine}Total files checked: {totalFilesChecked}".PrintLine();
            Console.CursorVisible = false;
            var cursorTop = Console.CursorTop;

            foreach (var kv in dict)
            {
                if (kv.Value.Count > 1)
                {
                    if (compHash)
                    {
                        Console.SetCursorPosition(0, cursorTop);

                        Parallel.For(0, kv.Value.Count, new ParallelOptions()
                        {
                            MaxDegreeOfParallelism = inParallel
                        }, (i) =>
                        {
                            try
                            {
                                Stream stream = File.OpenRead(kv.Value[i].FullName);
                                if (useStreamReduction)
                                {
                                    stream = new StreamReductor(stream, skip, take);
                                }

                                using (var md5 = MD5.Create())
                                    using (stream)
                                    {
                                        $"{++counter}/{totalFiles} [{kv.Value[i].Length / 1000}]Kb file{i} = {kv.Value[i].FullName}".PrintLine(ConsoleColor.Yellow);

                                        var h   = md5.ComputeHash(stream);
                                        var key = BitConverter.ToString(h);
                                        var acq = false;

                                        hashDictSpin.Enter(ref acq);

                                        if (acq)
                                        {
                                            if (!hashDict.ContainsKey(key))
                                            {
                                                hashDict.Add(key, new List <FileInfo>());
                                            }
                                            else
                                            {
                                                totalDuplicates++;
                                            }

                                            hashDict[key].Add(kv.Value[i]);
                                            hashDictSpin.Exit();
                                        }
                                    }
                            }
                            catch (Exception ex)
                            {
                                ex.Message.PrintSysError();
                                return;
                            }
                        });

                        var cursorTopNow = Console.CursorTop;
                        for (int top = cursorTop; top < cursorTopNow; top++)
                        {
                            for (int left = 0; left < Console.WindowWidth; left++)
                            {
                                Console.SetCursorPosition(left, top);
                                " ".Print();
                            }
                        }
                    }
                    else
                    {
                        foreach (var f in kv.Value)
                        {
                            var key = f.Name.ToLowerInvariant();

                            if (!hashDict.ContainsKey(key))
                            {
                                hashDict.Add(key, new List <FileInfo>());
                            }
                            else
                            {
                                totalDuplicates++;
                            }

                            hashDict[key].Add(f);
                            $"Comparing {++counter}/{totalFiles}".Print(ConsoleColor.Yellow);
                            Console.SetCursorPosition(0, Console.CursorTop);
                        }
                    }
                }
            }

            Console.SetCursorPosition(0, cursorTop);
            Console.CursorVisible = true;

            sb.AppendLine("Files with the same length and name/hash are grouped together.");
            sb.AppendLine();

            foreach (var kv in hashDict)
            {
                if (kv.Value.Count > 1)
                {
                    var    size = kv.Value[0].Length / 1000;
                    string lbl  = size < 1 ? lbl = $"{kv.Value[0].Length}b" : $"{size}Kb";

                    sb.AppendLine($"[{kv.Key}] {lbl}");
                    foreach (var p in kv.Value)
                    {
                        sb.AppendLine(p.FullName);
                    }

                    sb.AppendLine();
                }
            }


            $"There are {totalDuplicates} files with clones.".PrintLine();

            if (totalDuplicates > 0)
            {
                ra.Trace = interactive && Utils.ReadWord("Trace? (y/*): ", "y");

                if (ra.Trace)
                {
                    sb.ToString().PrintLine(ConsoleColor.Yellow);
                }

                // In case of -ni
                var opt = saveType;

                if (delete || (interactive && Utils.PickOption("Save results? (fdelete, xml, json, txt/*): ", ref opt, false, "fdelete", "xml", "json", "txt")))
                {
                    var fn   = string.Empty;
                    var data = string.Empty;

                    if (interactive)
                    {
                        Utils.ReadString("Result file path: ", ref fn, true);
                    }
                    else
                    {
                        fn = saveas;
                    }

                    if (opt == "fdelete" || delete)
                    {
                        var toDel = new StringBuilder();

                        foreach (var kv in hashDict)
                        {
                            if (kv.Value.Count > 1)
                            {
                                foreach (var f in kv.Value.Select(x => x.FullName).Skip(1))
                                {
                                    toDel.AppendLine(f);
                                    if (delete && File.Exists(f))
                                    {
                                        File.Delete(f);
                                    }
                                }
                            }
                        }

                        data = toDel.ToString();
                    }

                    if (opt == "txt")
                    {
                        data = sb.ToString();
                    }
                    else
                    {
                        var L = new List <Duplicate>();

                        foreach (var kv in hashDict)
                        {
                            if (kv.Value.Count > 1)
                            {
                                L.Add(new Duplicate(kv.Key, kv.Value[0].Length, kv.Value.Select(x => x.FullName).ToArray()));
                            }
                        }

                        if (opt == "json")
                        {
                            data = L.ToJson();
                        }
                        else
                        {
                            data = L.ToXml();
                        }
                    }

                    if (!string.IsNullOrEmpty(fn))
                    {
                        File.WriteAllText(fn, data);
                    }
                }
            }

            return(0);
        }
Exemple #28
0
        public void Test()
        {
            CustomKeyedCollection m = new CustomKeyedCollection();

            m.Add(new Word("ken"));
            m.Add(new Word("nimi"));
            m.Add(Words.nanpa);

            Console.WriteLine("");
            Console.WriteLine("DataContractJsonSerializer (serializes IXmlSerializable as XML strings?!)");
            Console.WriteLine("-------------------------------------------------------------------------");
            Console.WriteLine(m.ToJsonDcJs());
            Assert.NotNull(m.ToJsonDcJs());

            Console.WriteLine("");
            Console.WriteLine("JavaScriptSerializer (doesn't support enumerator keys in dictionaries!)");
            Console.WriteLine("-------------------------------------------------------------------------");
            Console.WriteLine(m.ToJsonJss());
            Assert.NotNull(m.ToJsonJss());

            Console.WriteLine("");
            Console.WriteLine("JSON.NET");
            Console.WriteLine("-------------------------------------------------------------------------");
            Console.WriteLine(m.ToJsonNet());
            Assert.NotNull(m.ToJsonNet());


            //WordXml
            List <WordXml> xmlWords = new List <WordXml>();
            WordXml        whut     = AutoMapper.Mapper.Map(Words.seme, new WordXml());

            xmlWords.Add(whut);

            Console.WriteLine("");
            Console.WriteLine("SharpSerializer (no privates, no fields)");
            Console.WriteLine("-------------------------------------------------------------------------");
            Console.WriteLine(xmlWords.ToSharpXml()); //Can't deal with private, so hard to serialize immutable!
            Assert.NotNull(xmlWords.ToSharpXml());

            Console.WriteLine("");
            Console.WriteLine("XmlSerializer (no privates, no built-in dictionaries)");
            Console.WriteLine("-------------------------------------------------------------------------");
            Console.WriteLine(xmlWords.ToXml()); //Can't deal with dictionaries? Ugh.
            Assert.NotNull(xmlWords.ToXml());

            Console.WriteLine("");
            Console.WriteLine("ToDataContractXml (No esoteric XML stuff)");
            Console.WriteLine("-------------------------------------------------------------------------");
            Console.WriteLine(m.ToDataContractXml().PrintXml()); //Can't deal with dictionaries? Ugh.
            Assert.NotNull(m.ToDataContractXml());


            Console.WriteLine("");
            Console.WriteLine("Binary");
            Console.WriteLine("-------------------------------------------------------------------------");
            BinaryFormatter formatter = new BinaryFormatter();

            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, m);
                ms.Position = 0;

                Console.WriteLine(Encoding.Default.GetString((ms.ToArray())));
                ms.Position = 0;
                CustomKeyedCollection result = formatter.Deserialize(ms) as CustomKeyedCollection;

                Assert.NotNull(result);
            }
        }
        private XDocument SerializeAssortment(List <AssortmentStockPriceProduct> currentAssortment)
        {
            var currentAssortmentXml = currentAssortment.ToXml();

            return(XDocument.Parse(currentAssortmentXml));
        }
        protected override void SerializeCustomPropertiesCore(XElement propertiesRoot)
        {
            base.SerializeCustomPropertiesCore(propertiesRoot);

            propertiesRoot.Add(commands.ToXml(rootName: CommandsString, nodeName: CommandString));
        }
Exemple #31
0
        public static bool AddUserTag(User user, int tagId, List <int> ignoredTagIds = null)
        {
            return(Retry3TimesForTimeout(() =>
            {
                var tagArticles = CacheClient.InMemoryCache.GetOrAdd <List <Article> >("articles" + tagId, CachePeriod.ForHours(1),
                                                                                       () => FeedService.GetArticlesPublishedAfterForTag(DateTime.Now.Date.AddMonths(-1), tagId));
                var db = GetDatabase();

                if (ignoredTagIds != null && ignoredTagIds.Count > 0)
                {
                    foreach (var ignoredTagId in ignoredTagIds)
                    {
                        var tagIgnoredArticles = CacheClient.InMemoryCache.GetOrAdd <List <Article> >("ingored-articles" + string.Join(",", ignoredTagIds), CachePeriod.ForHours(1),
                                                                                                      () => FeedService.GetArticlesPublishedAfterForTag(DateTime.Now.Date.AddMonths(-1), ignoredTagId));
                        tagArticles = tagArticles.FindAll(a => !tagIgnoredArticles.Select(ta => ta.Id).Contains(a.Id));
                    }
                }

                if (user.HideVisitedArticles)
                {
                    var visitedArticleIds = FeedService.GetArticlesVisitedAndPublishedAfter(user.Id, DateTime.Now.Date.AddMonths(-1));
                    tagArticles = tagArticles.FindAll(a => !visitedArticleIds.Contains(a.Id));
                }

                db.SortedSetAdd(GetWeekKey(user.Id), tagArticles.FindAll(a => a.Published >= DateTime.Now.Date.AddDays(-7))
                                .Select(a => new SortedSetEntry(a.Id, a.LikesCount))
                                .ToArray());
                db.SortedSetAdd(GetMonthKey(user.Id), tagArticles.FindAll(a => a.Published < DateTime.Now.Date.AddDays(-7) &&
                                                                          a.Published >= DateTime.Now.Date.AddMonths(-1))
                                .Select(a => new SortedSetEntry(a.Id, a.LikesCount))
                                .ToArray());
                //AddUser(user);
                return true;
            }, exceptionMessage: "AddUserTag:user:"******" tag:" + tagId + ":ignoredtagIds:" + ignoredTagIds.ToXml()));
        }
 public static void Save()
 {
     File.WriteAllText(_Filename, _Items.ToXml());
 }