Ejemplo n.º 1
0
 /// <summary>
 /// Считывает названия городов из файлов карт
 /// <para>Использует пути к файлам из class FilesDirectories</para>
 /// </summary>
 public void readCities(params string[] mapFiles)
 {
     CitiesList = new List<string>();
     for (int i = 0; i < mapFiles.Length; ++i)
     {
         System.IO.StreamReader file = new System.IO.StreamReader(mapFiles[i]);
         string mapType = file.ReadLine().ToLower();
         if (mapType.Contains("воздушная карта"))
         {
             string City;
             //Считывание Аэропортов
             while ((City = file.ReadLine()) != null)
             {
                 string[] RecordParts = City.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                 CitiesList.Add(RecordParts[0]);
             }
             file.Close();
         }
         if (mapType.Contains("наземная карта"))
         {
             string[] GroundCities;
             //Считывание Городов с графовой карты
             GroundCities = file.ReadLine().Split(new char[] { ' ', '\t', ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
             file.Close();
             CitiesList.AddRange(GroundCities);
             CitiesList = CitiesList.Distinct<string>().ToList<string>();
         }
     }
     CitiesList.Sort();
 }
Ejemplo n.º 2
0
            public FileVisionSource(string FileName, MsgService msgService)
                : base(msgService)
            {
                try
                {
                    Globals.SOURCE_NAME = FileName.Split(Path.DirectorySeparatorChar).Last().Split('.').First();
                    if (Constants.EVALUATE_SUCCESS_ENABLED /*&& Globals.FRAME_SIGN_HASH.Keys.Count==0*/ )
                    {
                        Globals.FRAME_SIGN_HASH = new Hashtable();
                        String line = null;
                        System.IO.StreamReader file = new System.IO.StreamReader(Constants.base_folder + "labels_" + Globals.SOURCE_NAME + ".txt");
                        while ((line = file.ReadLine()) != null)
                        {
                            string[] frameno_signno = line.Split(',');
                            if (frameno_signno.Length < 2)
                            {
                                file.Close();
                                throw new Exception("Invalid label file for " + Globals.SOURCE_NAME);
                            }

                            Globals.FRAME_SIGN_HASH.Add(frameno_signno[0], line);
                            Globals.FRAME_COUNT = long.Parse(line.Split(',').First())-1;
                        }
                        file.Close();
                    }

                    // Set up the capture graph
                    Configure(FileName);
                }
                catch
                {
                    Dispose();
                    throw;
                }
            }
        /// <summary>
        /// Refresh preview (if needed). Dependends on current environment and changed ETag.
        /// The preview is valid for remote and local view.
        /// First call will always lead to preview.
        /// 
        /// /Files/LocalPreview/Server/Path-To-File/file.preview.ext
        /// /Files/LocalPreview/Server/Path-To-File/file.etag
        /// </summary>
        /// <param name="file"></param>
        public void RefreshPreview(File file)
        {
            _file = file;
            bool createEtag = false;
            string path = "Files/LocalPreview/" + _info.Hostname + "/" + _file.FilePath + ".etag";
            var isf = App.DataContext.Storage;
            {
                if (isf.FileExists(path))
                {
                    var reader = new System.IO.StreamReader(isf.OpenFile(path, System.IO.FileMode.Open));
                    if (reader.ReadToEnd() == _file.ETag)
                    {
                        reader.Close();
                        return;
                    }
                    reader.Close();
                }
                else
                {
                    createEtag = true;
                }
            }

            // create main type
            if (_enabled)
            {
                switch (_file.FileType.Split('/').First())
                {
                    case "text":
                        TextPreview();
                        break;
                    case "image":
                        ImagePreview();
                        break;
                    case "application":
                        // try PDF content fetch
                        TextContentPreview();
                        break;
                    default:
                        PreviewIcon(file.IsDirectory);
                        break;
                }
            }
            else
            {
                PreviewIcon();
                createEtag = false;
            }

            if (createEtag)
            {
                    var storagePath = System.IO.Path.GetDirectoryName(path);
                    if (!isf.DirectoryExists(storagePath)) isf.CreateDirectory(storagePath);
                    var stream = isf.CreateFile(path);
                    System.IO.StreamWriter writer = new System.IO.StreamWriter(stream);
                    writer.Write(_file.ETag);
                    writer.Close();
            }
        }
        public ObservableCollection<Media> loadPlayListFile(string pathFile)
        {
            string line;
            string lineInfos;
            int advanced = 1;
            Media tmp = null;
            ObservableCollection<Media> playList = new ObservableCollection<Media>();

            System.IO.StreamReader file = new System.IO.StreamReader(pathFile);
            line = file.ReadLine();
            if (line == null)
            {
                file.Close();
                return playList;
            }
            if (line.IndexOf("#EXTM3U") == -1)
                advanced = 0;
            lineInfos = "";
            while ((line = file.ReadLine()) != null)
            {
                if (advanced == 1)
                {
                    if (line.IndexOf("#EXTINF:") != 0)
                    {
                        if (line.IndexOf("#EXTREM:") == -1)
                        {
                            try
                            {
                                tmp = _mediaCreator.Create(line);
                                playList.Add(tmp);
                                lineInfos = "";
                            }
                            catch (Exception e)
                            {
                                Debug.Add(e.ToString());
                            }
                        }
                    }
                    else
                        lineInfos = line.Substring(8);
                }
                else
                {
                    try
                    {
                        tmp = _mediaCreator.Create(line);
                        playList.Add(tmp);
                        lineInfos = "";
                    }
                    catch (Exception e)
                    {
                        Debug.Add(e.ToString());
                    }
                }
            }
            file.Close();
            return playList;
        }
Ejemplo n.º 5
0
        static void GetReleaseHistory()
        {
            string line;
            Dictionary <string, string> vrnHistory = new Dictionary <string, string>();

            // Read the file and display it line by line.
            System.IO.StreamReader file = null;
            try
            {
                file = new System.IO.StreamReader(mdFileName);
                var key   = string.Empty;
                var value = string.Empty;

                while ((line = file.ReadLine()) != null)
                {
                    Match m = versionExp.Match(line);
                    if (m.Success)
                    {
                        key   = line;
                        value = string.Empty;
                        vrnHistory.Add(key, value);
                    }
                    else
                    {
                        vrnHistory[key] = value += line;
                    }
                }
            }

            finally
            {
                file?.Close();
            }
        }
Ejemplo n.º 6
0
        private void loadFile(string path)
        {
            checkedListBox1.Items.Clear();
            System.IO.StreamReader sr = new
               System.IO.StreamReader(path);
            string line;
            try
            {
                while ((line = sr.ReadLine()) != null)
                {
                    string[] words = line.Split(',');
                    bool isChecked = Convert.ToBoolean(Convert.ToInt16(words[1]));
                    checkedListBox1.Items.Add(words[0]);
                    checkedListBox1.SetItemChecked(checkedListBox1.Items.Count - 1, isChecked);
                }
            }
            catch (IndexOutOfRangeException)
            {
                MessageBox.Show("An error has occured. The file " + openFileDialog1.SafeFileName +
                                " is corrupt or invalid.", "File error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                checkedListBox1.Items.Clear();
            }

            sr.Close();
        }
Ejemplo n.º 7
0
        public static void Main(string[] args)
        {
            // https://projecteuler.net/problem=18
            // https://projecteuler.net/problem=67
            int size = 100;//size of triangle from inputFilePath
            int[][] triangle = new int[size][];
            for (int i = 0; i < size; i++)
                triangle [i] = new int[i + 1];

            string inputFilePath = "test67.txt";//source file
            var fileStream = new System.IO.FileStream (inputFilePath, System.IO.FileMode.Open);
            var file = new System.IO.StreamReader(fileStream, System.Text.Encoding.UTF8);
            int lineCounter = 0;
            string lineOfText;
            while ((lineOfText = file.ReadLine()) != null) {
                var values = lineOfText.Split(' ');
                for (int j = 0; j < triangle [lineCounter].Length; j++)
                    triangle [lineCounter] [j] = Int32.Parse (values [j]);
                lineCounter++;
            }
            file.Close ();
            fileStream.Close ();

            //go from the bottom of triangle to the top
            //replace value in the line with maximum sum path from the botoom of the triangle to this point
            for (int k = size-2; k >= 0; k--) {
                var currentMaxValues = MaxPathSum (triangle [k+1], triangle [k]);
                for (int r = 0; r < currentMaxValues.Length; r++)
                    triangle [k] [r] = currentMaxValues [r];
            }
            Console.WriteLine ("Maximum path sum - {0}", triangle[0][0]);
        }
        public bool ExtractSettingsFromFile(String pathFileSettings)
        {
            try
            {
                if (System.IO.File.Exists(pathFileSettings) == true)
                {
                    System.IO.StreamReader myFile = new System.IO.StreamReader(pathFileSettings);
                    string globalContent = myFile.ReadToEnd();

                    myFile.Close();

                    if (globalContent.Contains(LineFileSeparator))
                    {
                        String[] listSettings = globalContent.Split(LineFileSeparator.ToCharArray());

                        for (int indexString = 0; indexString < listSettings.Length; indexString++)
                        {
                            if (listSettings[indexString].Contains(charToRemove.ToString()))
                            {
                                listSettings[indexString] = listSettings[indexString].Remove(listSettings[indexString].IndexOf(charToRemove), 1);
                            }
                        }
                        return ProcessSettings(listSettings);
                    }
                }

                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
Ejemplo n.º 9
0
        static Regex lineSimpleApply = CreateRegex(@"^Ext.apply\(\s*(?<name>({id}\.)?{idx})(\.prototype)?.*"); // e.g. Ext.apply(Dextop.common, {

        #endregion Fields

        #region Methods

        public override void ProcessFile(String filePath, Dictionary<String, LocalizableEntity> map)
        {
            ClasslikeEntity jsObject = null;
            System.IO.TextReader reader = new System.IO.StreamReader(filePath, Encoding.UTF8);
            //Logger.LogFormat("Processing file {0}", filePath);
            try
            {
                while (reader.Peek() > 0)
                {
                    String line = reader.ReadLine();
                    ClasslikeEntity o = ProcessExtendLine(filePath, line);
                    if (o != null)
                        jsObject = o;

                    else if (jsObject != null) {
                        LocalizableEntity prop = ProcessPropertyLine(jsObject, line);
                        if (prop != null && !map.ContainsKey(prop.FullEntityPath))
                            map.Add(prop.FullEntityPath, prop);
                    }
                }
                Logger.LogFormat("Processing file {0} - Success", filePath);
            }
            catch (Exception ex)
            {
                Logger.LogFormat("Processing file {0} - Error", filePath);
                throw ex;
            }
            finally
            {
                reader.Close();
            }
        }
Ejemplo n.º 10
0
        public static decimal ObtenerMedidaVertical ()
        {
            decimal vertical=0m;
            decimal horizontal=0m;
            if (System.IO.File.Exists(path))
            {
                System.IO.StreamReader SR = new System.IO.StreamReader(path);
                vertical = separatevaluefromparameter(SR.ReadLine())*pulgada;
                horizontal = separatevaluefromparameter(SR.ReadLine())*pulgada;
                
                SR.Close();
            }

            if (vertical > pulgada) 
            {
                vertical = 0.375m - (vertical - pulgada);
            }
            else if (vertical < pulgada) 
            {
                vertical = (pulgada - vertical) + 0.375m;
            }
            else if (vertical == pulgada)
            {
                vertical = 0.375m;
            }

            return vertical;
        }
Ejemplo n.º 11
0
        private void CheckPageForPhrase()
        {
            string html = "";
            try
            {
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.CreateDefault(new Uri(tbAddress.Text));
                System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse();
                System.IO.StreamReader current = new System.IO.StreamReader(resp.GetResponseStream());
                html = current.ReadToEnd();
                current.Close();
                string path = @"C:\LittleApps\HTMLPageScan\lastCheck.html";

                if (System.IO.File.Exists(path))
                {
                    System.IO.StreamReader last = System.IO.File.OpenText(path);
                    string tmpHtml = last.ReadToEnd();
                    last.Close();
                    if (html != tmpHtml)
                    {
                        SetText("\n*************" + DateTime.Now.ToShortTimeString() + "***************\nNew Item Added To Page\n");
                        WriteToDisk(path, html);
                    }
                }
                else//first time app is ever ran, otherwise the file already exists.
                {
                    WriteToDisk(path, html);
                }
                CheckHTML(html);
            }
            catch (Exception ex)
            {
                SetText(ex.Message);
            }
        }
Ejemplo n.º 12
0
        public static Move LoadMove(int moveNum)
        {
            Move move = new Move();
            string[] parse = null;
            using (System.IO.StreamReader read = new System.IO.StreamReader(IO.Paths.MovesFolder + "move" + moveNum + ".dat")) {
                while (!(read.EndOfStream)) {
                    parse = read.ReadLine().Split('|');
                    switch (parse[0].ToLower()) {
                        case "movedata":
                            if (parse[1].ToLower() != "v4") {
                                read.Close();
                                return null;
                            }
                            break;
                        case "data":
                            move.Name = parse[1];
                            move.MaxPP = parse[2].ToInt();
                            move.EffectType = (Enums.MoveType)parse[3].ToInt();
                            move.Element = (Enums.PokemonType)parse[4].ToInt();
                            move.MoveCategory = (Enums.MoveCategory)parse[5].ToInt();
                            move.RangeType = (Enums.MoveRange)parse[6].ToInt();
                            move.Range = parse[7].ToInt();
                            move.TargetType = (Enums.MoveTarget)parse[8].ToInt();

                            move.Data1 = parse[9].ToInt();
                            move.Data2 = parse[10].ToInt();
                            move.Data3 = parse[11].ToInt();
                            move.Accuracy = parse[12].ToInt();
                            move.HitTime = parse[13].ToInt();
                            move.AdditionalEffectData1 = parse[14].ToInt();
                            move.AdditionalEffectData2 = parse[15].ToInt();
                            move.AdditionalEffectData3 = parse[16].ToInt();
                            move.PerPlayer = parse[17].ToBool();

                            move.KeyItem = parse[18].ToInt();

                            move.Sound = parse[19].ToInt();

                            move.AttackerAnim.AnimationType = (Enums.MoveAnimationType)parse[20].ToInt();
                            move.AttackerAnim.AnimationIndex = parse[21].ToInt();
                            move.AttackerAnim.FrameSpeed = parse[22].ToInt();
                            move.AttackerAnim.Repetitions = parse[23].ToInt();

                            move.TravelingAnim.AnimationType = (Enums.MoveAnimationType)parse[24].ToInt();
                            move.TravelingAnim.AnimationIndex = parse[25].ToInt();
                            move.TravelingAnim.FrameSpeed = parse[26].ToInt();
                            move.TravelingAnim.Repetitions = parse[27].ToInt();

                            move.DefenderAnim.AnimationType = (Enums.MoveAnimationType)parse[28].ToInt();
                            move.DefenderAnim.AnimationIndex = parse[29].ToInt();
                            move.DefenderAnim.FrameSpeed = parse[30].ToInt();
                            move.DefenderAnim.Repetitions = parse[31].ToInt();

                            break;
                    }
                }
            }

            return move;
        }
Ejemplo n.º 13
0
        protected override void ExecuteCmdlet()
        {
            WebPartEntity wp = null;

            if (ParameterSetName == "FILE")
            {
                if (System.IO.File.Exists(Path))
                {
                    System.IO.StreamReader fileStream = new System.IO.StreamReader(Path);
                    string webPartString = fileStream.ReadToEnd();
                    fileStream.Close();

                    wp = new WebPartEntity();
                    wp.WebPartZone = ZoneId;
                    wp.WebPartIndex = ZoneIndex;
                    wp.WebPartXml = webPartString;
                }
            }
            else if (ParameterSetName == "XML")
            {
                wp = new WebPartEntity();
                wp.WebPartZone = ZoneId;
                wp.WebPartIndex = ZoneIndex;
                wp.WebPartXml = Xml;
            }
            if (wp != null)
            {
                this.SelectedWeb.AddWebPartToWebPartPage(PageUrl, wp);
            }
        }
 private void Button1_Click(object sender, EventArgs e)
 {
     openFileDialog1.ShowDialog();
     System.IO.StreamReader OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
     txtphoto.Text = openFileDialog1.FileName;
     OpenFile.Close();
 }
Ejemplo n.º 15
0
        public List<string[]> Read()
        {
            try {
                System.IO.FileInfo backlogFile = new System.IO.FileInfo(SQ.Util.Constant.BACKLOG_FILE);
                if (!backlogFile.Exists){
                    backlogFile.Create();
                    return new List<string[]>();
                }

                System.IO.StreamReader sr = new System.IO.StreamReader (SQ.Util.Constant.BACKLOG_FILE);
                Repo.LastSyncTime = backlogFile.LastWriteTime;
                List<string[]> filesInBackLog = new List<string[]>();
                int i = 1;
                while (!sr.EndOfStream) {
                    string [] info = BreakLine (sr.ReadLine (), 5);
                    filesInBackLog.Add (info);
                    i++;
                }
                sr.Dispose();
                sr.Close ();
                return filesInBackLog;
            } catch (Exception e) {
                SQ.Util.Logger.LogInfo("Sync", e);
                return null;
            }
        }
Ejemplo n.º 16
0
 public Markov(int randomnessLevel, string inputFileName, startForm controlForm)
 {
     k = randomnessLevel;
     keys = new Queue<string>(k);
     words = new List<string>();
     wordGroups = new Dictionary<string, List<string>>();
     statusForm = controlForm;
     string line;
     System.IO.StreamReader file = new System.IO.StreamReader(inputFileName);
     while ((line = file.ReadLine()) != null)
     {
         statusForm.status = "Reading input...";
         foreach(string s in line.Split(' '))
         {
             words.Add(cleanupString(s));
         }
     }
     file.Close();
     if (words.Count < (k + 1))
     {
         //To avoid trying to index outside of the array.  Just adds the first word k more times.
         //The output would have sucked anyway, so this won't throw it off very much.
         for (int i = 0; i < k; i++)
         {
             words.Add(words[0]);
         }
     }
     readWordGroups();
 }
Ejemplo n.º 17
0
	public static void Main(){

		string line;
		string temptab = "      \"temp\" : \"";
		string datetab = "      \"date\" : \"";

		System.IO.StreamReader file = new System.IO.StreamReader("bedroom.json");
		int ctr = 0;
		while((line = file.ReadLine()) != null)
		{
			
			if (line.Contains("temp") || line.Contains("date")){


				StringBuilder b = new StringBuilder(line);
				b.Replace(temptab, "");
				b.Replace(datetab, "");
				b.Replace("\"", "").Replace(",", "");

				if (ctr % 2 ==0){
					Console.Write(b + ",");
				}else {
					Console.WriteLine(b);
				}
				ctr++;
			}	   
		}
		file.Close();
		}
Ejemplo n.º 18
0
        public void generateDmcColors()
        {
            System.IO.StreamReader inFile = new System.IO.StreamReader(webPageDirectory);
            System.IO.StreamWriter outFile = new System.IO.StreamWriter(dmcDirectory, true);
            string line = "", dmc = "", name = "", color = "";

            while ((line = inFile.ReadLine()) != null)
            {
                if (line.Trim().StartsWith("<TD><FONT face=\"arial, helvetica, sans-serif\" size=2>") && !line.Trim().EndsWith("Select view")) //find dmc
                {
                    dmc = line.Trim().Split(new string[] { "<TD><FONT face=\"arial, helvetica, sans-serif\" size=2>" }, StringSplitOptions.None)[1];
                    dmc = dmc.Split(new string[] { "<" }, StringSplitOptions.None)[0];
                }
                else if (line.Trim().StartsWith("<TD noWrap><FONT face=\"arial, helvetica, sans-serif\" size=2>"))  //find name
                {
                    //issue with line continuation
                    name = line.Trim().Split(new string[] { "<TD noWrap><FONT face=\"arial, helvetica, sans-serif\" size=2>" }, StringSplitOptions.None)[1];
                    name = name.Split(new string[] { "<" }, StringSplitOptions.None)[0];
                    if (!line.Trim().EndsWith("</FONT></TD>"))
                    {
                        line = inFile.ReadLine();
                        name = name + " " + line.Trim().Split(new string[] { "<" }, StringSplitOptions.None)[0];
                    }
                }
                else if (line.Trim().StartsWith("<TD bgColor=") && line.Trim().Contains(">&nbsp;</TD>"))
                {
                    color = line.Trim().Split(new string[] { "<TD bgColor=" }, StringSplitOptions.None)[1];
                    color = color.Split(new string[] { ">" }, StringSplitOptions.None)[0];
                    outFile.WriteLine(dmc + ";" + name + ";" + color);
                }
            }
            inFile.Close();
            outFile.Close();
            Console.ReadLine();
        }
Ejemplo n.º 19
0
        public static Shop LoadShop(int shopNum)
        {
            Shop shop = new Shop();
            using (System.IO.StreamReader Read = new System.IO.StreamReader(IO.Paths.ShopsFolder + "shop" + shopNum + ".dat")) {
                string[] ShopInfo = Read.ReadLine().Split('|');
                if (ShopInfo[0] != "ShopData" || ShopInfo[1] != "V2") {
                        Read.Close();
                        return null;
                }

                string[] info;
                ShopInfo = Read.ReadLine().Split('|');
                shop.Name = ShopInfo[0];
                shop.JoinSay = ShopInfo[1];
                shop.LeaveSay = ShopInfo[2];
                //shop.FixesItems = ShopInfo[3].ToBool();
                //for (int i = 1; i <= 7; i++) {
                for (int z = 0; z < Constants.MAX_TRADES; z++) {
                    info = Read.ReadLine().Split('|');
                    shop.Items[z].GetItem = info[0].ToInt();
                    //shop.Items[z].GetValue = info[1].ToInt();
                    shop.Items[z].GiveItem = info[1].ToInt();
                    shop.Items[z].GiveValue = info[2].ToInt();
                }
                //}
            }
            return shop;
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            var file = new System.IO.StreamReader("PieCSource/Program.pie");

            string code = file.ReadToEnd();
            file.Close();

            CompilerParameters parameters = new CompilerParameters();
            parameters.ReferencedAssemblies.Add("Pie.dll");
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.GenerateInMemory = false;
            parameters.OutputAssembly = "piec.exe";
            parameters.GenerateExecutable = true;

            var provider = new PieCodeProvider();
            var results = provider.CompileAssemblyFromSource(parameters, code);

            foreach (CompilerError e in results.Errors)
            {
                Console.WriteLine(e.ErrorNumber + ", " + e.Line + ", " + e.Column + ": " + e.ErrorText);
            }

            if (results.Errors.Count == 0)
            {
                Type program = results.CompiledAssembly.GetType("Program");
                var main = program.GetMethod("Main");

                string[] strings = new string[] { "/out:test.exe", "TestCode/Program.pie", "TestCode/Hello.pie" };
                main.Invoke(null, new object[] { strings });
            }

            Console.ReadKey();
        }
		/// <summary> Loads a text file and adds every line as an entry to a HashSet (omitting
		/// leading and trailing whitespace). Every line of the file should contain only 
		/// one word. The words need to be in lowercase if you make use of an
		/// Analyzer which uses LowerCaseFilter (like GermanAnalyzer).
		/// 
		/// </summary>
		/// <param name="wordfile">File containing the wordlist
		/// </param>
		/// <returns> A HashSet with the file's words
		/// </returns>
		public static System.Collections.Hashtable GetWordSet(System.IO.FileInfo wordfile)
		{
			System.Collections.Hashtable result = new System.Collections.Hashtable();
			System.IO.StreamReader freader = null;
			System.IO.StreamReader lnr = null;
			try
			{
				freader = new System.IO.StreamReader(wordfile.FullName, System.Text.Encoding.Default);
				lnr = new System.IO.StreamReader(freader.BaseStream, freader.CurrentEncoding);
				System.String word = null;
				while ((word = lnr.ReadLine()) != null)
				{
                    System.String trimedWord = word.Trim();
					result.Add(trimedWord, trimedWord);
				}
			}
			finally
			{
				if (lnr != null)
					lnr.Close();
				if (freader != null)
					freader.Close();
			}
			return result;
		}
Ejemplo n.º 22
0
        public void addCandlesticks()
        {
            try
            {
                System.IO.StreamReader myFile = new System.IO.StreamReader("C:\\Users\\Steve\\Documents\\1.txt");
                string myString = myFile.ReadToEnd();
                myFile.Close();
                string[] lines = myString.Split(null);
                double[] prices = { Double.Parse(lines[0]), Double.Parse(lines[2]), Double.Parse(lines[4]), Double.Parse(lines[6]), Double.Parse(lines[8]) };

                candlesticksNQ.Add(new Candlestick());
                candlesticksCL.Add(new Candlestick());
                candlesticks6E.Add(new Candlestick());
                candlesticks6J.Add(new Candlestick());
                candlesticksGC.Add(new Candlestick());

                candlesticksNQ[candlesticksNQ.Count - 1].open = prices[0];
                candlesticksCL[candlesticksCL.Count - 1].open = prices[1];
                candlesticks6E[candlesticks6E.Count - 1].open = prices[2];
                candlesticks6J[candlesticks6J.Count - 1].open = prices[3];
                candlesticksGC[candlesticksGC.Count - 1].open = prices[4];
            }
            catch (Exception ex)
            {
                addCandlesticks();
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// �޸��û�����
        /// </summary>
        /// <param name="strNewPass">������</param>
        /// <returns>-100 �û������������</returns>
        public string PassWordModify(string strNewPass)
        {
            //��ȡϵͳ������Ϣ
            SystemConfig config = SystemConfig.GetSettings();
            string strRequst = "";
            try
            {
                Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
                string strTemp = "http://221.0.225.126:81/sendsms/modify?User="******"&Pass="******"&NewPass=" + HttpUtility.UrlEncode(strNewPass, encode);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strTemp);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encode);
                strRequst = reader.ReadToEnd();
                reader.Close();
                response.Close();

                //д�������ļ�
                SystemConfig systemConfig = new SystemConfig();
                systemConfig.NoteConfig = config.NoteConfig;
                systemConfig.NoteConfig.Password = strNewPass;
                systemConfig.SaveSettings();
            }
            catch
            {
            }
            return strRequst;
        }
Ejemplo n.º 24
0
        private string ReadString(string ressourcePath)
        {
            System.IO.Stream ressourceStream = null;
            System.IO.StreamReader textStreamReader = null;
            try
            {
                Assembly assembly = typeof(Addin).Assembly;
                ressourceStream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + ressourcePath);
                if (ressourceStream == null)
                    throw (new System.IO.IOException("Error accessing resource Stream."));

                textStreamReader = new System.IO.StreamReader(ressourceStream);
                if (textStreamReader == null)
                    throw (new System.IO.IOException("Error accessing resource File."));

                string text = textStreamReader.ReadToEnd();
                return text;
            }
            catch (Exception exception)
            {
                throw (exception);
            }
            finally
            {
                if (null != textStreamReader)
                    textStreamReader.Close();
                if (null != ressourceStream)
                    ressourceStream.Close();
            }
        }
Ejemplo n.º 25
0
        public string GetExplanation(string word)
        {
            const string dictionaryApiUrl = @"https://slovari.yandex.ru/";

            var requestUrl = dictionaryApiUrl + word + "/правописание/";
            var req = System.Net.WebRequest.Create(requestUrl);
            var resp = req.GetResponse();
            var stream = resp.GetResponseStream();

            if (stream != null)
            {
                var sr = new System.IO.StreamReader(stream);
                var Out = sr.ReadToEnd();
                sr.Close();

                var regex = new Regex("(?<=\"b-serp-item__text\">).*?(?=</div>)");
                var match = regex.Match(Out);
                if (match.Success)
                {
                    return match.Value;
                }
            }

            return @"Word explanation was not found.";
        }
Ejemplo n.º 26
0
        // Read from text file
        public void importInventory()
        {
            try
            {
                String directory = Environment.CurrentDirectory + "\\productInventory.txt";
                // Read the file
                System.IO.StreamReader file = new System.IO.StreamReader(directory);
                while ((line = file.ReadLine()) != null)
                {
                    inventory.Add(new List<String>());
                    breakDown = line.Split(',');
                    //Product names can be of different length, but index for prodID, amount and cost are fixed

                    //prodID
                    inventory[counter].Add(breakDown[0]);
                    //amount
                    inventory[counter].Add(breakDown[breakDown.Length - 2]);
                    //cost
                    inventory[counter].Add(breakDown[breakDown.Length - 1]);
                    //name
                    for (int i = 1; i < (breakDown.Length - 2); i++)
                    {
                        inventory[counter].Add(breakDown[i]);
                    }

                    counter++;
                }

                file.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.GetType());
            }
        }
Ejemplo n.º 27
0
        private static void TitleFillUp()
        {
            System.IO.StreamReader files = new System.IO.StreamReader(@"../../CodeResources/Files.txt");
            System.IO.StreamReader dependences = new System.IO.StreamReader(@"../../CodeResources/Dependences.txt");

            SortedDictionary<string, Node> independedFolders = new SortedDictionary<string, Node>();
            independedFolders.Add("TASKS_EXPLORER\n", new Node("TASKS_EXPLORER\n"));

            while (!files.EndOfStream) {
                string file = files.ReadLine();
                independedFolders.Add(file, new Node(file));
            }

            while (!dependences.EndOfStream) {
                string inp = dependences.ReadLine();
                inp = Regex.Replace(inp, @"\s+", " ");
                inp = Regex.Replace(inp, @"\\n+", "\n");
                string[] edge = inp.Split(' ');
                independedFolders[edge[0]].children.Add(independedFolders[edge[1]]);
                independedFolders[edge[0]].children[independedFolders[edge[0]].children.Count - 1].number = independedFolders[edge[0]].children.Count - 1;
                independedFolders[edge[0]].children[independedFolders[edge[0]].children.Count - 1].parent = independedFolders[edge[0]];
            }

            folders = independedFolders["TASKS_EXPLORER\n"];

            files.Close();
            dependences.Close();
        }
Ejemplo n.º 28
0
        static void insertCountries()
        {
            MySqlCommand cmd = new MySqlCommand("INSERT INTO `climate`.`countries` (`abbreviation`,`name`) VALUES (@abbrev,@name);", conn);

            conn.Open();
            System.IO.StreamReader countries = new System.IO.StreamReader("Y:\\country-list.txt");
            System.IO.StreamWriter csvCountries = new System.IO.StreamWriter("Y:\\country-list.csv");

            Console.WriteLine(countries.ReadLine());
            Console.WriteLine(countries.ReadLine());

            while (countries.Peek() > 0)
            {
                string line = countries.ReadLine();
                string[] strings = line.Split(new string[] { "          " }, StringSplitOptions.RemoveEmptyEntries);
                //string[] strings = line.Split(new char[] { ' ' }, 12);
                Console.WriteLine(strings[0] + "," + strings[1]);
                csvCountries.WriteLine(strings[0] + "," + strings[1]);
                cmd.Parameters.AddWithValue("abbrev", strings[0]);
                cmd.Parameters.AddWithValue("name", strings[1]);

                cmd.ExecuteScalar();
                cmd.Parameters.Clear();
            }

            conn.Close();
            csvCountries.Close();
            countries.Close();
        }
Ejemplo n.º 29
0
 public static List<TileBehavior> readFromFile(string fileName)
 {
     List<TileBehavior> behaviors = new List<TileBehavior>();
     try
     {
         System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
         while (!sr.EndOfStream)
         {
             string line = sr.ReadLine();
             if (line != string.Empty) {
                 if (line.StartsWith("+"))
                     behaviors.Add(new TileBehavior("", line.Substring(1)));
                 else {
                     int equalpos = line.IndexOf('=');
                     behaviors.Add(new TileBehavior(line.Substring(0, equalpos - 1).Trim(), line.Substring(equalpos + 1).Trim()));
                 }
             }
         }
         sr.Close();
     }
     catch (Exception ex)
     {
         System.Windows.Forms.MessageBox.Show("Error reading tile behavior file. The error is: \n" + ex.Message);
     }
     return behaviors;
 }
Ejemplo n.º 30
0
        public string GetHTMLFromURL(string url)
        {
            try
            {
                if (url.Length == 0)
                    throw new Exception("Invalid Url");

                string html = "";
                //Create request to internet
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Timeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"].Trim());
                //Create response to get data from URL
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                // get the response stream.
                System.IO.Stream responseStream = response.GetResponseStream();
                // use a stream reader that understands UTF8
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                // Read data
                html = reader.ReadToEnd();
                // close the reader
                response.Close();
                reader.Close();
                //Return
                return html;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Prends en parametre un nom de fichiers
 /// Renvoie le contenu du fichier
 /// Renvoie une chaine vide et cree le fichier
 /// si il n'existait pas
 /// </summary>
 /// <param name="name">Nom du fichier</param>
 /// <returns>Contenu du fichier</returns>
 public static string readFile(string name)
 {
     try
     {
         System.IO.StreamReader instream = new System.IO.StreamReader(name);
         string str = instream.ReadToEnd();
         instream.Close();
         return str;
     }
     catch (System.IO.FileNotFoundException)
     {
         writeFile(name, "");
         return "";
     }
     catch (System.IO.DirectoryNotFoundException)
     {
         writeFile(name, "");
         return "";
     }
     catch (Exception)
     {
         Console.WriteLine("FileStream.readFile : Erreur lors de la lecture du fichier " + name);
         return "";
     }
 }
Ejemplo n.º 32
0
		//----< close file >---------------------------------------------

		public void close()
		{
			fs_.Close();
		}
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("No arguments were passed.");
                Console.ReadLine();  // Keep the console open.
                return;
            }

            var filePath = args[0];

            Console.WriteLine($"Processing {filePath}.");

            if (filePath.ToLower().EndsWith(".xlsx"))
            {
                var package = new ExcelPackage(new System.IO.FileInfo(filePath));

                filePath = filePath.Replace(".xlsx", ".csv");
                package.ConvertToCsv(filePath);

                package.Dispose();
            }

            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file =
                new System.IO.StreamReader(filePath);

            // Get the Header (Columns)
            var columns = new List <DataTableColumn> ();
            // Read first libe (Header or column names)
            var line1 = file.ReadLine();
            // Comma separated
            var arrNames = line1.Split(',');

            foreach (var colName in arrNames)
            {
                var col = new DataTableColumn();
                col.ColumnName = colName;
                columns.Add(col);
            }

            // get the rows
            while ((line = file.ReadLine()) != null)
            {
                var values = line.Split(',');
                var index  = 0;
                foreach (var value in values)
                {
                    columns[index++].Values.Add(value);
                }
            }

            file.Close();
            var dataTableName = "Data";

            var has = columns.FirstOrDefault(col => col.ColumnName == "Type");

            if (has != null)
            {
                dataTableName = has.Values[0];
            }

            var datatable = $"let {dataTableName} = datatable (" + appendColumns(columns) + ") [";

            datatable += Environment.NewLine;
            datatable += appendRows(columns);
            datatable += Environment.NewLine;
            datatable += "];";
            datatable += Environment.NewLine;
            datatable += dataTableName;
            Console.WriteLine(datatable);
            // TODO: Save as .kql for Kusto explorer
            var logPath   = ".\\Query.kql";
            var logFile   = System.IO.File.Create(logPath);
            var logWriter = new System.IO.StreamWriter(logFile);

            logWriter.WriteLine(datatable);
            logWriter.Dispose();
            TextCopy.Clipboard.SetText(datatable);
        }
Ejemplo n.º 34
0
        public void Restore(string backupName)
        {
            string Carpeta = backupName + System.IO.Path.DirectorySeparatorChar;

            Lfx.Environment.Folders.EnsurePathExists(this.BackupPath);

            if (Carpeta != null && Carpeta.Length > 0 && System.IO.Directory.Exists(this.BackupPath + Carpeta))
            {
                bool UsandoArchivoComprimido = false;

                Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Restaurando copia de seguridad", "Este proceso va a demorar varios minutos. Por favor no lo interrumpa");
                Progreso.Modal = true;

                /* Progreso.ChangeStatus("Descomprimiendo");
                 * // Descomprimir backup si está comprimido
                 * if (System.IO.File.Exists(BackupPath + Carpeta + "backup.7z")) {
                 *      Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(BackupPath + Carpeta + "backup.7z");
                 *      ArchivoComprimido.ExtractAll(BackupPath + Carpeta);
                 *      UsandoArchivoComprimido = true;
                 * } */

                Progreso.ChangeStatus("Eliminando datos actuales");
                using (Lfx.Data.IConnection ConnRestaurar = Lfx.Workspace.Master.GetNewConnection("Restauración de copia de seguridad") as Lfx.Data.IConnection) {
                    Progreso.ChangeStatus("Acomodando estructuras");
                    Lfx.Workspace.Master.Structure.TagList.Clear();
                    Lfx.Workspace.Master.Structure.LoadFromFile(this.BackupPath + Carpeta + "dbstruct.xml");
                    Lfx.Workspace.Master.CheckAndUpdateDatabaseVersion(true, true);

                    using (BackupReader Lector = new BackupReader(this.BackupPath + Carpeta + "dbdata.lbd"))
                        using (IDbTransaction Trans = ConnRestaurar.BeginTransaction()) {
                            ConnRestaurar.EnableConstraints(false);

                            Progreso.ChangeStatus("Incorporando tablas de datos");

                            Progreso.Max = (int)(Lector.Length / 1024);
                            string           TablaActual   = null;
                            string[]         ListaCampos   = null;
                            object[]         ValoresCampos = null;
                            int              CampoActual   = 0;
                            bool             EndTable      = false;
                            qGen.BuilkInsert Insertador    = new qGen.BuilkInsert();
                            do
                            {
                                string Comando = Lector.ReadString(4);
                                switch (Comando)
                                {
                                case ":TBL":
                                    TablaActual = Lector.ReadPrefixedString4();
                                    string NombreTabla;
                                    if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(TablaActual) && Lfx.Workspace.Master.Structure.Tables[TablaActual].Label != null)
                                    {
                                        NombreTabla = Lfx.Workspace.Master.Structure.Tables[TablaActual].Label;
                                    }
                                    else
                                    {
                                        NombreTabla = TablaActual.ToTitleCase();
                                    }
                                    EndTable = false;
                                    Progreso.ChangeStatus("Cargando " + NombreTabla);

                                    qGen.Delete DelCmd = new qGen.Delete(TablaActual);
                                    DelCmd.EnableDeleleteWithoutWhere = true;
                                    ConnRestaurar.ExecuteNonQuery(DelCmd);
                                    break;

                                case ":FDL":
                                    ListaCampos   = Lector.ReadPrefixedString4().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    ValoresCampos = new object[ListaCampos.Length];
                                    CampoActual   = 0;
                                    break;

                                case ":FLD":
                                    ValoresCampos[CampoActual++] = Lector.ReadField();
                                    break;

                                case ".ROW":
                                    qGen.Insert Insertar = new qGen.Insert(TablaActual);
                                    for (int i = 0; i < ListaCampos.Length; i++)
                                    {
                                        Insertar.ColumnValues.AddWithValue(ListaCampos[i], ValoresCampos[i]);
                                    }
                                    Insertador.Add(Insertar);

                                    ValoresCampos = new object[ListaCampos.Length];
                                    CampoActual   = 0;
                                    break;

                                case ":REM":
                                    Lector.ReadPrefixedString4();
                                    break;

                                case ".TBL":
                                    EndTable = true;
                                    break;
                                }
                                if (EndTable || Insertador.Count >= 1000)
                                {
                                    if (Insertador.Count > 0)
                                    {
                                        ConnRestaurar.ExecuteNonQuery(Insertador);
                                    }
                                    Insertador.Clear();
                                    Progreso.Value = (int)(Lector.Position / 1024);
                                }
                            } while (Lector.Position < Lector.Length);
                            Lector.Close();

                            if (Lfx.Workspace.Master.MasterConnection.SqlMode == qGen.SqlModes.PostgreSql)
                            {
                                // PostgreSql: Tengo que actualizar las secuencias
                                Progreso.ChangeStatus("Actualizando secuencias");
                                string PatronSecuencia = @"nextval\(\'(.+)\'(.*)\)";
                                foreach (string Tabla in Lfx.Data.DatabaseCache.DefaultCache.GetTableNames())
                                {
                                    string OID = ConnRestaurar.FieldString("SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE pg_catalog.pg_table_is_visible(c.oid) AND c.relname ~ '^" + Tabla + "$'");
                                    System.Data.DataTable Campos = ConnRestaurar.Select("SELECT a.attname,pg_catalog.format_type(a.atttypid, a.atttypmod),(SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum FROM pg_catalog.pg_attribute a WHERE a.attrelid = '" + OID + "' AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum");
                                    foreach (System.Data.DataRow Campo in Campos.Rows)
                                    {
                                        if (Campo[2] != DBNull.Value && Campo[2] != null)
                                        {
                                            string DefaultCampo = System.Convert.ToString(Campo[2]);
                                            if (Regex.IsMatch(DefaultCampo, PatronSecuencia))
                                            {
                                                string NombreCampo = System.Convert.ToString(Campo[0]);
                                                foreach (System.Text.RegularExpressions.Match Ocurrencia in Regex.Matches(DefaultCampo, PatronSecuencia))
                                                {
                                                    string Secuencia = Ocurrencia.Groups[1].ToString();
                                                    int    MaxId     = ConnRestaurar.FieldInt("SELECT MAX(" + NombreCampo + ") FROM " + Tabla) + 1;
                                                    ConnRestaurar.ExecuteNonQuery("ALTER SEQUENCE " + Secuencia + " RESTART WITH " + MaxId.ToString());
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (System.IO.File.Exists(this.BackupPath + Carpeta + "blobs.lst"))
                            {
                                // Incorporar Blobs
                                Progreso.ChangeStatus("Incorporando imágenes");
                                System.IO.StreamReader LectorBlobs = new System.IO.StreamReader(this.BackupPath + Carpeta + "blobs.lst", System.Text.Encoding.Default);
                                string InfoImagen = null;
                                do
                                {
                                    InfoImagen = LectorBlobs.ReadLine();
                                    if (InfoImagen != null && InfoImagen.Length > 0)
                                    {
                                        string Tabla               = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string Campo               = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string CampoId             = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string NombreArchivoImagen = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");

                                        // Guardar blob nuevo
                                        qGen.Update ActualizarBlob = new qGen.Update(Tabla);
                                        ActualizarBlob.WhereClause = new qGen.Where(Campo, CampoId);

                                        System.IO.FileStream ArchivoImagen = new System.IO.FileStream(this.BackupPath + Carpeta + NombreArchivoImagen, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                        byte[] Contenido = new byte[System.Convert.ToInt32(ArchivoImagen.Length) - 1 + 1];
                                        ArchivoImagen.Read(Contenido, 0, System.Convert.ToInt32(ArchivoImagen.Length));
                                        ArchivoImagen.Close();

                                        ActualizarBlob.ColumnValues.AddWithValue(Campo, Contenido);
                                        ConnRestaurar.ExecuteNonQuery(ActualizarBlob);
                                    }
                                }while (InfoImagen != null);
                                LectorBlobs.Close();
                            }

                            if (UsandoArchivoComprimido)
                            {
                                Progreso.ChangeStatus("Eliminando archivos temporales");
                                // Borrar los archivos que descomprim temporalmente
                                System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(this.BackupPath + Carpeta);
                                foreach (System.IO.FileInfo DirItem in Dir.GetFiles())
                                {
                                    if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt")
                                    {
                                        System.IO.File.Delete(this.BackupPath + Carpeta + DirItem.Name);
                                    }
                                }
                            }
                            Progreso.ChangeStatus("Terminando transacción");
                            Trans.Commit();
                        }
                    Progreso.End();
                }

                Lfx.Workspace.Master.RunTime.Toast("La copia de seguridad se restauró con éxito. A continuación se va a reiniciar la aplicación.", "Copia Restaurada");
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Liest den Inhalt der unformatierten
        /// Textdatei beschrieben im Pfad.
        /// </summary>
        protected void Lesen()
        {
            Textdatei.Ausgeben("Textdatei.Lesen startet...", AusgabeModus.Debug);

            try
            {
                //Datei öffnen
                //var Leser = new System.IO.StreamReader(this.Pfad);
                //                              sympathischer Konstruktor, hat
                //                              aber den falschen Zeichensatz, Ä, Ö, ... fehlen
                var Leser = new System.IO.StreamReader(this.Pfad, System.Text.Encoding.Default);
                //                                                               ^-> .Net kann jeden Zeichensatz darstellen
                //                                                                   System.Text.Encoding unbedingt merken
                //                              ^-> weil der StreamReader-Konstruktor
                //                                  Ausnahmen auslöst (steht im Tool-Tipp Kommentar!),
                //                                  eine Fehlerbehandlung notwendig

                //Mit einer Abweiseschleife, solange wir nicht am Ende sind
                while (!Leser.EndOfStream)
                {
                    this.Zeilen.Add(Leser.ReadLine().Trim());
                }

                //Datei schließen
                Leser.Close();  //Es gibt Objekte, wo neben dem Dispose() auch
                                //eine Close() Methode vorhanden ist.
                                //In diesem Fall genügt, eine der beiden
                                //Methoden aufzurufen
                                //Leser.Dispose();
                Leser = null;
            }
            catch (System.Exception ex)
            {
                //Was tun im Fehlerfall?

                //Wir sind einer Klasse und haben beim
                //Tippen der Klasse keine Ahnung, wer, wo
                //ein Objekt unserer Klasse benutzt.
                //
                //D E S H A L B :
                //====> NIE MIT DEM BENUTZER REDEN!
                //      (Keine Messageboxes oder Sonstiges)
                //
                //Also, was tun?
                //-> eine Möglichkeit:
                //   Weiter abstürzen
                //throw new System.Exception("Bessere Meldung");

                //-> andere Möglichkeit:
                //   Windows Protokolleinträge
                //System.Diagnostics.EventLog.WriteEntry(....
                //                      ^-> das benötigt eine Quelle
                //System.Diagnostics.EventLog.CreateEventSource(....
                //                                  ^-> nur mit Adminrechten möglich
                //=> Der Trainer hat das aufgegeben, weil
                //   Administratoren kein Verständig dafür haben

                //-> eigenes Protokoll (im Teil 2)
                //

                //=> State of the Art
                //
                //-> Lieber Objektbenutzer, kümmere dich selber um das Problem
                //=> Ein Ereignis auslösen

                this.OnLeseFehlerAufgetreten(new FehlerAufgetretenEventArgs(ex));
            }

            Textdatei.Ausgeben("Textdatei.Lesen beendet.", AusgabeModus.Debug);
        }
Ejemplo n.º 36
0
        private void Run_Click(object sender, RoutedEventArgs e)
        {
            string Path = "";

            if (Desktop.IsChecked == true)
            {
                Path = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            }
            if (Doc.IsChecked == true)
            {
                Path = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            }
            //if (Nini.IsChecked == true) Path = textBox2.Text;
            if (Path == "")
            {
                //
                MessageBox.Show("選択してください");
            }
            else
            {
                if (Forms.IsChecked == true)
                {
                    System.IO.DirectoryInfo di =
                        System.IO.Directory.CreateDirectory(Path + @"\" + textBox1.Text + @"\source");
                    System.IO.DirectoryInfo di1 =
                        System.IO.Directory.CreateDirectory(Path + @"\" + textBox1.Text + @"\build");
                    System.IO.StreamWriter prof = new System.IO.StreamWriter(
                        Path + @"\" + textBox1.Text + @"\ProjectInfo.projectt",
                        false,
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    prof.WriteLine("/////決してこのファイルを編集しないでください/////");
                    prof.WriteLine(textBox1.Text);
                    prof.WriteLine("kind:forms");
                    prof.Close();
                    Hensu.RunHikisu = Path + @"\" + textBox1.Text + @"\ProjectInfo.projectt";
                    System.IO.StreamWriter mainCS = new System.IO.StreamWriter(
                        Path + @"\" + textBox1.Text + @"\source\main.cs",
                        false,
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    mainCS.WriteLine("using System;");
                    mainCS.WriteLine("using System.CodeDom;");
                    mainCS.WriteLine("using System.CodeDom.Compiler;");
                    mainCS.WriteLine("using System.Reflection;");
                    mainCS.WriteLine("using System.Windows.Forms;");
                    mainCS.WriteLine("using System.Drawing;");
                    mainCS.WriteLine("namespace " + textBox1.Text);
                    System.IO.StreamReader sr = new System.IO.StreamReader(
                        @"AppData\res\form\main.cs",
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    //内容をすべて読み込む
                    string s = sr.ReadToEnd();
                    //閉じる
                    sr.Close();
                    mainCS.WriteLine(s);

                    mainCS.Close();


                    System.IO.StreamWriter sw = new System.IO.StreamWriter(
                        Path + @"\" + textBox1.Text + @"\source\Form1.cs",
                        false,
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    sw.WriteLine("using System;");
                    sw.WriteLine("using System.CodeDom;");
                    sw.WriteLine("using System.CodeDom.Compiler;");
                    sw.WriteLine("using System.Reflection;");
                    sw.WriteLine("using System.Windows.Forms;");
                    sw.WriteLine("using System.Drawing;");
                    sw.WriteLine("namespace " + textBox1.Text);
                    System.IO.StreamReader sr1 = new System.IO.StreamReader(
                        @"AppData\res\form\form1.cs",
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    //内容をすべて読み込む
                    string s1 = sr1.ReadToEnd();
                    //閉じる
                    sr1.Close();
                    sw.WriteLine(s1);
                    //閉じる
                    sw.Close();
                    //guidate
                    var guiBook = new XLWorkbook();
                    var guiDate = guiBook.AddWorksheet("guiDate");
                    guiDate.Cell(1, 1).Value = "Form";
                    guiDate.Cell(1, 2).Value = "Form1";
                    guiDate.Cell(1, 3).Value = "Size";
                    guiDate.Cell(1, 4).Value = "200:300";
                    guiBook.SaveAs(Path + @"\" + textBox1.Text + @"\source\Form1.xlsx");
                    //event
                    System.IO.StreamWriter sw2 = new System.IO.StreamWriter(
                        Path + @"\" + textBox1.Text + @"\source\Form1.eve",
                        false,
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    sw2.WriteLine("Form/Form1/;");
                    sw2.Close();
                }
                if (Console.IsChecked == true)
                {
                    System.IO.DirectoryInfo di =
                        System.IO.Directory.CreateDirectory(Path + @"\" + textBox1.Text + @"\source");
                    System.IO.DirectoryInfo di1 =
                        System.IO.Directory.CreateDirectory(Path + @"\" + textBox1.Text + @"\build");
                    System.IO.StreamWriter prof = new System.IO.StreamWriter(
                        Path + @"\" + textBox1.Text + @"\ProjectInfo.projectt",
                        false,
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    prof.WriteLine("/////決してこのファイルを編集しないでください/////");
                    prof.WriteLine(textBox1.Text);
                    prof.WriteLine("kind:console");
                    prof.Close();
                    Hensu.RunHikisu = Path + @"\" + textBox1.Text + @"\ProjectInfo.projectt";
                    System.IO.StreamWriter mainCS = new System.IO.StreamWriter(
                        Path + @"\" + textBox1.Text + @"\source\main.cs",
                        false,
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    mainCS.WriteLine("using System;");
                    mainCS.WriteLine("namespace " + textBox1.Text);
                    mainCS.WriteLine("{");
                    mainCS.WriteLine("\tstatic class main");
                    mainCS.WriteLine("\t{");
                    mainCS.WriteLine("\t\t[STAThread]");
                    mainCS.WriteLine("\t\tstatic void Main()");
                    mainCS.WriteLine("\t\t{");
                    mainCS.WriteLine("\t\t\t");
                    mainCS.WriteLine("\t\t}");
                    mainCS.WriteLine("\t}");
                    mainCS.WriteLine("}");
                    mainCS.Close();
                }
                if (WPF.IsChecked == true)
                {
                    //MessageBox.Show("WPFはまだ実装されていません。代わりにFormsアプリケーションを生成します。");
                    System.IO.DirectoryInfo di =
                        System.IO.Directory.CreateDirectory(Path + @"\" + textBox1.Text + @"\source");
                    System.IO.DirectoryInfo di1 =
                        System.IO.Directory.CreateDirectory(Path + @"\" + textBox1.Text + @"\build");
                    System.IO.StreamWriter prof = new System.IO.StreamWriter(
                        Path + @"\" + textBox1.Text + @"\ProjectInfo.projectt",
                        false,
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    prof.WriteLine("/////決してこのファイルを編集しないでください/////");
                    prof.WriteLine(textBox1.Text);
                    prof.WriteLine("kind:wpf");
                    prof.Close();
                    Hensu.RunHikisu = Path + @"\" + textBox1.Text + @"\ProjectInfo.projectt";
                    System.IO.StreamWriter appF = new System.IO.StreamWriter(
                        Path + @"\" + textBox1.Text + @"\source\app.xaml",
                        false,
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    appF.WriteLine(@"<Application x:Class=""" + textBox1.Text + @".App""");
                    appF.WriteLine("\t\t" + @"xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""");
                    appF.WriteLine("\t\t" + @"xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""");
                    appF.WriteLine("\t\t" + @"xmlns:local=""clr -namespace:" + textBox1.Text + @"""");
                    appF.WriteLine("\t\t" + @"StartupUri=""MainWindow.xaml"">");
                    appF.WriteLine("\t" + @"<Application.Resources>");
                    appF.WriteLine("\t" + @"</Application.Resources>");
                    appF.WriteLine(@"</Application>");
                    appF.Close();
                    System.IO.StreamWriter MainW = new System.IO.StreamWriter(
                        Path + @"\" + textBox1.Text + @"\source\MainWindow.xaml",
                        false,
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    MainW.WriteLine(@"<Window x:Class=""" + textBox1.Text + @".MainWindow""");
                    MainW.WriteLine("\t\t" + @"xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""");
                    MainW.WriteLine("\t\t" + @"xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""");
                    MainW.WriteLine("\t\t" + @"xmlns:d=""http://schemas.microsoft.com/expression/blend/2008""");
                    MainW.WriteLine("\t\t" + @"xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006""");
                    MainW.WriteLine("\t\t" + @"xmlns:local=""clr-namespace:""" + textBox1.Text + @"""");
                    MainW.WriteLine("\t\t" + @"mc:Ignorable=""d""");
                    MainW.WriteLine("\t\t" + @"Title=""MainWindow"" Height=""350"" Width=""525"">");
                    MainW.WriteLine("\t" + @"<Grid>");
                    MainW.WriteLine("\t\t");
                    MainW.WriteLine("\t" + @"</Grid>");
                    MainW.WriteLine(@"</Window>");
                    MainW.WriteLine(@"");
                    MainW.Close();
                    System.IO.StreamWriter mainCS = new System.IO.StreamWriter(
                        Path + @"\" + textBox1.Text + @"\source\main.cs",
                        false,
                        System.Text.Encoding.GetEncoding("shift_jis"));
                    mainCS.WriteLine("using System;");
                    mainCS.WriteLine("namespace " + textBox1.Text);
                    mainCS.WriteLine("{");
                    mainCS.WriteLine("\tstatic class main");
                    mainCS.WriteLine("\t{");
                    mainCS.WriteLine("\t\t");
                    mainCS.WriteLine("\t}");
                    mainCS.WriteLine("}");
                    mainCS.Close();
                }
                if (IotA.IsChecked == true)
                {
                }
            }

            this.Close();
        }
Ejemplo n.º 37
0
        public DataTable GetDataCSV196(string ruta196)
        {
            try
            {
                String    LineaTexto = String.Empty;
                String    nombre_archivo196;
                DataTable dtReporte196 = new DataTable("Reporte196");

                dtReporte196.Columns.Add("Unidad de Negocio", typeof(String));
                dtReporte196.Columns.Add("Fecha", typeof(DateTime));
                dtReporte196.Columns.Add("PPU", typeof(String));
                dtReporte196.Columns.Add("Tipo de GPS", typeof(String));
                dtReporte196.Columns.Add("Servicio", typeof(String));
                dtReporte196.Columns.Add("Sentido", typeof(String));
                dtReporte196.Columns.Add("Intervalo", typeof(String));
                dtReporte196.Columns.Add("Operativo", typeof(String));
                dtReporte196.Columns.Add("KM Intervalo", typeof(Double));
                dtReporte196.Columns.Add("KM del viaje en intervalo", typeof(Double));
                dtReporte196.Columns.Add("Fecha Inicio Viaje", typeof(DateTime));
                dtReporte196.Columns.Add("Fecha Fin Viaje", typeof(DateTime));
                dtReporte196.Columns.Add("Tiempo de este viaje", typeof(Double));
                dtReporte196.Columns.Add("Tiempo total de viaje del intervalo", typeof(Double));
                dtReporte196.Columns.Add("Tiempo de Viaje", typeof(String));
                dtReporte196.Columns.Add("Inicio y Fin de Ruta", typeof(String));
                dtReporte196.Columns.Add("120 Minutos Antes", typeof(String));
                dtReporte196.Columns.Add("120 Minutos Despues", typeof(String));
                dtReporte196.Columns.Add("PC cada 2 Km", typeof(String));
                dtReporte196.Columns.Add("Igual Servicio", typeof(String));

                String[] SplitLine;;
                Int32    intContador = 0;
                nombre_archivo196 = System.IO.Path.GetFileName(ruta196);

                label1.Text = nombre_archivo196;

                if (System.IO.File.Exists(ruta196) == true)
                {
                    Int32 contColumnas = 0;
                    var   objReader    = new System.IO.StreamReader(ruta196);
                    while (objReader.Peek() != -1)
                    {
                        LineaTexto   = objReader.ReadLine();
                        SplitLine    = LineaTexto.Split(';');
                        contColumnas = SplitLine.Count();

                        if (intContador > 7)
                        {
                            Dictionary <String, String> diccionario = new Dictionary <string, string>();
                            diccionario.Add("I", "Ida");
                            diccionario.Add("IDA", "Ida");
                            diccionario.Add("R", "Ret");
                            diccionario.Add("RETORNO", "Ret");
                            diccionario.Add("REGRESO", "Ret");

                            String unidad_negocio  = SplitLine[0].Trim();
                            String PPU             = SplitLine[2].Trim();
                            String GPS             = SplitLine[3].Trim();
                            String Servicio        = SplitLine[4].Replace(" ", "").ToUpper();
                            String Sentido         = SplitLine[5].Trim().ToUpper();
                            String Intervalo       = SplitLine[6].Trim();
                            String Operativo       = SplitLine[7].Trim();
                            String tiempos_viaje   = SplitLine[14];
                            String Inicio_fin_ruta = SplitLine[15];
                            String min_120_antes   = SplitLine[16];
                            String min_120_despues = SplitLine[17];
                            String pc_cada2km      = SplitLine[18];
                            String igual_servicio  = SplitLine[19];

                            ///Creamos las filas en el DataTable

                            DataRow NuevaFila = dtReporte196.NewRow();

                            NuevaFila[0] = unidad_negocio;

                            if (IsDate(SplitLine[1]))
                            {
                                NuevaFila[1] = Convert.ToDateTime(SplitLine[1]);
                            }

                            NuevaFila[2] = PPU;
                            NuevaFila[3] = GPS;

                            NuevaFila[4] = Servicio;

                            NuevaFila[5] = Sentido;
                            NuevaFila[6] = Intervalo;
                            NuevaFila[7] = Operativo;

                            if (IsNumeric(SplitLine[8]))
                            {
                                NuevaFila[8] = SplitLine[8];
                            }

                            if (IsNumeric(SplitLine[9]))
                            {
                                NuevaFila[9] = SplitLine[9];
                            }

                            if (IsDate(SplitLine[10]))
                            {
                                NuevaFila[10] = Convert.ToDateTime(SplitLine[10]);
                            }

                            if (IsDate(SplitLine[11]))
                            {
                                NuevaFila[11] = Convert.ToDateTime(SplitLine[11]);
                            }

                            if (IsNumeric(SplitLine[12]))
                            {
                                NuevaFila[12] = SplitLine[12];
                            }

                            if (IsNumeric(SplitLine[13]))
                            {
                                NuevaFila[13] = SplitLine[13];
                            }

                            NuevaFila[14] = tiempos_viaje;
                            NuevaFila[15] = Inicio_fin_ruta;
                            NuevaFila[16] = min_120_antes;
                            NuevaFila[17] = min_120_despues;
                            NuevaFila[18] = pc_cada2km;
                            NuevaFila[19] = igual_servicio;

                            dtReporte196.Rows.Add(NuevaFila);
                        }
                        intContador = intContador + 1;
                    }
                    objReader.Close();
                }
                else
                {
                    MessageBox.Show("No Existe el Archivo");
                }
                return(dtReporte196);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }
        }
Ejemplo n.º 38
0
 public void Dispose()
 {
     _sr.Close();
 }
Ejemplo n.º 39
0
        // raiddata-e.txt
        // raiddata_begin	id=1	npc_id=29001	npc_level=40	affiliated_area_id=30	loc_x=-21610.000000	loc_y=181594.000000	loc_z=-5734.000000	raid_desc=[]	raiddata_end
        // -> raiddata_begin	id=139	npc_id=25333	npc_level=28	affiliated_area_id=179	loc_x=0.000000	loc_y=0.000000	loc_z=0.000000	raid_desc=[A being that tries to invade the real world by crossing the Dimensional Rift along with the otherworldly devils. Its shape is very unstable because of the Rift's distortion of time and space.]	raiddata_end

        // npcname-e.txt
        // npcname_begin	id=25001	name=[Greyclaw Kutus]	description=[Raid Boss]	rgb[0]=3F	rgb[1]=8B	rgb[2]=FE	reserved1=-1	npcname_end
        // npcname_begin	id=25002	name=[Guard of Kutus]	description=[Raid Fighter]	rgb[0]=3F	rgb[1]=8B	rgb[2]=FE	reserved1=-1	npcname_end
        // npc_pch.txt
        // [hatchling_of_wind] = 1012311


        private void StartButton_Click(object sender, EventArgs e)
        {
            string sRBFile      = "raiddata-e.txt";
            string sNpcNameFile = "npcname-e.txt";
            string sNpcPchFile  = "npc_pch.txt";

            string sRBAIFile = "announce_raid_boss_position_all_rb.txt";
            string sRBNpcPos = "npcpos_all_rb.txt";

            OpenFileDialog.FileName = sRBFile;
            OpenFileDialog.Filter   = "Lineage II client Raid Boss position file (raiddata-e.txt)|raiddata*.txt|All files|*.*";
            if (OpenFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            sRBFile = OpenFileDialog.FileName;

            OpenFileDialog.FileName = sNpcNameFile;
            OpenFileDialog.Filter   = "Lineage II client npcname file (npcname-e.txt)|npcname*.txt|All files|*.*";
            if (OpenFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            sNpcNameFile = OpenFileDialog.FileName;

            OpenFileDialog.FileName = sNpcPchFile;
            OpenFileDialog.Filter   = "Lineage II server npc file (npc_pch.txt)|npc_pch.txt|All files|*.*";
            if (OpenFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            sNpcPchFile = OpenFileDialog.FileName;

            SaveFileDialog.FileName = sRBAIFile;
            SaveFileDialog.Filter   = "Lineage II Raid Boss AI.obj class (announce_raid_boss_position_all_rb.txt)|*.txt|All files|*.*";
            if (SaveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            sRBAIFile = SaveFileDialog.FileName;

            SaveFileDialog.FileName = sRBNpcPos;
            SaveFileDialog.Filter   = "Lineage II Raid Boss Npcpos(announce_raid_boss_position_all_rb.txt)|*.txt|All files|*.*";
            if (SaveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            sRBNpcPos = SaveFileDialog.FileName;

            System.IO.StreamReader inFile;             // = Nothing
            System.IO.StreamWriter outFile;

            var aNpcPch = new string[1];                // storage for ids (29001,25001,...)
            var aBase   = new RaidBoss[1];

            string sTemp;
            int    iTemp;

            string[] aTemp;

            // Reading NpcPch file
            inFile = new System.IO.StreamReader(sNpcPchFile, System.Text.Encoding.Default, true, 1);
            ToolStripProgressBar.Value   = 0;
            ToolStripProgressBar.Maximum = Conversions.ToInteger(inFile.BaseStream.Length);
            while (inFile.EndOfStream != true)
            {
                sTemp = inFile.ReadLine();
                sTemp = sTemp.Trim().Replace(" ", "");
                aTemp = sTemp.Split(Conversions.ToChar("="));

                // npc_pch.txt
                // [hatchling_of_wind] = 1012311

                if (Conversions.ToInteger(aTemp[1].Substring(2, 5)) >= aNpcPch.Length)
                {
                    Array.Resize(ref aNpcPch, Conversions.ToInteger(aTemp[1].Substring(2, 5)) + 1);
                }
                aNpcPch[aNpcPch.Length - 1] = aTemp[0];

                ToolStripProgressBar.Value = Conversions.ToInteger(inFile.BaseStream.Position);
            }
            ToolStripProgressBar.Value = 0;
            inFile.Close();

            // Reading raiddata-e.txt file
            inFile = new System.IO.StreamReader(sRBFile, System.Text.Encoding.Default, true, 1);
            ToolStripProgressBar.Value   = 0;
            ToolStripProgressBar.Maximum = Conversions.ToInteger(inFile.BaseStream.Length);
            while (inFile.EndOfStream != true)
            {
                sTemp = inFile.ReadLine();

                // raiddata-e.txt
                // raiddata_begin	id=1	npc_id=29001	npc_level=40	affiliated_area_id=30	loc_x=-21610.000000	loc_y=181594.000000	loc_z=-5734.000000	raid_desc=[]	raiddata_end
                // -> raiddata_begin	id=139	npc_id=25333	npc_level=28	affiliated_area_id=179	loc_x=0.000000	loc_y=0.000000	loc_z=0.000000	raid_desc=[A being that tries to invade the real world by crossing the Dimensional Rift along with the otherworldly devils. Its shape is very unstable because of the Rift's distortion of time and space.]	raiddata_end

                iTemp = Conversions.ToInteger(Libraries.GetNeedParamFromStr(sTemp, "npc_id"));
                if (!string.IsNullOrEmpty(aNpcPch[iTemp]))
                {
                    Array.Resize(ref aBase, aBase.Length + 1);
                    aBase[aBase.Length - 1].PchName = aNpcPch[iTemp];
                    aBase[aBase.Length - 1].Id      = iTemp;
                    iTemp = aBase.Length - 1;
                    aBase[iTemp].Level = Conversions.ToInteger(Libraries.GetNeedParamFromStr(sTemp, "npc_level"));
                    aBase[iTemp].LocX  = Conversions.ToInteger(Libraries.GetNeedParamFromStr(sTemp, "loc_x"));
                    aBase[iTemp].LocY  = Conversions.ToInteger(Libraries.GetNeedParamFromStr(sTemp, "loc_y"));
                    aBase[iTemp].LocZ  = Conversions.ToInteger(Libraries.GetNeedParamFromStr(sTemp, "loc_z"));
                }

                ToolStripProgressBar.Value = Conversions.ToInteger(inFile.BaseStream.Position);
            }
            ToolStripProgressBar.Value = 0;
            inFile.Close();

            // Reading npcname-e.txt file
            inFile = new System.IO.StreamReader(sNpcNameFile, System.Text.Encoding.Default, true, 1);
            ToolStripProgressBar.Value   = 0;
            ToolStripProgressBar.Maximum = Conversions.ToInteger(inFile.BaseStream.Length);
            int    iTempLevel;
            int    iPrevBossId = -1;
            string sTemp2;

            while (inFile.EndOfStream != true)
            {
                sTemp = inFile.ReadLine();

                // npcname-e.txt
                // npcname_begin	id=25001	name=[Greyclaw Kutus]	description=[Raid Boss]	rgb[0]=3F	rgb[1]=8B	rgb[2]=FE	reserved1=-1	npcname_end
                // npcname_begin	id=25002	name=[Guard of Kutus]	description=[Raid Fighter]	rgb[0]=3F	rgb[1]=8B	rgb[2]=FE	reserved1=-1	npcname_end
                iTemp = Conversions.ToInteger(Libraries.GetNeedParamFromStr(sTemp, "id"));
                var loopTo = aBase.Length - 1;
                for (iTempLevel = 0; iTempLevel <= loopTo; iTempLevel++)
                {
                    if (aBase[iTempLevel].Id == iTemp)
                    {
                        aBase[iTempLevel].Name = Libraries.GetNeedParamFromStr(sTemp, "name").Replace("[", "").Replace("]", "");
                        // aBase(aBase.Length - 1).Privates = Libraries.GetNeedParamFromStr(sTemp, "description")
                        iPrevBossId = iTempLevel;
                    }
                }

                if (GenPrivatesCheckBox.Checked == true)
                {
                    // iPrevBossId
                    sTemp2 = Libraries.GetNeedParamFromStr(sTemp, "description");
                    if (sTemp2.StartsWith("[Raid ") == true & sTemp2.StartsWith("[Raid Boss") == false)
                    {
                        // Found privates
                        iTemp = Conversions.ToInteger(Libraries.GetNeedParamFromStr(sTemp, "id"));
                        if (iTemp != -1)
                        {
                            if (!string.IsNullOrEmpty(aBase[iPrevBossId].Privates))
                            {
                                aBase[iPrevBossId].Privates = aBase[iPrevBossId].Privates + ";";
                            }
                            aBase[iPrevBossId].Privates = aBase[iPrevBossId].Privates + aNpcPch[iTemp].Replace("[", "").Replace("]", "");
                        }
                    }
                }

                ToolStripProgressBar.Value = Conversions.ToInteger(inFile.BaseStream.Position);
            }
            ToolStripProgressBar.Value = 0;
            inFile.Close();


            // WRITE AI class 'announce_raid_boss_position.txt'
            outFile = new System.IO.StreamWriter(sRBAIFile, false, System.Text.Encoding.Unicode, 1);

            // Write header to AI class
            outFile.WriteLine("class 1 announce_raid_boss_position : citizen");
            outFile.WriteLine("parameter_define_begin");
            outFile.WriteLine(Constants.vbTab + "string fnHiPCCafe \"pc.htm\"");
            outFile.WriteLine("parameter_define_end");
            outFile.WriteLine("property_define_begin");
            int iTempLevel2;

            for (iTempLevel = 20; iTempLevel <= 90; iTempLevel += 10)
            {
                // telposlist_begin RaidBossList20_29
                outFile.WriteLine(Constants.vbTab + "telposlist_begin RaidBossList{0}_{1}", iTempLevel, iTempLevel + 9);

                for (iTempLevel2 = 0; iTempLevel2 <= 9; iTempLevel2++)                 // Step 10
                {
                    var loopTo1 = aBase.Length - 1;
                    for (iTemp = 0; iTemp <= loopTo1; iTemp++)
                    {
                        if (aBase[iTemp].Level == iTempLevel + iTempLevel2)
                        {
                            // {"Madness Beast (lv20)"; -54096; 84288; -3512; 0; 0 }
                            if (aBase[iTemp].LocX != 0)
                            {
                                // outFile.WriteLine(vbTab & vbTab & "{""" & aBase(iTemp).Name & " (lv" & aBase(iTemp).Level & ")""; " & aBase(iTemp).LocX & "; " & aBase(iTemp).LocY & "; " & aBase(iTemp).LocZ & "; 0; 0}")
                                outFile.WriteLine(Constants.vbTab + Constants.vbTab + "{\"" + aBase[iTemp].Name + " (lv" + Conversions.ToString(aBase[iTemp].Level) + ")\"; " + Conversions.ToString(aBase[iTemp].LocX) + "; " + Conversions.ToString(aBase[iTemp].LocY) + "; " + Conversions.ToString(aBase[iTemp].LocZ) + "; 0; 0}");
                            }
                        }
                    }
                }

                outFile.WriteLine(Constants.vbTab + "telposlist_end");
            }
            outFile.WriteLine("property_define_end");
            outFile.Close();


            // WRITE NpcPos'
            if (GenPosCheckBox.Checked == true)
            {
                outFile = new System.IO.StreamWriter(sRBNpcPos, false, System.Text.Encoding.Unicode, 1);

                // Write header to AI class

                // territory_begin	[aden24_mb2320_04]	{{123340;93852;-2464;-1864};{124204;93488;-2464;-1864};{124684;93960;-2464;-1864};{124512;94308;-2464;-1864};{123572;94656;-2464;-1864}}	territory_end
                // npcmaker_begin	[aden24_mb2320_04]	initial_spawn=all	maximum_npc=10
                // npc_begin	[kelbar]	pos=anywhere	total=1	respawn=36hour	respawn_rand=24hour	dbname=[kelbar]	dbsaving={death_time;parameters}	npc_end
                // npcmaker_end

                int iTemp2;
                var loopTo2 = aBase.Length - 1;
                for (iTemp = 0; iTemp <= loopTo2; iTemp++)
                {
                    if (aBase[iTemp].LocX != 0)
                    {
                        // territory_begin	[aden24_mb2320_04]	{{123340;93852;-2464;-1864};{124204;93488;-2464;-1864};{124684;93960;-2464;-1864};{124512;94308;-2464;-1864};{123572;94656;-2464;-1864}}	territory_end
                        outFile.Write("territory_begin" + Constants.vbTab);
                        outFile.Write("[raidboss" + Conversions.ToString(iTemp) + "_" + aBase[iTemp].PchName.Replace("[", "").Replace("]", "") + "]" + Constants.vbTab);
                        outFile.Write("{{" + Conversions.ToString(aBase[iTemp].LocX - 200) + ";" + Conversions.ToString(aBase[iTemp].LocY - 200) + ";" + Conversions.ToString(aBase[iTemp].LocZ - 100) + ";" + Conversions.ToString(aBase[iTemp].LocZ + 300) + "};");
                        outFile.Write("{" + Conversions.ToString(aBase[iTemp].LocX + 200) + ";" + Conversions.ToString(aBase[iTemp].LocY - 200) + ";" + Conversions.ToString(aBase[iTemp].LocZ - 100) + ";" + Conversions.ToString(aBase[iTemp].LocZ + 300) + "};");
                        outFile.Write("{" + Conversions.ToString(aBase[iTemp].LocX + 200) + ";" + Conversions.ToString(aBase[iTemp].LocY + 200) + ";" + Conversions.ToString(aBase[iTemp].LocZ - 100) + ";" + Conversions.ToString(aBase[iTemp].LocZ + 300) + "};");
                        outFile.Write("{" + Conversions.ToString(aBase[iTemp].LocX - 200) + ";" + Conversions.ToString(aBase[iTemp].LocY + 200) + ";" + Conversions.ToString(aBase[iTemp].LocZ - 100) + ";" + Conversions.ToString(aBase[iTemp].LocZ + 300) + "}");
                        outFile.WriteLine("}}" + Constants.vbTab + "territory_end");

                        // npcmaker_begin	[aden24_mb2320_04]	initial_spawn=all	maximum_npc=10
                        outFile.Write("npcmaker_begin" + Constants.vbTab);
                        outFile.Write("[raidboss" + Conversions.ToString(iTemp) + "_" + aBase[iTemp].PchName.Replace("[", "").Replace("]", "") + "]" + Constants.vbTab);
                        outFile.Write("initial_spawn=all" + Constants.vbTab);
                        outFile.WriteLine("maximum_npc=10");

                        // npc_begin	[kelbar]	pos=anywhere	total=1	respawn=36hour	respawn_rand=24hour	dbname=[kelbar]	dbsaving={death_time;parameters}	npc_end
                        // Privates=[talakin_archer:talakin_archer:1:0sec;talakin_raider:talakin_raider:1:0sec]
                        outFile.Write("npc_begin" + Constants.vbTab);
                        outFile.Write(aBase[iTemp].PchName + Constants.vbTab + "pos=anywhere" + Constants.vbTab + "total=1" + Constants.vbTab + "respawn=36hour" + Constants.vbTab + "respawn_rand=24hour" + Constants.vbTab + "dbname=" + aBase[iTemp].PchName + Constants.vbTab + "dbsaving={death_time;parameters}" + Constants.vbTab);

                        // Generate Privates list
                        if (GenPrivatesCheckBox.Checked == true)
                        {
                            if (!string.IsNullOrEmpty(aBase[iTemp].Privates))
                            {
                                outFile.Write("Privates=[");
                                aTemp = aBase[iTemp].Privates.Split(Conversions.ToChar(";"));
                                var loopTo3 = aTemp.Length - 1;
                                for (iTemp2 = 0; iTemp2 <= loopTo3; iTemp2++)
                                {
                                    outFile.Write(aTemp[iTemp2] + ":");
                                    outFile.Write(aTemp[iTemp2] + ":");
                                    outFile.Write("1:0sec");
                                    if (iTemp2 < aTemp.Length - 1)
                                    {
                                        outFile.Write(";");
                                    }
                                }
                                outFile.Write("]" + Constants.vbTab);
                            }
                        }

                        outFile.WriteLine("npc_end");

                        // npcmaker_end
                        outFile.WriteLine("npcmaker_end" + Constants.vbNewLine);
                    }
                }
                outFile.Close();
            }


            MessageBox.Show("Complete.");
        }
Ejemplo n.º 40
0
        static void FakeMain(string[] args)
        {
            Console.WriteLine(string.Join(',', args));
            if (args.Length > 0)
            {
                IList <string> gridStrings = new List <string> ();
                string         line;

                string fileName             = @"puzzles.txt";
                System.IO.StreamReader file = new System.IO.StreamReader(fileName);
                while ((line = file.ReadLine()) != null)
                {
                    if (line.Contains("Grid"))
                    {
                        continue;
                    }
                    else
                    {
                        gridStrings.Add(line.Trim());
                    }
                    System.Console.WriteLine(line);
                }

                file.Close();
                System.Console.WriteLine("{0} in {1}", gridStrings.Count, fileName);

                // TODO: Do initial solve to reduce jitter
                Console.WriteLine("Starting benchmarking");
                var solveTimes = new List <double> (new double[gridStrings.Count]);

                Stopwatch sw            = new Stopwatch();
                int       numIterations = 10;

                for (int i = 0; i < numIterations; i++)
                {
                    for (int j = 0; j < gridStrings.Count; j++)
                    {
                        var cpb = new CPBoard(gridStrings[j]);
                        cpb.Print();
                        Console.WriteLine(new String('-', 20));

                        sw.Restart();
                        var sr = CPSolver.Solve(cpb);
                        sw.Stop();

                        double ticks        = sw.ElapsedTicks;
                        double seconds      = ticks / Stopwatch.Frequency;
                        double milliseconds = (ticks / Stopwatch.Frequency) * 1000;
                        solveTimes[j] += milliseconds;

                        if (!sr.DidSolve)
                        {
                            throw new Exception($"Could not solve:\n {cpb.ToString()}");
                        }

                        sr.CPB.Print();
                    }
                }

                var averageTimes = solveTimes.Select(st => st / numIterations).ToList();
                var averageTime  = averageTimes.Average();
                Console.WriteLine($"Average solve time was: {averageTime}");
                for (int i = 0; i < averageTimes.Count; i++)
                {
                    Console.WriteLine($"Grid {i} : {averageTimes[i]}");
                }
            }
            else
            {
                string line;
                // Handle piped input
                Console.SetIn(new System.IO.StreamReader(Console.OpenStandardInput(8192)));    // This will allow input >256 chars
                while (Console.In.Peek() != -1)
                {
                    line = Console.In.ReadLine();

                    if (line.Contains("Grid"))
                    {
                        var puzzleName = line;
                        Console.WriteLine($"Attempting ${puzzleName}");
                    }
                    else
                    {
                        var cpb = new CPBoard(line);
                        cpb.Print();
                        Console.WriteLine(new String('-', 20));

                        var sr = CPSolver.Solve(cpb);
                        if (!sr.DidSolve)
                        {
                            throw new Exception($"Could not solve:\n {cpb.ToString()}");
                        }
                        sr.CPB.Print();
                    }
                }
            }
        }
        private void LoadGraph(ListBoxItem item)
        {
            Title = "Graph algorithms - " + item.Content.ToString().Remove(0, 1);
            string location = (item.Tag as string);

            ClearWindow();
            try
            {
                textBlock1.Text = string.Empty;
                var    reader = new System.IO.StreamReader(item.Tag as string);
                string file   = reader.ReadToEnd();
                reader.Close();
                var verticesInfo = file.Split('~', ';');
                for (int k = 0; k < verticesInfo.Length; k++)
                {
                    textBlock1.Text += "|" + verticesInfo[k] + "|";
                }
                int n1 = Convert.ToInt32(verticesInfo[0]);
                int c  = 0;
                for (int i = 1; i <= n1; i++, c = i)
                {
                    var verticesdata = verticesInfo[i].Split(',');
                    for (int j = 1; j < verticesdata.Length; j += 3)
                    {
                        if (verticesdata[j] != string.Empty)
                        {
                            AddNewVertex(Convert.ToDouble(verticesdata[j]), Convert.ToDouble(verticesdata[j + 1]), Convert.ToDouble(verticesdata[j + 2]));
                        }
                    }
                }
                c++;
                int n2 = Convert.ToInt32(verticesInfo[c]);
                for (int i = c + 1; i < c + n2; i++)
                {
                    var verticesdata = verticesInfo[i].Split(',');
                    for (int k = 0; k < verticesdata.Length; k++)
                    {
                        textBlock1.Text += "/" + verticesdata[k] + "/";
                    }
                    for (int j = 1; j < verticesdata.Length; j += 9)
                    {
                        if (verticesdata[j] != string.Empty)
                        {
                            AddNewConnection(Convert.ToDouble(verticesdata[j]),
                                             Convert.ToDouble(verticesdata[j + 1]),
                                             Convert.ToDouble(verticesdata[j + 2]),
                                             Convert.ToDouble(verticesdata[j + 3]),
                                             Convert.ToDouble(verticesdata[j + 4]),
                                             Convert.ToDouble(verticesdata[j + 5]),
                                             Convert.ToInt32(verticesdata[j + 6]),
                                             Convert.ToInt32(verticesdata[j + 7]),
                                             Convert.ToInt32(verticesdata[j + 8]));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                textBlock1.Text += "\nsomething went wrong\n" + ex.ToString();
                EnableControls();
            }
            EnableControls();
        }
Ejemplo n.º 42
0
        static void Main(string[] args)
        {
            System.IO.StreamReader workerFile =
                new System.IO.StreamReader(@"c:\Users\Kyle\Desktop\spring sem\adv prog\weeks\week7\worker.txt");


            int WarrSize = Convert.ToInt32(workerFile.ReadLine());


            Worker[] workerArr = new Worker[WarrSize];

            int Currentyear = 0;

            Console.Write("What is the current year: ");
            Currentyear = Convert.ToInt32(Console.ReadLine());

            for (int x = 0; x < WarrSize; x++)//cycle array
            {
                workerArr[x] = new Worker(
                    Currentyear,                             //current year
                    Convert.ToString(workerFile.ReadLine()), //fname
                    Convert.ToString(workerFile.ReadLine()), //lname
                    Convert.ToString(workerFile.ReadLine()), //workID
                    Convert.ToInt32(workerFile.ReadLine()),  //year started
                    Convert.ToDouble(workerFile.ReadLine())  //double initial salary,
                    );                                       //current salary
                //intake worker info line by line.
            }
            Console.WriteLine("\n--------------EMPLOYEES---------------------");

            foreach (var employee in workerArr)
            {
                Console.WriteLine(employee);
            }

            workerFile.Close();

            System.IO.StreamReader managerFile =
                new System.IO.StreamReader(@"c:\Users\Kyle\Desktop\spring sem\adv prog\weeks\week7\manager.txt");


            int MarrSize = Convert.ToInt32(managerFile.ReadLine());

            Manager[] Marr = new Manager[MarrSize];

            for (int x = 0; x < MarrSize; x++)//cycle array
            {
                Marr[x] = new Manager(

                    Currentyear,                              //current year
                    Convert.ToString(managerFile.ReadLine()), //fname
                    Convert.ToString(managerFile.ReadLine()), //lname
                    Convert.ToString(managerFile.ReadLine()), //workID
                    Convert.ToInt32(managerFile.ReadLine()),  //year started
                    Convert.ToDouble(managerFile.ReadLine()), // initial salary,
                    Convert.ToInt32(managerFile.ReadLine())   // promoted year
                    );
                //intake worker info line by line.
            }
            Console.WriteLine("\n--------------MANAGERS---------------------");
            foreach (var manager in Marr)
            {
                Console.WriteLine(manager);
            }

            managerFile.Close();



            Console.ReadLine();
        }
Ejemplo n.º 43
0
        static void Main(string[] args)
        {
            String M = "CRYPTOGRAPHY";
            String K = "BREAKBREAKBR";
            String C = "";
            int    n = 4, k0 = 3;
            int    k1 = 7;

            int[] k = { 3, 4, 1, 5, 2 };
            bool  b = true;

            while (b)
            {
                Console.WriteLine("Choose exercise: 1e | 1d | 2e | 2d | 31e | 31d | 32e | 32d | 4e | 4d | 5e | 5d | q");
                switch (Console.ReadLine())
                {
                case "1e":
                    Console.Write("Enter  M: ");
                    M = Console.ReadLine().ToUpper();
                    Console.Write("Enter  n: ");
                    n = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("       C: " + exercise1encode(M, n) + "\n\n\n");
                    break;

                case "1d":
                    System.IO.StreamReader file1 =
                        new System.IO.StreamReader(System.IO.Directory.GetCurrentDirectory() + @"\result1.txt");
                    C = file1.ReadLine();
                    n = Int32.Parse(file1.ReadLine());
                    file1.Close();
                    Console.WriteLine("Loaded C: " + C);
                    Console.WriteLine("Loaded n: " + n);
                    Console.Write("Enter  n: ");
                    n = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("       M: " + exercise1decode(C, n) + "\n\n\n");
                    break;

                case "2e":
                    Console.Write("Enter M:     ");
                    M = Console.ReadLine().ToUpper();
                    Console.Write("Enter key[]: ");
                    K = Console.ReadLine();
                    Console.WriteLine("       C:    " + exercise2encode(M, K) + "\n\n\n");
                    break;

                case "2d":
                    System.IO.StreamReader file2 =
                        new System.IO.StreamReader(System.IO.Directory.GetCurrentDirectory() + @"\result2.txt");
                    C = file2.ReadLine();
                    K = file2.ReadLine();
                    file2.Close();
                    Console.WriteLine("Loaded C:     " + C);
                    Console.WriteLine("Loaded key[]: " + K);
                    Console.Write("Enter  key[]: ");
                    K = Console.ReadLine();
                    Console.WriteLine("       M:     " + exercise2decode(C, K) + "\n\n\n");
                    break;

                case "31e":
                    Console.Write("Enter M:   ");
                    M = Console.ReadLine().ToUpper();
                    Console.Write("Enter KEY: ");
                    K = Console.ReadLine().ToUpper();
                    Console.WriteLine("      C:   " + exercise31encode(M, K) + "\n\n\n");
                    break;

                case "31d":
                    System.IO.StreamReader file3 =
                        new System.IO.StreamReader(System.IO.Directory.GetCurrentDirectory() + @"\result31.txt");
                    C = file3.ReadLine();
                    K = file3.ReadLine();
                    file3.Close();
                    Console.WriteLine("Loaded C:   " + C);
                    Console.WriteLine("Loaded KEY: " + K);
                    Console.Write("Enter  KEY: ");
                    K = Console.ReadLine();
                    Console.WriteLine("       M:   " + exercise31decode(C, K) + "\n\n\n");
                    break;

                case "32e":
                    Console.Write("Enter M:   ");
                    M = Console.ReadLine().ToUpper();
                    Console.Write("Enter KEY: ");
                    K = Console.ReadLine().ToUpper();
                    Console.WriteLine("      C:   " + exercise32encode(M, K) + "\n\n\n");
                    break;

                case "32d":
                    System.IO.StreamReader file32 =
                        new System.IO.StreamReader(System.IO.Directory.GetCurrentDirectory() + @"\result32.txt");
                    C = file32.ReadLine();
                    K = file32.ReadLine();
                    file32.Close();
                    Console.WriteLine("Loaded C:   " + C);
                    Console.WriteLine("Loaded KEY: " + K);
                    Console.Write("Enter  KEY: ");
                    K = Console.ReadLine();
                    Console.WriteLine("       M:   " + exercise32decode(C, K) + "\n\n\n");
                    break;

                case "4e":
                    Console.Write("Enter M:  ");
                    M = Console.ReadLine().ToUpper();
                    Console.Write("Enter k0: ");
                    k0 = Int32.Parse(Console.ReadLine());
                    Console.Write("Enter k1: ");
                    k1 = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("      C:  " + exercise4encode(M, k0, k1) + "\n\n\n");
                    break;

                case "4d":
                    System.IO.StreamReader file4 =
                        new System.IO.StreamReader(System.IO.Directory.GetCurrentDirectory() + @"\result4.txt");
                    C  = file4.ReadLine();
                    k0 = Int32.Parse(file4.ReadLine());
                    k1 = Int32.Parse(file4.ReadLine());
                    file4.Close();
                    Console.WriteLine("Loaded C:  " + C);
                    Console.WriteLine("Loaded k0: " + k0);
                    Console.WriteLine("Loaded k1: " + k1);
                    Console.Write("Enter  k0: ");
                    k0 = Int32.Parse(Console.ReadLine());
                    Console.Write("Enter  k1: ");
                    k1 = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("       M:  " + exercise4decode(C, k0, k1) + "\n\n\n");
                    break;

                case "5e":
                    Console.Write("Enter M: ");
                    M = Console.ReadLine().ToUpper();
                    Console.Write("Enter K: ");
                    K = Console.ReadLine().ToUpper();
                    Console.WriteLine("      C: " + exercise5encode(M, K) + "\n\n\n");
                    break;

                case "5d":
                    System.IO.StreamReader file5 =
                        new System.IO.StreamReader(System.IO.Directory.GetCurrentDirectory() + @"\result5.txt");
                    C = file5.ReadLine();
                    K = file5.ReadLine();
                    file5.Close();
                    Console.WriteLine("Loaded C: " + C);
                    Console.WriteLine("Loaded K: " + K);
                    Console.Write("Enter  K: ");
                    K = Console.ReadLine();
                    Console.WriteLine("       M: " + exercise5decode(C, K) + "\n\n\n");
                    break;

                case "q":
                    b = false;
                    break;
                }
            }
            Console.ReadKey();
        }
Ejemplo n.º 44
0
        internal void LoadSettings()
        {
            string s  = "";
            string s1 = "";
            string s2 = "";

            tItems = new List <Spectrum_TableItem>();

            tItem = new Spectrum_TableItem();

            System.IO.StreamReader textReader = new System.IO.StreamReader(fileName);

            Spectrum_TableItem tItem_temp;

            //加载补偿项
            while (!textReader.EndOfStream)
            {
                s = (textReader.ReadLine()).Trim();

                if (String.IsNullOrEmpty(s))
                {
                    continue;
                }

                s1 = IniFile.GetItemFrom(s, 0, 2);

                s2 = IniFile.GetItemFrom(s, 1, 2);

                try
                {
                    tItem_temp = new Spectrum_TableItem();

                    tItem_temp.f = Convert.ToSingle(s1);
                    tItem_temp.v = Convert.ToSingle(s2);
                    tItems.Add(tItem_temp);
                } catch (System.InvalidCastException)
                {
                }
            }

            textReader.Close();

            textReader.Dispose();

            Processing();

            if (tItems.Count > 0)
            {
                tItem.f1 = tItems[0].f1;
                tItem.v1 = tItems[0].v1;
                tItem.f  = tItems[0].f;
                tItem.v  = tItems[0].v;
                tItem.f2 = tItems[0].f2;
                tItem.v2 = tItems[0].v2;
            }
            else
            {
                tItem.f1 = float.MaxValue;
                tItem.v1 = float.MinValue;
                tItem.f  = float.MaxValue;
                tItem.v  = float.MinValue;
                tItem.f2 = float.MaxValue;
                tItem.v2 = float.MinValue;
            }
        }
Ejemplo n.º 45
0
        /// <summary>
        /// 上传媒体文件,如果上传成功,返回获取到的MediaID,否则,返回String.Empty
        /// </summary>
        private String UploadMedia(String file, String receiver, Int32 fileIndex = 0)
        {
            String toUser = receiver;

            System.Net.ServicePointManager.DefaultConnectionLimit = 100;
            //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            String         _result  = String.Empty;
            String         _url     = $"https://file.{m_Session.WXVer}.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json";
            HttpWebRequest _request = WebRequest.CreateHttp(_url);

            System.IO.FileStream fs = System.IO.File.Open(file, System.IO.FileMode.Open);
            byte[] content          = new byte[fs.Length];
            fs.Read(content, 0, content.Length);
            fs.Close();

            //_request.KeepAlive = false;
            _request.CookieContainer = m_Session.CookieContainer;
            _request.Timeout         = (Int32)TimeSpan.FromSeconds(20).TotalMilliseconds;
            _request.ProtocolVersion = HttpVersion.Version10;
            _request.Method          = "POST";
            _request.UserAgent       = m_Session.UserAgent;
            _request.Accept          = "*/*";


            String boundary = "----WebKitFormBoundaryXfoMzS2vayvACSgy";

            //_request.ContentType = "application/x-www-form-urlencoded";
            _request.ContentType = "multipart/form-data; boundary=" + boundary;
            //_request.ContentType = "multipart/form-data;";
            //_request.ContentLength = content.Length;
            System.IO.FileInfo          finfo = new System.IO.FileInfo(file);
            Dictionary <string, object> paras = new Dictionary <string, object>();

            paras.Add("id", "WU_FILE_" + fileIndex);
            paras.Add("name", finfo.Name);
            paras.Add("lastModifiedDate", finfo.LastWriteTimeUtc);
            paras.Add("size", finfo.Length);
            paras.Add("mediatype", "pic");
            paras.Add("uploadmediarequest", JsonConvert.SerializeObject(UploadMediaRequest.Get(toUser, m_Session, file)));
            paras.Add("webwx_data_ticket", m_Session.GetCookie("webwx_data_ticket"));
            paras.Add("pass_ticket", m_Session.pass_ticket);
            paras.Add("filename", new FileParameter(content, finfo.Name, "image/jpeg"));

            byte[] postData = GetMultipartFormData(paras, boundary);

            System.IO.Stream _stream = _request.GetRequestStream();
            _stream.Write(postData, 0, postData.Length);
            _stream.Close();



            HttpWebResponse response = (HttpWebResponse)_request.GetResponse();

            m_Session.AddCookies(response.Cookies);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                WriteLog("[上传文件]HTTP加载错误,HTTP请求状态:" + response.StatusCode);
            }

            System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
            String _responseText      = sr.ReadToEnd();

            sr.Close();
            response.Close();
            WriteLog("[上传文件]HTTP请求返回结果:" + _responseText);

            if (_responseText.Contains("\"MediaId\":"))
            {
                String mediaID = Regex.Match(_responseText, "(?<=\"MediaId\":).{1,}(?=\",)").Value;
                _result = mediaID;
            }

            return(_result);
        }
Ejemplo n.º 46
0
        static void Main(string[] args)
        {
            ParallelOptions paropts = new ParallelOptions {
                MaxDegreeOfParallelism = 1
            };

            Console.WriteLine("SolarModel V2.0");
            Console.WriteLine();
            Console.WriteLine("You will need: 2 txt files with hourly values for DHI and DNI respectively. They need to be named DNI.txt and DHI.txt");
            Console.WriteLine("Please define path for reading inputs and writing result files:");
            string path = Console.ReadLine(); //"C:\Users\wach\Desktop

            Console.WriteLine();

            //load in weather file DHI
            List <double> DHI     = new List <double>();
            List <double> DNI     = new List <double>();
            int           counter = 0;
            string        line;

            // Read the file and display it line by line.
            Console.WriteLine("Reading inputs...");
            System.IO.StreamReader file =
                new System.IO.StreamReader(path + "\\DHI.txt");
            while ((line = file.ReadLine()) != null)
            {
                DHI.Add(Convert.ToDouble(line));
                //Console.WriteLine(line);
                counter++;
            }
            file.Close();

            System.IO.StreamReader file2 = new System.IO.StreamReader(path + "\\DNI.txt");
            while ((line = file2.ReadLine()) != null)
            {
                DNI.Add(Convert.ToDouble(line));
                //Console.WriteLine(line);
                counter++;
            }
            file.Close();
            Console.WriteLine();



            int recursion = 2;      //resolution of skydome

            int    year;
            double longitude, latitude;

            Console.WriteLine("Longitude: ");
            if (!double.TryParse(Console.ReadLine(), out longitude))
            {
                Console.WriteLine("You need to input a real number. Hit any key to close.");
                Console.ReadLine();
            }
            Console.WriteLine("Latitude: ");
            if (!double.TryParse(Console.ReadLine(), out latitude))
            {
                Console.WriteLine("You need to input a real number. Hit any key to close.");
                Console.ReadLine();
            }
            Console.WriteLine("Year: ");
            if (!int.TryParse(Console.ReadLine(), out year))
            {
                Console.WriteLine("You need to input an integer number. Hit any key to close.");
                Console.ReadLine();
            }
            Console.WriteLine();
            //double longitude = 8.539;
            //double latitude = 47.370;
            //int year = 2005;



            List <SunVector> sunvectors;

            SunVector.Create8760SunVectors(out sunvectors, longitude, latitude, year);
            Context.cWeatherdata weather;
            weather.DHI  = new List <double>();
            weather.DNI  = new List <double>();
            weather.Snow = new List <double>();
            for (int i = 0; i < 8760; i++)
            {
                weather.DHI.Add(DHI[i]);
                weather.DNI.Add(DNI[i]);
            }

            Context.cLocation location;
            location.dLatitude  = latitude;
            location.dLongitude = longitude;
            location.dTgmt      = 1;


            Dictionary <string, double> albedos = new Dictionary <string, double>();

            albedos.Add("LAWN", 0.205);
            albedos.Add("UNTILTEDFIELD", 0.26);
            albedos.Add("NAKEDGROUND", 0.17);
            albedos.Add("CONCRETE", 0.3);
            albedos.Add("SNOW", 0.85);
            albedos.Add("OLDSNOW", 0.58);

            Console.WriteLine("Ground albedo: allowed inputs 'LAWN', 'UNTILTEDFIELD', 'NAKEDGROUND', 'CONCRETE', 'SNOW', 'OLDSNOW'.");
            string albedo_string = Console.ReadLine();
            double albedo1       = albedos[albedo_string];

            double[] albedo = new double[8760];
            for (int t = 0; t < 8760; t++)
            {
                albedo[t] = albedo1;
            }

            double beta_in, psi_in;

            Console.WriteLine("Tilt angle in degree: ");
            if (!double.TryParse(Console.ReadLine(), out beta_in))
            {
                Console.WriteLine("You need to input a real number. Hit any key to close.");
                Console.ReadLine();
                return;
            }
            Console.WriteLine("Azimuth angle in degree (North is 0, South is 180): ");
            if (!double.TryParse(Console.ReadLine(), out psi_in))
            {
                Console.WriteLine("You need to input a real number. Hit any key to close.");
                Console.ReadLine();
                return;
            }
            Console.WriteLine();

            //double []beta = new double[1]{20};
            //double [] psi=new double[1]{180};
            double[] beta = new double[1] {
                beta_in
            };
            double [] psi = new double[1] {
                psi_in
            };
            Sensorpoints.p3d [] coord = new Sensorpoints.p3d[1];    //dummy variables. will not be used in this simplified simulation
            coord[0].X = 0;
            coord[0].Y = 0;
            coord[0].Z = 0;
            Sensorpoints.v3d[] normal = new Sensorpoints.v3d[1];   //dummy variables. will not be used in this simplified simulation
            normal[0].X = 0;
            normal[0].Y = 1;
            normal[0].Z = 0;

            Console.WriteLine("Calculating irradiation...");
            Sensorpoints p = new Sensorpoints(beta, psi, coord, normal, recursion);

            p.SetSimpleSkyMT(beta, paropts);
            p.SetSimpleGroundReflectionMT(beta, albedo, weather, sunvectors.ToArray(), paropts);
            p.CalcIrradiationMT(weather, sunvectors.ToArray(), paropts);

            Console.WriteLine("Writing to path...");
            System.IO.StreamWriter write  = new System.IO.StreamWriter(path + "\\calc.txt");
            System.IO.StreamWriter write2 = new System.IO.StreamWriter(path + "\\calcbeam.txt");
            System.IO.StreamWriter write3 = new System.IO.StreamWriter(path + "\\calcdiff.txt");
            System.IO.StreamWriter write4 = new System.IO.StreamWriter(path + "\\calcgroundrefl.txt");
            for (int i = 0; i < p.I[0].Count(); i++)
            {
                //Console.WriteLine(p.I[0][i]);
                write.WriteLine(p.I[0][i]);
                write2.WriteLine(p.Ibeam[0][i]);
                write3.WriteLine(p.Idiff[0][i]);
                write4.WriteLine(p.Irefl_diff[0][i]);
            }
            write.Close();
            write2.Close();
            write3.Close();
            write4.Close();
            Console.WriteLine();
            Console.WriteLine("Done. Press any key to quit");
            Console.ReadKey();
        }
Ejemplo n.º 47
0
        /// <summary>
        /// 保存排序规则
        /// </summary>
        /// <param name="strpath"></param>文件绝对路径
        /// <param name="className"></param>根节点
        /// <param name="node"></param>打印类型的节点
        /// <param name="sortName"></param>排序的列名
        /// <param name="sortOrder"></param>排序(升降)
        public void SaveNode(string strpath, string className, string node, string sortName, string sortOrder)
        {
            XmlDocument xd = new XmlDocument();//创建文

            if (System.IO.File.Exists(strpath))
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(strpath);
                string strXml             = sr.ReadToEnd().Trim();
                sr.Close();
                if (strXml.Length > 0)
                {
                    xd.Load(strpath);//加载文档
                    XmlNode xmlNode = xd.SelectSingleNode("//" + node);
                    if (xmlNode != null)
                    {
                        xmlNode.InnerText = sortName.Trim();

                        XmlElement xmlele = (XmlElement)xmlNode;
                        xmlele.SetAttribute("sortOrder", sortOrder);
                    }
                    else
                    {
                        XmlNode root1 = xd.DocumentElement;
                        System.Xml.XmlElement ele2 = xd.CreateElement(node);
                        ele2.InnerText = sortName.Trim();
                        ele2.SetAttribute("sortOrder", sortOrder);
                        root1.AppendChild(ele2);
                    }
                }
                else
                {
                    System.Xml.XmlDeclaration dec = xd.CreateXmlDeclaration("1.0", "utf-8", null);
                    xd.AppendChild(dec);
                    System.Xml.XmlElement ele = xd.CreateElement(className);
                    ele.SetAttribute("Version", "1");
                    xd.AppendChild(ele);

                    System.Xml.XmlElement ele2 = xd.CreateElement(node);
                    ele2.InnerText = sortName.Trim();
                    ele2.SetAttribute("sortOrder", sortOrder);

                    ele.AppendChild(ele2);
                }
            }
            else
            {
                System.Xml.XmlDeclaration dec = xd.CreateXmlDeclaration("1.0", "utf-8", null);
                xd.AppendChild(dec);
                System.Xml.XmlElement ele = xd.CreateElement(className);
                ele.SetAttribute("Version", "1");
                xd.AppendChild(ele);

                System.Xml.XmlElement ele2 = xd.CreateElement(node);
                ele2.InnerText = sortName.Trim();
                ele2.SetAttribute("sortOrder", sortOrder);

                ele.AppendChild(ele2);
            }

            string filename = strpath;
            string hh       = (xd.InnerXml.ToString());

            System.IO.FileStream   myFs = new System.IO.FileStream(filename, System.IO.FileMode.Create);
            System.IO.StreamWriter mySw = new System.IO.StreamWriter(myFs);
            mySw.Write(hh);
            mySw.Close();
            myFs.Close();
        }
        private bool loadImportedDataPM(string fileName)
        {
            bool   result     = false;
            string sqlCommand = "";
            string pmInvoice  = "";
            //bool checkForRO = true;
            //int lastPos = 0;
            //int prevPos = 0;
            //int firstPos = 0;
            string         roInvoice        = "";
            string         tempString       = "";
            int            importedBranchID = 0;
            int            storedBranchID   = 0;
            MySqlException internalEX       = null;

            DS.beginTransaction();

            try
            {
                DS.mySqlConnect();

                System.IO.StreamReader file = new System.IO.StreamReader(fileName);

                pmInvoice  = file.ReadLine();
                roInvoice  = file.ReadLine();
                tempString = file.ReadLine();;
                if (int.TryParse(tempString, out importedBranchID))
                {
                    storedBranchID = getBranchID();
                    if (storedBranchID != importedBranchID)
                    {
                        file.Close();
                        throw new Exception("INFORMASI BRANCH ID TIDAK SESUAI");
                    }
                }
                else
                {
                    //MessageBox.Show("INFORMASI BRANCH ID TIDAK DITEMUKAN");

                    file.Close();
                    throw new Exception("INFORMASI BRANCH ID TIDAK DITEMUKAN");
                }

                if (!noPMExist(pmInvoice))
                {
                    while ((sqlCommand = file.ReadLine()) != null)
                    {
                        //if (checkForRO)
                        //{
                        //    tempString = sqlCommand;
                        //    // GET RO_INVOICE
                        //    if (sqlCommand.LastIndexOf("RO_INVOICE") > 0)
                        //    {
                        //        lastPos = sqlCommand.LastIndexOf("',");
                        //        prevPos = sqlCommand.LastIndexOf(", '", lastPos - 1);
                        //        roInvoice = sqlCommand.Substring(prevPos+3, lastPos - prevPos-3);
                        //    }

                        //    // GET BRANCH_ID
                        //    if (sqlCommand.IndexOf("BRANCH_ID_TO") > 0)
                        //    {
                        //        firstPos = tempString.IndexOf("('");
                        //        tempString = tempString.Substring(firstPos);

                        //        firstPos = tempString.IndexOf(",");
                        //        tempString = tempString.Substring(firstPos+1);

                        //        firstPos = tempString.IndexOf(",");
                        //        tempString = tempString.Substring(firstPos + 1);

                        //        firstPos = tempString.IndexOf(",");
                        //        tempString = tempString.Substring(1, firstPos-1);

                        //        if (int.TryParse(tempString, out importedBranchID))
                        //        {
                        //            storedBranchID = getBranchID();

                        //            if (storedBranchID != importedBranchID)
                        //            {
                        //                //MessageBox.Show("INFORMASI BRANCH ID TIDAK SESUAI");

                        //                file.Close();
                        //                throw new Exception("INFORMASI BRANCH ID TIDAK SESUAI");
                        //            }
                        //        }
                        //        else
                        //        {
                        //            //MessageBox.Show("INFORMASI BRANCH ID TIDAK DITEMUKAN");

                        //            file.Close();
                        //            throw new Exception("INFORMASI BRANCH ID TIDAK DITEMUKAN");
                        //        }
                        //    }

                        //}
                        //checkForRO = false;
                        if (!DS.executeNonQueryCommand(sqlCommand, ref internalEX))
                        {
                            throw internalEX;
                        }
                    }

                    file.Close();

                    if (roInvoice.Length > 0)
                    {
                        sqlCommand = "UPDATE REQUEST_ORDER_HEADER SET RO_ACTIVE = 0 WHERE RO_INVOICE = '" + roInvoice + "'";
                        if (!DS.executeNonQueryCommand(sqlCommand, ref internalEX))
                        {
                            throw internalEX;
                        }
                    }

                    DS.commit();

                    result = true;
                }
                else
                {
                    file.Close();
                    throw new Exception("NOMOR MUTASI SUDAH ADA");
                }
            }
            catch (Exception e)
            {
                result = false;
                try
                {
                    //myTrans.Rollback();
                }
                catch (MySqlException ex)
                {
                    if (DS.getMyTransConnection() != null)
                    {
                        MessageBox.Show("An exception of type " + ex.GetType() +
                                        " was encountered while attempting to roll back the transaction.");
                    }
                }

                MessageBox.Show(e.Message);
            }
            finally
            {
                DS.mySqlClose();
            }

            return(result);
        }
Ejemplo n.º 49
0
        protected virtual void OnGenerateButtonClicked(object sender, System.EventArgs e)
        {
            llum.Core core = llum.Core.getCore();
            //System.Collections.Generic.Dictionary<string,string>dic=new System.Collections.Generic.Dictionary<string, string>();

            System.Collections.Generic.List <CookComputing.XmlRpc.XmlRpcStruct> list = new System.Collections.Generic.List <CookComputing.XmlRpc.XmlRpcStruct>();

            if (studentsRadiobutton.Active)
            {
                list        = core.xmlrpc.get_students_passwords();
                search_mode = 0;
            }
            if (teachersRadiobutton.Active)
            {
                list = core.xmlrpc.get_teachers_passwords();
                //groupsCombobox.Active=0;
                search_mode = 1;
            }
            if (allRadiobutton.Active)
            {
                list = core.xmlrpc.get_all_passwords();
                //groupsCombobox.Active=0;
                search_mode = 2;
            }

            /*
             * foreach(string str in dic.Keys)
             * {
             *      if(!dic[str].Contains("{SSHA}"))
             *              Console.WriteLine(str + ":" + dic[str]);
             *
             * }
             */

            string close_html = "</div>\n" +
                                "</body>\n" +
                                "</html>\n";

            System.IO.StreamReader stream = new System.IO.StreamReader(core.html_skel);
            string final_html             = stream.ReadToEnd();

            stream.Close();

            final_html = final_html.Replace("%%NAME%%", Mono.Unix.Catalog.GetString("Name"));
            final_html = final_html.Replace("%%USER%%", Mono.Unix.Catalog.GetString("User"));
            final_html = final_html.Replace("%%PASSWORD%%", Mono.Unix.Catalog.GetString("Password"));
            final_html = final_html.Replace("%%PRINT%%", Mono.Unix.Catalog.GetString("Print"));


            bool impar = false;



            foreach (CookComputing.XmlRpc.XmlRpcStruct dic in list)
            {
                bool ok = false;
                if (user_list != null)
                {
                    if (search_mode == 0)
                    {
                        foreach (LdapUser user in user_list)
                        {
                            if ((string)dic ["uid"] == user.uid)
                            {
                                if (groupsCombobox.Active == 0)
                                {
                                    ok = true;
                                    break;
                                }
                                else
                                {
                                    ok = user.groups.Contains(groupsCombobox.ActiveText);
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        ok = true;
                    }
                }

                else
                {
                    ok = true;
                }

                if (ok)
                {
                    if (!impar)
                    {
                        final_html += "\n<div class='row'><div class='left'>\n";
                        final_html += dic["sn"] + ", " + dic["cn"];
                        final_html += "\n</div><div class='middle'>\n";
                        final_html += dic["uid"];
                        final_html += "\n</div><div class='right'>\n";
                        final_html += dic["passwd"];
                        final_html += "\n</div></div>\n";


                        impar = true;
                    }
                    else
                    {
                        final_html += "\n<div class='row impar'><div class='left'>\n";
                        final_html += dic["sn"] + ", " + dic["cn"];
                        final_html += "\n</div><div class='middle'>\n";
                        final_html += dic["uid"];
                        final_html += "\n</div><div class='right'>\n";
                        final_html += dic["passwd"];
                        final_html += "\n</div></div>\n";
                        impar       = false;
                    }
                }
            }

            final_html += close_html;

            string file_name = "/tmp/." + RandomString(10) + ".html";

            while (System.IO.File.Exists(file_name))
            {
                file_name = "/tmp/." + RandomString(10) + ".html";
            }

            System.IO.StreamWriter sw = new System.IO.StreamWriter(file_name);
            sw.Write(final_html);
            sw.Close();



            Mono.Unix.Native.Syscall.chmod(file_name, Mono.Unix.Native.FilePermissions.S_IRWXU);

            System.Threading.ThreadStart start = delegate {
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.UseShellExecute        = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError  = true;
                p.StartInfo.FileName  = "/usr/share/llum/llum-browser";
                p.StartInfo.Arguments = file_name;
                p.Start();
            };

            System.Threading.Thread thread = new System.Threading.Thread(start);

            thread.Start();
        }
Ejemplo n.º 50
0
        public static Item LoadItem(int itemNum)
        {
            Item item = new Item();

            string[] parse = null;
            using (System.IO.StreamReader read = new System.IO.StreamReader(IO.Paths.ItemsFolder + "item" + itemNum + ".dat"))
            {
                while (!(read.EndOfStream))
                {
                    parse = read.ReadLine().Split('|');
                    switch (parse[0].ToLower())
                    {
                    case "itemdata":
                        if (parse[1].ToLower() != "v2")
                        {
                            read.Close();
                            return(null);
                        }
                        break;

                    case "data":
                        item.Name  = parse[1].Trim();
                        item.Desc  = parse[2];
                        item.Pic   = parse[3].ToInt();
                        item.Type  = (Enums.ItemType)parse[4].ToInt();
                        item.Data1 = parse[5].ToInt();
                        item.Data2 = parse[6].ToInt();
                        item.Data3 = parse[7].ToInt();


                        item.Price     = parse[8].ToInt();
                        item.Stackable = parse[9].ToBool();
                        item.Bound     = parse[10].ToBool();
                        item.Loseable  = parse[11].ToBool();
                        item.Rarity    = parse[12].ToInt();
                        break;

                    case "reqs":
                    {
                        item.AttackReq   = parse[1].ToInt();
                        item.DefenseReq  = parse[2].ToInt();
                        item.SpAtkReq    = parse[3].ToInt();
                        item.SpDefReq    = parse[4].ToInt();
                        item.SpeedReq    = parse[5].ToInt();
                        item.ScriptedReq = parse[6].ToInt();
                    }
                    break;

                    case "stats":
                    {
                        item.AddHP       = parse[1].ToInt();
                        item.AddPP       = parse[2].ToInt();
                        item.AddAttack   = parse[3].ToInt();
                        item.AddDefense  = parse[4].ToInt();
                        item.AddSpAtk    = parse[5].ToInt();
                        item.AddSpDef    = parse[6].ToInt();
                        item.AddSpeed    = parse[7].ToInt();
                        item.AddEXP      = parse[8].ToInt();
                        item.AttackSpeed = parse[9].ToInt();

                        item.RecruitBonus = parse[10].ToInt();
                    }
                    break;
                    }
                }
            }
            return(item);
        }
Ejemplo n.º 51
0
        static void Main(string[] args)
        {
            Outlook.Application app       = new Microsoft.Office.Interop.Outlook.Application();
            Outlook._NameSpace  nameSpace = app.GetNamespace("MAPI");
            nameSpace.Logon(null, null, false, false);
            Outlook.Folder folder = (Outlook.Folder)app.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts);

            Outlook.MailItem msg;

            //Making an Excel file
            Excel.Application xlApp;
            Excel.Workbook    xlWorkBook;
            Excel.Worksheet   xlWorkSheet;
            object            misValue = System.Reflection.Missing.Value;

            xlApp       = new Microsoft.Office.Interop.Excel.Application();
            xlWorkBook  = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            //Passing the files with address of msg file to StreamReader
            System.IO.StreamReader file = new System.IO.StreamReader(@"list_of_msg_files.txt");

            const string PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";

            int    count = 1; //In excel count starts from 1
            string filePath, smtpAddress = "";

            //reading name of each msg file from
            while ((filePath = file.ReadLine()) != null)
            {
                try
                {
                    check++;
                    msg = (Outlook.MailItem)app.Session.OpenSharedItem(filePath);
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(filePath);
                    if (check > 11093)
                    {
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }


                try
                {
                    //Fiding Sender Information
                    Outlook._MailItem temp = ((Outlook._MailItem)msg).Reply();

                    Outlook.Recipient        sender = temp.Recipients[1];
                    Outlook.PropertyAccessor xx     = sender.PropertyAccessor;


                    try //For some companies, when an employee leaves, the local email address is deleted
                    {
                        smtpAddress = xx.GetProperty(PR_SMTP_ADDRESS).ToString();
                    }
                    catch (Exception ex)
                    {
                        smtpAddress = "NAN";
                    }

                    temp.Delete();

                    xlWorkSheet.Cells[count, 1] = (sender.Name == null) ? "" : sender.Name;
                }
                catch (Exception e) //ignore!!
                {
                    xlWorkSheet.Cells[count, 1] = (msg.SenderName == null) ? "" : msg.SenderName;
                }


                xlWorkSheet.Cells[count, 2] = (smtpAddress == null) ? "" : smtpAddress;

                //subject
                xlWorkSheet.Cells[count, 3] = (msg.Subject == null) ? "" : msg.Subject;

                //Recipients
                smtpAddress = "";
                string             names  = "";
                Outlook.Recipients recips = msg.Recipients;

                foreach (Outlook.Recipient recip in recips)
                {
                    Outlook.PropertyAccessor pa = recip.PropertyAccessor;

                    string tmp;
                    try // if email address is not there
                    {
                        tmp = pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                    }
                    catch (Exception ex)
                    {
                        tmp = recip.Name;
                    }

                    smtpAddress = smtpAddress + "," + tmp;
                    names       = names + "," + recip.Name;
                }


                xlWorkSheet.Cells[count, 4] = (smtpAddress == null) ? "" : smtpAddress;
                xlWorkSheet.Cells[count, 5] = (names == null) ? "" : names;

                //In case you need CreationTime
                //xlWorkSheet.Cells[count, 6] = (msg.CreationTime == null) ? "" : msg.CreationTime.ToShortDateString();
                //xlWorkSheet.Cells[count, 7] = (msg.ReceivedTime == null) ? "" : msg.ReceivedTime.ToShortDateString();

                xlWorkSheet.Cells[count, 6] = (msg.SentOn == null) ? "" : msg.SentOn.Day + "-" + msg.SentOn.Month + "-" + msg.SentOn.Year;
                xlWorkSheet.Cells[count, 7] = (msg.Body == null) ? "" : msg.Body;
                xlWorkSheet.Cells[count, 8] = filePath;


                string attached = "";
                for (int i = 0; i < msg.Attachments.Count; i++)
                {
                    attached += "," + msg.Attachments[i + 1].FileName;
                }


                xlWorkSheet.Cells[count, 9] = attached;

                count++;
            }


            file.Close();

            xlWorkBook.SaveAs("Emails.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            System.Console.ReadLine();
        }
Ejemplo n.º 52
0
        public void AnalyzeFile(string filename)
        {
            System.IO.StreamReader sr = null;
            try
            {
                for (int i = 0; i < 30; i++)
                {
                    try
                    {
                        sr = new System.IO.StreamReader(filename, Encoding.Default);
                        break;
                    }
                    catch (Exception ee)
                    {
                        System.Diagnostics.Debug.WriteLine(ee.Message);
                    }
                }
                if (sr == null)
                {
                    throw new ApplicationException("Could not open input file, copy error?");
                }
                string header = sr.ReadLine();

                string[] fields = header.Split(SplitChars);

                /*Detect OE format*/
                int fldID, fldSI, fldFName, fldEName, fldClub, fldClass, fldStart, fldTime, fldStatus, fldFirstPost, fldText1, fldText2, fldText3, fldFinish, fldLeg;
                int fldTotalTime;
                OxTools.DetectOxCSVFormat(OxTools.SourceProgram.OE, fields, out fldID, out fldSI, out fldFName, out fldEName, out fldClub, out fldClass, out fldStart, out fldTime, out fldStatus, out fldFirstPost, out fldLeg, out fldFinish, out fldText1, out fldText2, out fldText3, out fldTotalTime);

                if (fldID == -1 || fldSI == -1 || fldFName == -1 || fldEName == -1 || fldClub == -1 || fldClass == -1 ||
                    fldStart == -1 || fldTime == -1 ||
                    fldStart == -1 || fldFirstPost == -1)
                {
                    throw new System.IO.IOException("Not OE-formatted file!");
                }


                if (fldID == -1 || fldSI == -1 || fldFName == -1 || fldEName == -1 || fldClub == -1 || fldClass == -1 ||
                    fldStart == -1 || fldTime == -1)
                {
                    throw new System.IO.IOException("Not OE-formatted file!");
                }

                string tmp;
                while ((tmp = sr.ReadLine()) != null)
                {
                    string[] parts = tmp.Split(SplitChars);

                    /* check so that the line is not incomplete*/
                    int    id    = Convert.ToInt32(parts[fldID]);
                    string name  = parts[fldFName].Trim('\"') + " " + parts[fldEName].Trim('\"');
                    string club  = parts[fldClub].Trim('\"');
                    string Class = parts[fldClass].Trim('\"');
                    int    start = strTimeToInt(parts[fldStart]);
                    int    time  = strTimeToInt(parts[fldTime]);


                    int status = 0;
                    try
                    {
                        status = Convert.ToInt32(parts[fldStatus]);
                    }
                    catch
                    {
                    }

                    var splittimes = new List <ResultStruct>();
                    /*parse splittimes*/
                    var codes = new List <int>();
                    if (fldFirstPost >= 0)
                    {
                        for (int i = fldFirstPost; i < parts.Length - 4; i++)
                        {
                            if (parts[i + 1].Length == 0 ||
                                parts[i + 2].Length == 0)
                            {
                                i += 3;
                                continue;
                            }
                            var s = new ResultStruct();
                            try
                            {
                                //s.ControlNo = Convert.ToInt32(parts[i]);
                                i++;
                                s.ControlCode = Convert.ToInt32(parts[i]);

                                if (s.ControlCode == 999)
                                {
                                    i++;
                                    if (time == -1 && status == 0)
                                    {
                                        time = strTimeToInt(parts[i]);
                                    }

                                    i++;
                                }
                                else
                                {
                                    s.ControlCode += 1000;
                                    while (codes.Contains(s.ControlCode))
                                    {
                                        s.ControlCode += 1000;
                                    }
                                    codes.Add(s.ControlCode);

                                    i++;
                                    s.Time = strTimeToInt(parts[i]);
                                    i++;

                                    if (s.Time > 0)
                                    {
                                        s.Place = 0;
                                        try
                                        {
                                            s.Place = Convert.ToInt32(parts[i]);
                                        }
                                        catch
                                        { }

                                        splittimes.Add(s);
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                    FireOnResult(new Result {
                        ID         = id,
                        RunnerName = name,
                        RunnerClub = club,
                        Class      = Class,
                        StartTime  = start,
                        Time       = time,
                        Status     = status,
                        SplitTimes = splittimes
                    });
                }
            }
            catch (Exception ee)
            {
                FireLogMsg("ERROR in OEPArser: " + ee.Message);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
Ejemplo n.º 53
0
        public static RDungeon LoadRDungeon(int dungeonNum)
        {
            RDungeon dungeon  = new RDungeon(dungeonNum);
            string   FilePath = IO.Paths.RDungeonsFolder + "rdungeon" + dungeonNum.ToString() + ".dat";

            using (System.IO.StreamReader reader = new System.IO.StreamReader(FilePath)) {
                while (!(reader.EndOfStream))
                {
                    string[] parse = reader.ReadLine().Split('|');
                    switch (parse[0].ToLower())
                    {
                    case "rdungeondata":
                        if (parse[1].ToLower() != "v1")
                        {
                            reader.Close();
                            reader.Dispose();
                            return(null);
                        }
                        break;

                    case "data":
                        dungeon.DungeonName = parse[1];
                        dungeon.Direction   = (Enums.Direction)parse[2].ToInt();
                        dungeon.MaxFloors   = parse[3].ToInt();
                        dungeon.Recruitment = parse[4].ToBool();
                        dungeon.Exp         = parse[5].ToBool();
                        break;

                    case "terrain": {
                        #region Terrain
                        dungeon.StairsX     = parse[1].ToInt();
                        dungeon.StairsSheet = parse[2].ToInt();

                        dungeon.mGroundX     = parse[3].ToInt();
                        dungeon.mGroundSheet = parse[4].ToInt();

                        dungeon.mTopLeftX       = parse[5].ToInt();
                        dungeon.mTopLeftSheet   = parse[6].ToInt();
                        dungeon.mTopCenterX     = parse[7].ToInt();
                        dungeon.mTopCenterSheet = parse[8].ToInt();
                        dungeon.mTopRightX      = parse[9].ToInt();
                        dungeon.mTopRightSheet  = parse[10].ToInt();

                        dungeon.mCenterLeftX       = parse[11].ToInt();
                        dungeon.mCenterLeftSheet   = parse[12].ToInt();
                        dungeon.mCenterCenterX     = parse[13].ToInt();
                        dungeon.mCenterCenterSheet = parse[14].ToInt();
                        dungeon.mCenterRightX      = parse[15].ToInt();
                        dungeon.mCenterRightSheet  = parse[16].ToInt();

                        dungeon.mBottomLeftX       = parse[17].ToInt();
                        dungeon.mBottomLeftSheet   = parse[18].ToInt();
                        dungeon.mBottomCenterX     = parse[19].ToInt();
                        dungeon.mBottomCenterSheet = parse[20].ToInt();
                        dungeon.mBottomRightX      = parse[21].ToInt();
                        dungeon.mBottomRightSheet  = parse[22].ToInt();

                        dungeon.mInnerTopLeftX        = parse[23].ToInt();
                        dungeon.mInnerTopLeftSheet    = parse[24].ToInt();
                        dungeon.mInnerBottomLeftX     = parse[25].ToInt();
                        dungeon.mInnerBottomLeftSheet = parse[26].ToInt();

                        dungeon.mInnerTopRightX        = parse[27].ToInt();
                        dungeon.mInnerTopRightSheet    = parse[28].ToInt();
                        dungeon.mInnerBottomRightX     = parse[29].ToInt();
                        dungeon.mInnerBottomRightSheet = parse[30].ToInt();

                        if (parse.Length > 32)
                        {
                            dungeon.mWaterX            = parse[31].ToInt();
                            dungeon.mWaterSheet        = parse[32].ToInt();
                            dungeon.mWaterAnimX        = parse[33].ToInt();
                            dungeon.mWaterAnimSheet    = parse[34].ToInt();
                            dungeon.mIsolatedWallX     = parse[35].ToInt();
                            dungeon.mIsolatedWallSheet = parse[36].ToInt();

                            dungeon.mColumnTopX        = parse[37].ToInt();
                            dungeon.mColumnTopSheet    = parse[38].ToInt();
                            dungeon.mColumnCenterX     = parse[39].ToInt();
                            dungeon.mColumnCenterSheet = parse[40].ToInt();
                            dungeon.mColumnBottomX     = parse[41].ToInt();
                            dungeon.mColumnBottomSheet = parse[42].ToInt();

                            dungeon.mRowLeftX       = parse[43].ToInt();
                            dungeon.mRowLeftSheet   = parse[44].ToInt();
                            dungeon.mRowCenterX     = parse[45].ToInt();
                            dungeon.mRowCenterSheet = parse[46].ToInt();
                            if (parse.Length > 48)
                            {
                                dungeon.mRowRightX     = parse[47].ToInt();
                                dungeon.mRowRightSheet = parse[48].ToInt();
                                if (parse.Length > 50)
                                {
                                    dungeon.mShoreTopLeftX             = parse[49].ToInt();
                                    dungeon.mShoreTopLeftSheet         = parse[50].ToInt();
                                    dungeon.mShoreTopRightX            = parse[51].ToInt();
                                    dungeon.mShoreTopRightSheet        = parse[52].ToInt();
                                    dungeon.mShoreBottomRightX         = parse[53].ToInt();
                                    dungeon.mShoreBottomRightSheet     = parse[54].ToInt();
                                    dungeon.mShoreBottomLeftX          = parse[55].ToInt();
                                    dungeon.mShoreBottomLeftSheet      = parse[56].ToInt();
                                    dungeon.mShoreDiagonalForwardX     = parse[57].ToInt();
                                    dungeon.mShoreDiagonalForwardSheet = parse[58].ToInt();
                                    dungeon.mShoreDiagonalBackX        = parse[59].ToInt();
                                    dungeon.mShoreDiagonalBackSheet    = parse[60].ToInt();

                                    dungeon.mShoreTopX            = parse[61].ToInt();
                                    dungeon.mShoreTopSheet        = parse[62].ToInt();
                                    dungeon.mShoreRightX          = parse[63].ToInt();
                                    dungeon.mShoreRightSheet      = parse[64].ToInt();
                                    dungeon.mShoreBottomX         = parse[65].ToInt();
                                    dungeon.mShoreBottomSheet     = parse[66].ToInt();
                                    dungeon.mShoreLeftX           = parse[67].ToInt();
                                    dungeon.mShoreLeftSheet       = parse[68].ToInt();
                                    dungeon.mShoreVerticalX       = parse[69].ToInt();
                                    dungeon.mShoreVerticalSheet   = parse[70].ToInt();
                                    dungeon.mShoreHorizontalX     = parse[71].ToInt();
                                    dungeon.mShoreHorizontalSheet = parse[72].ToInt();

                                    dungeon.mShoreInnerTopLeftX         = parse[73].ToInt();
                                    dungeon.mShoreInnerTopLeftSheet     = parse[74].ToInt();
                                    dungeon.mShoreInnerTopRightX        = parse[75].ToInt();
                                    dungeon.mShoreInnerTopRightSheet    = parse[76].ToInt();
                                    dungeon.mShoreInnerBottomRightX     = parse[77].ToInt();
                                    dungeon.mShoreInnerBottomRightSheet = parse[78].ToInt();
                                    dungeon.mShoreInnerBottomLeftX      = parse[79].ToInt();
                                    dungeon.mShoreInnerBottomLeftSheet  = parse[80].ToInt();

                                    dungeon.mShoreInnerTopX        = parse[81].ToInt();
                                    dungeon.mShoreInnerTopSheet    = parse[82].ToInt();
                                    dungeon.mShoreInnerRightX      = parse[83].ToInt();
                                    dungeon.mShoreInnerRightSheet  = parse[84].ToInt();
                                    dungeon.mShoreInnerBottomX     = parse[85].ToInt();
                                    dungeon.mShoreInnerBottomSheet = parse[86].ToInt();
                                    dungeon.mShoreInnerLeftX       = parse[87].ToInt();
                                    dungeon.mShoreInnerLeftSheet   = parse[88].ToInt();

                                    dungeon.mShoreSurroundedX     = parse[89].ToInt();
                                    dungeon.mShoreSurroundedSheet = parse[90].ToInt();
                                }
                            }
                        }
                        #endregion
                    }
                    break;

                    case "floor": {
                        RDungeonFloor floor = new RDungeonFloor();
                        floor.WeatherIntensity = parse[1].ToInt();
                        floor.Weather          = (Enums.Weather)parse[2].ToInt();
                        floor.Music            = parse[3];
                        floor.GoalType         = (Enums.RFloorGoalType)parse[4].ToInt();
                        floor.GoalMap          = parse[5].ToInt();
                        floor.GoalX            = parse[6].ToInt();
                        floor.GoalY            = parse[7].ToInt();
                        floor.ItemSpawnRate    = parse[8].ToInt();
                        int maxTraps = parse[9].ToInt();

                        int n = 10;
                        for (int i = 0; i < 15; i++)
                        {
                            floor.Npc[i] = parse[n].ToInt();
                            n++;
                        }
                        for (int i = 0; i < 8; i++)
                        {
                            floor.Items[i] = parse[n].ToInt();
                            n++;
                        }
                        for (int i = 0; i < maxTraps; i++)
                        {
                            floor.Traps.Add(parse[n].ToInt());
                            n++;
                        }
                        dungeon.Floors.Add(floor);
                    }
                    break;

                    case "cratersettings": {
                        dungeon.Options.Craters         = parse[1].ToInt();
                        dungeon.Options.CraterMinLength = parse[2].ToInt();
                        dungeon.Options.CraterMaxLength = parse[3].ToInt();
                        dungeon.Options.CraterFuzzy     = parse[4].ToBool();
                    }
                    break;
                    }
                }
            }
            return(dungeon);
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Parsing DXF File
        /// </summary>
        /// <param name="dxfFileLocation">Dxf File Location</param>
        /// <param name="dxfData">Replicating data to simplify Stressing</param>
        /// <param name="dxfData12_9">Splitting data for better sorting 12,9</param>
        /// <param name="dxfData15_7">Splitting data for better sorting 15.7</param>
        /// <param name="dxfTendonRef"></param>
        public void ParseDXFFile(string dxfFileLocation, ref string projectNumber, ref List <DXFData> dxfData,
                                 ref List <DXFData> dxfData12_9, ref List <DXFData> dxfData15_7
                                 , ref List <DXFTendonRef> dxfTendonRef)
        {
            dxfData.Clear();

            dxfData12_9.Clear();
            dxfData15_7.Clear();

            dxfTendonRef.Clear();

            localDxfTendonRef.Clear();

            //int counter = 0;
            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(dxfFileLocation);

            DXFData row  = new DXFData();
            bool    falg = false;

            while ((line = file.ReadLine()) != null)
            {
                // Select that this is the the ACDbText Type Input
                if (line != "AcDbText")
                {
                    continue;
                }

                // Skip Settings to reach value
                for (int i = 0; i < 9; i++)
                {
                    file.ReadLine();
                }

                //line = file.ReadLine();
                //if(line.StartsWith("B-"))
                //{
                //    Console.WriteLine(line);
                //}

                // Save Value
                valueExtracted = file.ReadLine();
                if (valueExtracted.StartsWith("B-"))
                {
                    string[] projectValues = valueExtracted.Split('-');
                    projectNumber = "B961-" + projectValues[1];
                }
                if (valueExtracted.Contains("TYPE "))
                {
                    for (int i = 0; i < 80; i++)
                    {
                        line = file.ReadLine();
                        if (line == "TEXT")
                        {
                            break;
                        }
                    }

                    for (int i = 0; i < 19; i++)
                    {
                        file.ReadLine();
                    }

                    line = file.ReadLine();


                    if (!falg)
                    {
                        falg = true;
                    }
                    else
                    {
                        //if (int.TryParse(, out tempTendonRef))
                        //{
                        DXFTendonRef dxfTendonRefLocal = new DXFTendonRef();
                        dxfTendonRefLocal.tendonType   = valueExtracted.Remove(0, 5);
                        dxfTendonRefLocal.tendonNumber = line;
                        localDxfTendonRef.Add(dxfTendonRefLocal);


                        //
                    }

                    continue;
                }


                // Skip Settings to reach Type of input
                for (int i = 0; i < 17; i++)
                {
                    file.ReadLine();
                }

                // Save Input Type
                line = file.ReadLine();

                try
                {
                    // This switch is just to save that this value
                    // is known and it's linked to these selected types
                    switch (line)
                    {
                    case "TYPE_NO":
                        row.TYPE_NO = valueExtracted;

                        dxfData.Add(row);

                        if (row.STRAND_TYPE.Contains("12.9"))
                        {
                            dxfData12_9.Add(row);
                        }
                        else
                        {
                            dxfData15_7.Add(row);
                        }

                        row = new DXFData();
                        break;

                    case "NO_OF_TYPES":
                        row.NO_OF_TYPES = int.Parse(valueExtracted);
                        break;

                    case "ANCHOR_TYPE":
                        row.ANCHOR_TYPE = valueExtracted;
                        break;

                    case "NO_OF_LIVES":
                        row.NO_OF_LIVES = int.Parse(valueExtracted);
                        break;

                    case "NO_OF_STRANDS":
                        row.NO_OF_STRANDS = int.Parse(valueExtracted);
                        break;

                    case "STRAND_TYPE":
                        row.STRAND_TYPE = valueExtracted;
                        break;

                    case "GUTS":
                        row.GUTS = int.Parse(valueExtracted);
                        break;

                    case "LENGTH":
                        row.LENGTH = double.Parse(valueExtracted);
                        break;

                    case "JACK_FORCE":
                        row.JACK_FORCE = valueExtracted;
                        break;

                    case "EXTENSION":
                        row.EXTENSION = int.Parse(valueExtracted);
                        break;

                    case "STRESSING":
                        row.STRESSING = valueExtracted;

                        break;
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceInformation("Error Input:" + ex.Message);
                    continue;
                }
            }

            file.Close();

            for (int i = 0; i < dxfData.Count; i++)
            {
                for (int j = 0; j < localDxfTendonRef.Count; j++)
                {
                    if (localDxfTendonRef[j].tendonType == dxfData[i].TYPE_NO)
                    {
                        dxfTendonRef.Add(localDxfTendonRef[j]);
                    }
                }
            }

            //// 1a Problemmmmmmmm
            //dxfTendonRef.Sort(delegate(DXFTendonRef a, DXFTendonRef b)
            //{
            //    int xdiff = a.tendonType.CompareTo(b.tendonType);
            //    if (xdiff != 0) return xdiff;
            //    else return a.tendonNumber.CompareTo(b.tendonNumber);
            //});
        }
Ejemplo n.º 55
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        async Task FromDataPartner(RequestDataMart reqDM)
        {
            //close the current task
            var currentTask = await PmnTask.GetActiveTaskForRequestActivityAsync(reqDM.Request.ID, reqDM.Request.WorkFlowActivityID.Value, DB);

            CompleteTask(currentTask);

            //open new task and set the request to the new activity
            var task = DB.Actions.Add(PmnTask.CreateForWorkflowActivity(reqDM.Request.ID, ConductAnalysisActivityID, WorkflowID, DB));

            reqDM.Request.WorkFlowActivityID = ConductAnalysisActivityID;

            //create new routing
            var analysisCenterRouting = await DB.RequestDataMarts.Include(rdm => rdm.Responses).Where(rdm => rdm.RequestID == reqDM.Request.ID && rdm.RoutingType == RoutingType.AnalysisCenter).FirstOrDefaultAsync();

            Lpp.Dns.Data.Response analysisCenterResponse = null;
            if (analysisCenterRouting.Status == RoutingStatus.Draft && analysisCenterRouting.Responses.Count == 1 && analysisCenterRouting.Responses.Where(rsp => rsp.ResponseTime.HasValue == false).Any())
            {
                //if the initial status of the routing is draft, and there is only a single response assume this is the first time hitting the analysis center.
                //use the existing response to submit to the analysis center
                analysisCenterResponse = analysisCenterRouting.Responses.First();
            }
            else if (analysisCenterRouting.Status != RoutingStatus.Draft)
            {
                analysisCenterRouting.Status = RoutingStatus.Draft;
            }

            if (analysisCenterResponse == null)
            {
                analysisCenterResponse = analysisCenterRouting.AddResponse(IdentityID);
            }

            //use all the dp output documents to be the input documents for the AC routing
            //build a manifest for where the documents are coming from
            List <Lpp.Dns.DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem> manifestItems = new List <DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem>();
            var q = from rd in DB.RequestDocuments
                    join rsp in DB.Responses on rd.ResponseID equals rsp.ID
                    join rdm in DB.RequestDataMarts on rsp.RequestDataMartID equals rdm.ID
                    join dm in DB.DataMarts on rdm.DataMartID equals dm.ID
                    join doc in DB.Documents on rd.RevisionSetID equals doc.RevisionSetID
                    where rsp.Count == rsp.RequestDataMart.Responses.Max(r => r.Count) &&
                    rdm.RequestID == reqDM.Request.ID &&
                    rd.DocumentType == RequestDocumentType.Output &&
                    rdm.RoutingType == RoutingType.DataPartner &&
                    doc.ItemID == rsp.ID &&
                    doc.ID == DB.Documents.Where(dd => dd.RevisionSetID == doc.RevisionSetID && doc.ItemID == rsp.ID).OrderByDescending(dd => dd.MajorVersion).ThenByDescending(dd => dd.MinorVersion).ThenByDescending(dd => dd.BuildVersion).ThenByDescending(dd => dd.RevisionVersion).Select(dd => dd.ID).FirstOrDefault()
                    select new
            {
                DocumentID            = doc.ID,
                DocumentKind          = doc.Kind,
                DocumentFileName      = doc.FileName,
                ResponseID            = rd.ResponseID,
                RevisionSetID         = rd.RevisionSetID,
                RequestDataMartID     = rsp.RequestDataMartID,
                DataMartID            = rdm.DataMartID,
                DataPartnerIdentifier = dm.DataPartnerIdentifier,
                DataMart = dm.Name
            };

            var documents = await(q).ToArrayAsync();

            // further filtering based on if a output filelist document was included needs to be done. Only the files indicated should be passed on to the analysis center
            foreach (var dpDocuments in documents.GroupBy(k => k.RequestDataMartID))
            {
                var filelistDocument = dpDocuments.Where(d => !string.IsNullOrEmpty(d.DocumentKind) && string.Equals("DistributedRegression.FileList", d.DocumentKind, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (filelistDocument != null)
                {
                    //only include the files indicated in the filelist document
                    using (var ds = new Lpp.Dns.Data.Documents.DocumentStream(DB, filelistDocument.DocumentID))
                        using (var reader = new System.IO.StreamReader(ds))
                        {
                            //read the header line
                            reader.ReadLine();

                            string line, filename;
                            bool   includeInDistribution = false;
                            while (!reader.EndOfStream)
                            {
                                line = reader.ReadLine();
                                string[] split = line.Split(',');
                                if (split.Length > 0)
                                {
                                    filename = split[0].Trim();
                                    if (split.Length > 1)
                                    {
                                        includeInDistribution = string.Equals(split[1].Trim(), "1");
                                    }
                                    else
                                    {
                                        includeInDistribution = false;
                                    }

                                    if (includeInDistribution == false)
                                    {
                                        continue;
                                    }

                                    if (!string.IsNullOrEmpty(filename))
                                    {
                                        Guid?revisionSetID = dpDocuments.Where(d => string.Equals(d.DocumentFileName, filename, StringComparison.OrdinalIgnoreCase)).Select(d => d.RevisionSetID).FirstOrDefault();
                                        if (revisionSetID.HasValue)
                                        {
                                            DB.RequestDocuments.AddRange(dpDocuments.Where(d => d.RevisionSetID == revisionSetID.Value).Select(d => new RequestDocument {
                                                DocumentType = RequestDocumentType.Input, ResponseID = analysisCenterResponse.ID, RevisionSetID = d.RevisionSetID
                                            }).ToArray());
                                            manifestItems.AddRange(dpDocuments.Where(d => d.RevisionSetID == revisionSetID.Value).Select(d => new DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem
                                            {
                                                DocumentID            = d.DocumentID,
                                                DataMart              = d.DataMart,
                                                DataMartID            = d.DataMartID,
                                                DataPartnerIdentifier = d.DataPartnerIdentifier,
                                                RequestDataMartID     = d.RequestDataMartID,
                                                ResponseID            = d.ResponseID,
                                                RevisionSetID         = d.RevisionSetID
                                            }).ToArray());
                                        }
                                    }
                                }
                            }

                            reader.Close();
                        }
                }
                else
                {
                    var inputDocuments = dpDocuments.Where(d => d.DocumentKind != "DistributedRegression.AdapterEventLog" && d.DocumentKind != "DistributedRegression.TrackingTable");
                    if (inputDocuments.Count() > 0)
                    {
                        DB.RequestDocuments.AddRange(inputDocuments.Select(d => new RequestDocument {
                            DocumentType = RequestDocumentType.Input, ResponseID = analysisCenterResponse.ID, RevisionSetID = d.RevisionSetID
                        }).ToArray());
                        manifestItems.AddRange(inputDocuments.Select(d => new DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem
                        {
                            DocumentID            = d.DocumentID,
                            DataMart              = d.DataMart,
                            DataMartID            = d.DataMartID,
                            DataPartnerIdentifier = d.DataPartnerIdentifier,
                            RequestDataMartID     = d.RequestDataMartID,
                            ResponseID            = d.ResponseID,
                            RevisionSetID         = d.RevisionSetID
                        }).ToArray());
                    }
                }
            }

            //serialize the manifest of dataparter documents to the analysis center
            byte[] buffer;
            using (var ms = new System.IO.MemoryStream())
                using (var sw = new System.IO.StreamWriter(ms))
                    using (var jw = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                        serializer.Serialize(jw, manifestItems);
                        jw.Flush();

                        buffer = ms.ToArray();
                    }

            //create and add the manifest file
            Document analysisCenterManifest = DB.Documents.Add(new Document
            {
                Description  = "Contains information about the input documents and the datamart they came from.",
                Name         = "Internal: Analysis Center Manifest",
                FileName     = "manifest.json",
                ItemID       = task.ID,
                Kind         = DocumentKind.SystemGeneratedNoLog,
                UploadedByID = IdentityID,
                Viewable     = false,
                MimeType     = "application/json",
                Length       = buffer.Length
            });

            analysisCenterManifest.RevisionSetID = analysisCenterManifest.ID;

            //TODO:determine if there is a parent document to make the manifest a revision of. If there is update the revisionset id, and version numbers
            //chances are there should not be unless this is a resubmit for the same task

            var allTasks = await DB.ActionReferences.Where(tr => tr.ItemID == reqDM.Request.ID &&
                                                           tr.Type == DTO.Enums.TaskItemTypes.Request &&
                                                           tr.Task.Type == DTO.Enums.TaskTypes.Task
                                                           )
                           .Select(tr => tr.Task.ID).ToArrayAsync();

            var attachments = await(from doc in DB.Documents.AsNoTracking()
                                    join x in (
                                        DB.Documents.Where(dd => allTasks.Contains(dd.ItemID))
                                        .GroupBy(k => k.RevisionSetID)
                                        .Select(k => k.OrderByDescending(d => d.MajorVersion).ThenByDescending(d => d.MinorVersion).ThenByDescending(d => d.BuildVersion).ThenByDescending(d => d.RevisionVersion).Select(y => y.ID).Distinct().FirstOrDefault())
                                        ) on doc.ID equals x
                                    where allTasks.Contains(doc.ItemID) && doc.Kind == "Attachment.Input"
                                    orderby doc.ItemID descending, doc.RevisionSetID descending, doc.CreatedOn descending
                                    select doc).ToArrayAsync();

            DB.RequestDocuments.Add(new RequestDocument {
                DocumentType = RequestDocumentType.Input, ResponseID = analysisCenterResponse.ID, RevisionSetID = analysisCenterManifest.RevisionSetID.Value
            });

            foreach (var attachment in attachments)
            {
                DB.RequestDocuments.Add(new RequestDocument {
                    RevisionSetID = attachment.RevisionSetID.Value, ResponseID = analysisCenterResponse.ID, DocumentType = DTO.Enums.RequestDocumentType.AttachmentInput
                });
            }

            await DB.SaveChangesAsync();

            await DB.Entry(analysisCenterRouting).ReloadAsync();

            //post the manifest content
            analysisCenterManifest.SetData(DB, buffer);

            //submit the routing
            analysisCenterRouting.Status = analysisCenterResponse.Count > 1 ? RoutingStatus.Resubmitted : RoutingStatus.Submitted;
            await DB.SaveChangesAsync();

            //Check for Job Fail trigger, and update Data Partner Routing to Failed.
            //Request status will not be affected.
            if (documents.Any(d => d.DocumentKind == JobFailTriggerFileKind))
            {
                //Reload the entity before updating the status, else EF will report an exception.
                await DB.Entry(reqDM).ReloadAsync();

                reqDM.Status = RoutingStatus.Failed;
                await DB.SaveChangesAsync();
            }

            //change the status of the request to conducting analysis
            //manually override the request status using sql direct, EF does not allow update of computed
            await DB.Database.ExecuteSqlCommandAsync("UPDATE Requests SET Status = @status WHERE ID = @ID", new System.Data.SqlClient.SqlParameter("@status", (int)RequestStatuses.ConductingAnalysis), new System.Data.SqlClient.SqlParameter("@ID", reqDM.Request.ID));

            await DB.Entry(reqDM.Request).ReloadAsync();
        }
Ejemplo n.º 56
0
        public ParticleManager()
        {
            particles = new List <ParticleTemplate>();
            if (System.IO.File.Exists(@"particles.txt"))
            {
                System.IO.StreamReader r = new System.IO.StreamReader(@"particles.txt");
                string           line    = "";
                ParticleTemplate p       = new ParticleTemplate();
                bool             cont    = true;
                while (cont)
                {
                    line = r.ReadLine();
                    if (line.Length == 0 || line[0] == '#')
                    {
                        //skip this line
                    }
                    else
                    {
                        string[] items = line.Split(':');
                        switch (items[0].ToLower())
                        {
                        case "name":
                            if (p.name == "")
                            {
                                p.name = items[1].Trim();
                            }
                            else
                            {
                                particles.Add(p);
                                Exilania.text_stream.WriteLine("Particle Template '" + p.name + "' Loaded.");
                                p      = new ParticleTemplate();
                                p.name = items[1].Trim();
                            }
                            break;

                        case "pic":
                            string[] vals = Acc.script_remove_outer_parentheses(items[1]).Split(',');
                            p.image = new Rectangle(int.Parse(vals[0]), int.Parse(vals[1]), int.Parse(vals[2]), int.Parse(vals[3]));
                            break;

                        case "travel":
                            switch (items[1].ToLower())
                            {
                            case "straight":
                                p.travel_path = TravelType.Straight;
                                break;

                            case "boomerang":
                                p.travel_path = TravelType.Boomerang;
                                break;

                            case "piercing":
                                p.travel_path = TravelType.Piercing;
                                break;

                            case "bouncing":
                                p.travel_path = TravelType.Bouncy;
                                break;

                            case "graceful":
                                p.travel_path = TravelType.Graceful;
                                break;

                            case "haphazard":
                                p.travel_path = TravelType.Haphazard;
                                break;
                            }
                            break;

                        case "gravity":
                            p.gravity_affected = bool.Parse(items[1]);
                            break;

                        case "speed":
                            p.speed = float.Parse(items[1]);
                            break;

                        default:
                            Exilania.text_stream.WriteLine("UNHANDLED type " + items[0]);
                            break;
                        }
                    }
                    if (r.EndOfStream)
                    {
                        particles.Add(p);
                        Exilania.text_stream.WriteLine("Particle Template '" + p.name + "' Loaded.");
                        cont = false;
                    }
                }
                r.Close();
            }
            else
            {
                Exilania.text_stream.Write("ERROR! No furniture.txt file.");
            }
        }
Ejemplo n.º 57
0
        private void DetermineDelimiter()
        {
            string line;
            int    columnCounter = 0;

            char[] possibleDelimiters = { ',', '\t', ';' };
            int[]  delimitersFrequecy = { 0, 0, 0 };
            int    index = 0;


            while (index <= 2)
            {
                System.IO.StreamReader file = new System.IO.StreamReader(_filePath);

                if ((line = file.ReadLine()) != null)
                {
                    string[] result = line.Split(possibleDelimiters[index]);

                    columnCounter = result.Length;

                    Console.WriteLine("for file " + _filePath + " counter is " + columnCounter + " for " + possibleDelimiters[index]);
                    Console.Read();
                }

                bool ok = true;
                while ((line = file.ReadLine()) != null)
                {
                    string[] result = line.Split(possibleDelimiters[index]);

                    //Console.WriteLine("for file " + _filePath + " result counter is " + result.Length + " for " + possibleDelimiters[index]);
                    //Console.Read();

                    if (result.Length != columnCounter)
                    {
                        delimitersFrequecy[index] = 0;
                        ok = false;
                        break;
                    }
                }

                if (ok == true)
                {
                    delimitersFrequecy[index] = columnCounter;
                }

                index++;
                file.Close();
            }

            int maxVal         = 0;
            int delimiterIndex = 0;

            for (int i = 0; i <= 2; i++)
            {
                if (delimitersFrequecy[i] > maxVal)
                {
                    maxVal         = delimitersFrequecy[i];
                    delimiterIndex = i;
                }
            }

            _fileFormat._fileDelimiter = possibleDelimiters[delimiterIndex];
        }
        private static void UpdateProjectAndSolution(string slnFile, string sourceDir, string targetDir, string[] emptyDirectories)
        {
            // NOTE: The logic in this routine counts on unique GUIDS
            // Open the file and read project
            System.IO.StreamReader reader = new System.IO.StreamReader(slnFile);
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.XmlNodeList nodes;
            System.IO.StreamWriter writer;
            string sln = reader.ReadToEnd();

            string[]   slnLines;
            string[]   sAttr;
            string[]   fileNames  = null;
            string[][] GUIDLookup = null;
            //System.IO.Stream stream;
            string sProj;

            reader.Close();

            slnLines = sln.Split('\n');
            foreach (string s in slnLines)
            {
                if (s.Trim().ToLower().StartsWith("project("))
                {
                    if (GUIDLookup == null)
                    {
                        GUIDLookup = new string[1][];
                        fileNames  = new string[1];
                    }
                    else
                    {
                        string[][] GUIDLookupTemp = new string[GUIDLookup.GetLength(0) + 1][];
                        GUIDLookup.CopyTo(GUIDLookupTemp, 0);
                        GUIDLookup = GUIDLookupTemp;
                        //ReDim Preserve GUIDLookup( GUIDLookup.GetUpperBound( 0 ) + 1);
                        string[] fileNamesTemp = new string[fileNames.GetLength(0) + 1];
                        fileNames.CopyTo(fileNamesTemp, 0);
                        fileNames = fileNamesTemp;
                        //ReDim Preserve fileNames( fileNames.GetUpperBound( 0 ) + 1);
                    }
                    sAttr = s.Split(',');
                    // Second position is file, third is GUID  with junk after
                    sAttr[2] = sAttr[2].Substring(sAttr[2].IndexOf("{") + 1);
                    sAttr[2] = sAttr[2].Substring(0, sAttr[2].IndexOf("}"));
                    fileNames[fileNames.GetUpperBound(0)]   = sAttr[1].Replace("\"", "").Trim();
                    GUIDLookup[GUIDLookup.GetUpperBound(0)] = new string[] { new Guid(sAttr[2]).ToString(), Guid.NewGuid().ToString() };
                }
            }
            sln     = ReplaceArray(sln, GUIDLookup);
            slnFile = System.IO.Path.GetFileName(slnFile);
            writer  = new System.IO.StreamWriter(System.IO.Path.Combine(targetDir, slnFile));
            writer.Write(sln);
            writer.Flush();
            writer.Close();

            foreach (string fileName in fileNames)
            {
                reader = new System.IO.StreamReader(System.IO.Path.Combine(System.IO.Path.Combine(sourceDir, System.IO.Path.GetDirectoryName(slnFile)), fileName));
                sProj  = reader.ReadToEnd();
                reader.Close();
                sProj  = ReplaceArray(sProj, GUIDLookup);
                writer = new System.IO.StreamWriter(System.IO.Path.Combine(System.IO.Path.Combine(targetDir, System.IO.Path.GetDirectoryName(slnFile)), fileName));
                writer.Write(sProj);
                writer.Flush();
                writer.Close();

                xmlDoc.Load(System.IO.Path.Combine(System.IO.Path.Combine(targetDir, System.IO.Path.GetDirectoryName(slnFile)), fileName));
                foreach (string exclude in emptyDirectories)
                {
                    nodes = xmlDoc.SelectNodes("//Files/Include/File[starts-with(@RelPath,'" + exclude + "' )]");
                    foreach (System.Xml.XmlNode node in nodes)
                    {
                        node.ParentNode.RemoveChild(node);
                    }
                }
                xmlDoc.Save(System.IO.Path.Combine(System.IO.Path.Combine(targetDir, System.IO.Path.GetDirectoryName(slnFile)), fileName));
            }
        }
Ejemplo n.º 59
0
        public void ImportConfig(string filename)
        {
            if (!System.IO.File.Exists(filename))
            {
                System.Windows.Forms.MessageBox.Show("File does not exist!", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return;
            }

            if (mMachineStatus == MacStatus.Idle)
            {
                try
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(filename))
                    {
                        lock (this)
                        {
                            mSentPtr  = new System.Collections.Generic.List <IGrblRow>();                            //assign sent queue
                            mQueuePtr = new System.Collections.Generic.Queue <GrblCommand>();

                            string rline = null;
                            while ((rline = sr.ReadLine()) != null)
                            {
                                if (rline.StartsWith("$"))
                                {
                                    mQueuePtr.Enqueue(new GrblCommand(rline));
                                }
                            }
                        }

                        try
                        {
                            sr.Close();
                            while (com.IsOpen && (mQueuePtr.Count > 0 || mPending.Count > 0))                             //resta in attesa del completamento della comunicazione
                            {
                                ;
                            }

                            int errors = 0;
                            foreach (IGrblRow row in mSentPtr)
                            {
                                if (row is GrblCommand)
                                {
                                    if (((GrblCommand)row).Result != "OK")
                                    {
                                        errors++;
                                    }
                                }
                            }

                            if (errors > 0)
                            {
                                System.Windows.Forms.MessageBox.Show(String.Format("{0} Config imported with {1} errors!", mSentPtr.Count, errors), "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                            }
                            else
                            {
                                System.Windows.Forms.MessageBox.Show(String.Format("{0} Config imported with success!", mSentPtr.Count), "Success", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                            }
                        }
                        catch { System.Windows.Forms.MessageBox.Show("Error reading file!", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); }

                        lock (this)
                        {
                            mQueuePtr = mQueue;
                            mSentPtr  = mSent;                            //restore queue
                        }
                    }
                }
                catch { System.Windows.Forms.MessageBox.Show("Error reading file!", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); }
            }
        }
Ejemplo n.º 60
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        async Task FromAnalysisCenter(RequestDataMart reqDM)
        {
            //close the current task
            var currentTask = await PmnTask.GetActiveTaskForRequestActivityAsync(reqDM.Request.ID, reqDM.Request.WorkFlowActivityID.Value, DB);

            currentTask.Status          = DTO.Enums.TaskStatuses.Complete;
            currentTask.EndOn           = DateTime.UtcNow;
            currentTask.PercentComplete = 100d;

            //open new task and set the request to the new activity
            var task = DB.Actions.Add(PmnTask.CreateForWorkflowActivity(reqDM.Request.ID, CompleteDistributionActivityID, WorkflowID, DB));

            reqDM.Request.WorkFlowActivityID = CompleteDistributionActivityID;

            //get the documents uploaded by the analysis center
            var documents = await(from rd in DB.RequestDocuments
                                  join rsp in DB.Responses on rd.ResponseID equals rsp.ID
                                  join rdm in DB.RequestDataMarts on rsp.RequestDataMartID equals rdm.ID
                                  join dm in DB.DataMarts on rdm.DataMartID equals dm.ID
                                  join doc in DB.Documents on rd.RevisionSetID equals doc.RevisionSetID
                                  where rdm.RequestID == reqDM.Request.ID &&
                                  rdm.RoutingType == RoutingType.AnalysisCenter &&
                                  rd.DocumentType == RequestDocumentType.Output &&
                                  rsp.Count == rdm.Responses.Max(r => r.Count) &&
                                  doc.ID == DB.Documents.Where(dd => dd.RevisionSetID == doc.RevisionSetID).OrderByDescending(dd => dd.MajorVersion).ThenByDescending(dd => dd.MinorVersion).ThenByDescending(dd => dd.BuildVersion).ThenByDescending(dd => dd.RevisionVersion).Select(dd => dd.ID).FirstOrDefault()
                                  select new
            {
                DocumentID    = doc.ID,
                RevisionSetID = rd.RevisionSetID,
                DocumentKind  = doc.Kind,
                FileName      = doc.FileName
            }).ToArrayAsync();

            if (documents.Any(d => d.DocumentKind == JobFailTriggerFileKind))
            {
                //stop file, end regression.
                CompleteTask(task);
                reqDM.Request.WorkFlowActivityID = CompletedActivityID;

                //Save changes and reload entity
                //If this is not done, EF throws an exception on updating the status of the Request DataMart.
                await DB.SaveChangesAsync();

                await DB.Entry(reqDM).ReloadAsync();

                //Set the routing status to Failed.
                reqDM.Status = RoutingStatus.Failed;
                await DB.SaveChangesAsync();

                //change the status of the request to Failed
                //manually override the request status using sql direct, EF does not allow update of computed
                await DB.Database.ExecuteSqlCommandAsync("UPDATE Requests SET Status = @status WHERE ID = @ID", new System.Data.SqlClient.SqlParameter("@status", (int)RequestStatuses.Failed), new System.Data.SqlClient.SqlParameter("@ID", reqDM.Request.ID));

                return;
            }

            if (documents.Any(d => d.DocumentKind == StopProcessingTriggerDocumentKind))
            {
                //stop file, end regression. All the routes should be complete now and the request status should be already in Completed. Just need to update the current activity.
                CompleteTask(task);
                reqDM.Request.WorkFlowActivityID = CompletedActivityID;

                //NOTE: notification of complete request will be handled outside of the helper
            }
            else
            {
                if (documents.Length > 0)
                {//ASPE-605: change the association of the document owner from the analysis center response to the complete distribution task (current task).
                 //This is to support showing the AC documents in the task documents tab.

                    //add a reference to the response to the current task so that we can track back to the source.
                    try
                    {
                        Guid currentResponseID = await DB.Responses.Where(rsp => rsp.RequestDataMartID == reqDM.ID && rsp == rsp.RequestDataMart.Responses.OrderByDescending(rrsp => rrsp.Count).FirstOrDefault()).Select(rsp => rsp.ID).FirstAsync();

                        if (DB.Entry(currentTask).Collection(t => t.References).IsLoaded == false)
                        {
                            await DB.Entry(currentTask).Collection(t => t.References).LoadAsync();
                        }
                        if (currentTask.References.Any(tr => tr.ItemID == currentResponseID) == false)
                        {
                            task.References.Add(new TaskReference {
                                TaskID = currentTask.ID, ItemID = currentResponseID, Type = TaskItemTypes.Response
                            });
                        }
                    }catch
                    {
                        //do not kill processing if this fails, eventlog builder has contingencies to handle if the task reference to the response is not set.
                    }

                    StringBuilder query = new StringBuilder();
                    query.Append("UPDATE Documents SET ItemID='" + currentTask.ID.ToString("D") + "'");
                    query.Append(" WHERE ID IN (");
                    query.Append(string.Join(",", documents.Select(d => string.Format("'{0:D}'", d.DocumentID))));
                    query.Append(")");
                    await DB.Database.ExecuteSqlCommandAsync(query.ToString());
                }

                //the output files from the analysis center will now become the input files for each active dataparter route
                List <Guid> responseIDs = new List <Guid>();

                var allTasks = await DB.ActionReferences.Where(tr => tr.ItemID == reqDM.Request.ID &&
                                                               tr.Type == DTO.Enums.TaskItemTypes.Request &&
                                                               tr.Task.Type == DTO.Enums.TaskTypes.Task
                                                               )
                               .Select(tr => tr.Task.ID).ToArrayAsync();

                var attachments = await(from doc in DB.Documents.AsNoTracking()
                                        join x in (
                                            DB.Documents.Where(dd => allTasks.Contains(dd.ItemID))
                                            .GroupBy(k => k.RevisionSetID)
                                            .Select(k => k.OrderByDescending(d => d.MajorVersion).ThenByDescending(d => d.MinorVersion).ThenByDescending(d => d.BuildVersion).ThenByDescending(d => d.RevisionVersion).Select(y => y.ID).Distinct().FirstOrDefault())
                                            ) on doc.ID equals x
                                        where allTasks.Contains(doc.ItemID) && doc.Kind == "Attachment.Input"
                                        orderby doc.ItemID descending, doc.RevisionSetID descending, doc.CreatedOn descending
                                        select doc).ToArrayAsync();

                var dataPartnerRoutes = await DB.RequestDataMarts.Include(rdm => rdm.Responses).Where(rdm => rdm.RequestID == reqDM.Request.ID && rdm.Status != RoutingStatus.Canceled && rdm.RoutingType == RoutingType.DataPartner).ToArrayAsync();

                foreach (var route in dataPartnerRoutes)
                {
                    var response = route.AddResponse(IdentityID);
                    responseIDs.Add(response.ID);

                    route.Status = response.Count > 1 ? RoutingStatus.Resubmitted : RoutingStatus.Submitted;

                    foreach (var attachment in attachments)
                    {
                        DB.RequestDocuments.Add(new RequestDocument {
                            RevisionSetID = attachment.RevisionSetID.Value, ResponseID = response.ID, DocumentType = DTO.Enums.RequestDocumentType.AttachmentInput
                        });
                    }
                }

                var filelistDocument = documents.Where(d => !string.IsNullOrEmpty(d.DocumentKind) && string.Equals("DistributedRegression.FileList", d.DocumentKind, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (filelistDocument != null)
                {
                    //only include the files indicated in the filelist document
                    using (var ds = new Lpp.Dns.Data.Documents.DocumentStream(DB, filelistDocument.DocumentID))
                        using (var reader = new System.IO.StreamReader(ds))
                        {
                            //read the header line
                            reader.ReadLine();

                            string line, filename;
                            bool   includeInDistribution = false;
                            while (!reader.EndOfStream)
                            {
                                line = reader.ReadLine();
                                string[] split = line.Split(',');
                                if (split.Length > 0)
                                {
                                    filename = split[0].Trim();
                                    if (split.Length > 1)
                                    {
                                        includeInDistribution = string.Equals(split[1].Trim(), "1");
                                    }
                                    else
                                    {
                                        includeInDistribution = false;
                                    }

                                    if (includeInDistribution == false)
                                    {
                                        continue;
                                    }

                                    if (!string.IsNullOrEmpty(filename))
                                    {
                                        Guid?revisionSetID = documents.Where(d => string.Equals(d.FileName, filename, StringComparison.OrdinalIgnoreCase)).Select(d => d.RevisionSetID).FirstOrDefault();
                                        if (revisionSetID.HasValue)
                                        {
                                            DB.RequestDocuments.AddRange(responseIDs.Select(rspID => new RequestDocument {
                                                DocumentType = RequestDocumentType.Input, ResponseID = rspID, RevisionSetID = revisionSetID.Value
                                            }).ToArray());
                                        }
                                    }
                                }
                            }

                            reader.Close();
                        }
                }
                else
                {
                    var requestDocuments = (from d in documents
                                            from responseID in responseIDs
                                            where d.DocumentKind != "DistributedRegression.AdapterEventLog" && d.DocumentKind != "DistributedRegression.TrackingTable"
                                            select new RequestDocument
                    {
                        DocumentType = RequestDocumentType.Input,
                        ResponseID = responseID,
                        RevisionSetID = d.RevisionSetID
                    }).ToArray();

                    if (requestDocuments.Length > 0)
                    {
                        DB.RequestDocuments.AddRange(requestDocuments);
                    }
                }
            }

            await DB.SaveChangesAsync();
        }