Example #1
0
        public static void Main(String[] args)
        {
            String toolName = typeof(Program).GetTypeInfo().Assembly.GetName().Name;
            String path = Path.GetFullPath(Directory.GetCurrentDirectory());
            GennyApplication application = new GennyApplication();
            Project project = ProjectReader.GetProject(path);
            application.Name = project.Name;
            application.BasePath = path;

            if (args.Contains("--no-dispatch"))
            {
                new GennyCommand(application).Execute(args.Where(arg => arg != "--no-dispatch").ToArray());
            }
            else
            {
                ProjectDependenciesCommandFactory factory = new ProjectDependenciesCommandFactory(
                    project.GetTargetFrameworks().FirstOrDefault().FrameworkName,
                    Constants.DefaultConfiguration,
                    null,
                    null,
                    path);

                factory
                    .Create(toolName, args.Concat(new[] { "--no-dispatch" }).ToArray())
                    .ForwardStdErr()
                    .ForwardStdOut()
                    .Execute();
            }
        }
Example #2
0
 static ParsedLog[] ParseLog(String[] lines)
 {
     return lines
         .Where(x => x.Trim().Length > 0 && !x.StartsWith("#"))
         .Select(x => new ParsedLog(x))
         .ToArray();
 }
Example #3
0
 public static IEnumerable<CharacterCount> AnalyzeWord(String word)
 {
     return word.Where(c => !Char.IsWhiteSpace(c))
         .OrderBy(Char.ToLower)
         .GroupBy(c => c)
         .Select(grouping => new CharacterCount { Key = grouping.Key, Count = grouping.Count() });
 }
 public static String RemovePunctuation(String input)
 {
     String result = "";
     String noPunc = new string(input.Where(c => !char.IsPunctuation(c)).ToArray());
     result = noPunc;
     return result;
 }
            /// <summary>
            /// Convert string value to decimal ignore the culture.
            /// </summary>
            /// <param name="value">The value.</param>
            /// <returns>Decimal value.</returns>
            public static decimal ToDecimal(string value)
            {
                decimal number;
                value = new String(value.Where(c => char.IsPunctuation(c) || char.IsNumber(c)).ToArray());
                string tempValue = value;

                var punctuation = value.Where(x => char.IsPunctuation(x)).Distinct();
                int count = punctuation.Count();

                NumberFormatInfo format = CultureInfo.InvariantCulture.NumberFormat;
                switch (count)
                {
                    case 0:
                        break;
                    case 1:
                        tempValue = value.Replace(",", ".");
                        break;
                    case 2:
                        if (punctuation.ElementAt(0) == '.')
                            tempValue = SwapChar(value, '.', ',');
                        break;
                    default:
                        throw new InvalidCastException();
                }

                number = decimal.Parse(tempValue, format);
                return number;
            }
Example #6
0
 public static Boolean IsNameMatch(this MangaObject value, String name)
 {
     if (value == null)
         return false;
     String _name = new String(name.Where(Char.IsLetterOrDigit).ToArray()).ToLower();
     return new String(value.Name.Where(Char.IsLetterOrDigit).ToArray()).ToLower().Contains(_name) ||
         value.AlternateNames.FirstOrDefault(o => new String(o.Where(Char.IsLetterOrDigit).ToArray()).ToLower().Contains(_name)) != null;
 }
Example #7
0
 public void StartWatch(String[] watchPaths)
 {
     foreach (var watchPath in watchPaths.Where(x => Directory.Exists(x) || File.Exists(x)))
     {
         if (!String.IsNullOrWhiteSpace(watchPath))
         {
             StartWatch(watchPath);
         }
     }
 }
Example #8
0
		public Hashids(string salt = "", int minHashLength = MIN_HASH_LENGTH, string alphabet = DEFAULT_ALPHABET) {
			if (string.IsNullOrWhiteSpace(alphabet))
				throw new ArgumentNullException("alphabet");

			if (alphabet.Contains(' '))
				throw new ArgumentException("alphabet cannot contain spaces", "alphabet");

			Alphabet = new String(alphabet.Distinct().ToArray());

			Salt = salt;
			MinHashLength = minHashLength;

			// separators should be in the alphabet
			Separators = DEFAULT_SEPARATORS;
			Separators = new String(Separators.Where(x => Alphabet.Contains(x)).ToArray());

			if (string.IsNullOrWhiteSpace(Separators))
				throw new ArgumentException("alphabet does not contain separators", "separators");

			Separators = ConsistentShuffle(input: Separators, salt: Salt);

			// remove separator characters from the alphabet
			Alphabet = new String(Alphabet.Where(x => !Separators.Contains(x)).ToArray());

			if (string.IsNullOrWhiteSpace(Alphabet) || Alphabet.Length < MIN_ALPHABET_LENGTH)
				throw new ArgumentException("alphabet must contain atleast " + MIN_ALPHABET_LENGTH + " unique, non-separator characters.", "alphabet");

			double sepDivisor = 3.5;
			if ((Separators.Length == 0) || (((double)Alphabet.Length / (double)Separators.Length) > sepDivisor)) {
				int sepsLength = (int)Math.Ceiling(Alphabet.Length / sepDivisor);

				if (sepsLength == 1)
					sepsLength++;

				if (sepsLength > Separators.Length) {
					int diff = sepsLength - Separators.Length;
					Separators += Alphabet.Substring(0, diff);
					Alphabet = Alphabet.Substring(diff);
				} else {
					Separators = Separators.Substring(0, sepsLength);
				}
			}

			double guardDivisor = 12.0;
			Alphabet = ConsistentShuffle(input: Alphabet, salt: Salt);
			int guardCount = (int)Math.Ceiling(Alphabet.Length / guardDivisor);

			if (Alphabet.Length < 3) {
				Guards = Separators.Substring(0, guardCount);
				Separators = Separators.Substring(guardCount);
			} else {
				Guards = Alphabet.Substring(0, guardCount);
				Alphabet = Alphabet.Substring(guardCount);
			}
		}
Example #9
0
 /// <summary>
 /// Parse a string representation of a dice roll (a roll string)
 /// </summary>
 /// <param name="input">Roll string to parse</param>
 public DiceRoll(String input)
 {
     if (input == null)
     {
         this.d10 = this.d5 = this.Modifier = 0;
         return;
     }
     String roll = new string(input.Where(c => !Char.IsWhiteSpace(c)).ToArray());//strip whitespace
     this.d10 = this.d5 = 0;
     int index = 0;
     int previous = index;
     while (index < roll.Length)
     {
         if (roll[index++] == 'd')
         {
             if (roll[index] == '1' && roll[index + 1] == '0')
             {
                 if (previous == index - 1)
                     d10 = 1;
                 else
                     d10 = Int32.Parse(roll.Substring(previous, index - previous - 1));
                 index++;//move to the 0 so the final ++ puts after the dice
             }
             else if (roll[index] == '5')
             {
                 if (previous == index - 2)
                     d5 = 1;
                 else
                     d5 = Int32.Parse(roll.Substring(previous, index - previous - 1));
             }
             else
                 throw new FormatException("Only d10 and d5 are supported");
             index++;//point after the dice
             previous = index;//advance last found
         }
     }
     if (previous == index)
         Modifier = 0;
     else
         Modifier = Int32.Parse(roll.Substring(previous, index - previous));
 }
        public String[] getNews(String[] topics) {
            topics = topics.Where(x => !string.IsNullOrEmpty(x)).ToArray();
            String baseUrl = "https://webhose.io/search?token="your token";
            String[] emptyArray=new String[1];
            if(topics.Length==0){
            emptyArray[1]="please give some input";
            return emptyArray;
            }

            String query = "&q=";
            for (int i = 0; i < topics.Length; i++)
            {
                    if (i < topics.Length - 1)
                    {
                        query = query + topics[i] + " OR ";
                    }
                    else query = query + topics[i];
                
            }

            query = query + "&language=english" + "&size=100"+"&is_first=true";
            
            HttpWebRequest request = WebRequest.Create(baseUrl+query) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(response.GetResponseStream());

            XmlNodeList nl = xmlDoc.GetElementsByTagName("post");
            String[] res = new String[nl.Count];
           for (int i = 0; i < nl.Count; i++)
            {
                res[i] = nl.Item(i).ChildNodes.Item(2).InnerText;
             }
            return res;
		        
        }
        /// <summary>
        /// Creates new unassigned property in database.
        /// </summary>
        /// <param name="name">Should be correct.</param>
        /// <param name="systemName">Should be latin singleline word.</param>
        /// <param name="type">Only types defined in this program.</param>
        /// <param name="availableValues">Only for types with selection.</param>
        /// <exception cref="ConnectionException" />
        /// <exception cref="BadSystemNameException" />
        /// <exception cref="BadPropertyTypeException" />
        /// <exception cref="BadDisplayTypeNameException" />
        public void CreateNewProperty(String name, String systemName, String type, String[] availableValues)
        {
            if(name == null)
            {
                throw new BadSystemNameException();
            }
            name = name.CutWhitespaces();
            systemName = systemName.CutWhitespaces();
            if(!TypeValidationHelper.IsValidSystemName(systemName))
            {
                throw new BadSystemNameException();
            }

            if(!TypeValidationHelper.IsValidType(type))
            {
                throw new BadPropertyTypeException();
            }

            if(!TypeValidationHelper.IsValidDisplayName(name))
            {
                throw new BadDisplayTypeNameException();
            }
            Property creating = new Property();
            creating.DisplayName = name;
            creating.SystemName = systemName;
            creating.Type = type;

            if (!ConnectionHelper.CreateProperty(creating))
            {
                throw new BadSystemNameException();
            }
            if (TypeValidationHelper.IsSelectable(type))
            {
                ConnectionHelper.AddAvailableValues(availableValues.Where(x => TypeValidationHelper.IsValidValue(x)), creating);
            }
        }
Example #12
0
 public static String fixYearMonth(String s, out int newPosition)
 {
     newPosition = -1;
       String res = new String(s.Where(Char.IsDigit).ToArray());
       if (res.Length > 4) {
     res = res.Substring(0, 4);
     //newPosition = 0;
       }
       if (res.Length == 3) {
     int month = int.Parse(res.Substring(2, 1));
     if (month > 1) {
       res = res.Substring(0, 2);
       newPosition = 2;
     }
       }
       if (res.Length == 4) {
     int month = int.Parse(res.Substring(2, 2));
     if ((month <= 0) || (month > 12)) {
       res = res.Substring(0, 2);
       newPosition = 2;
     }
       }
       return res;
 }
Example #13
0
 public static bool ParseAsDirective(SmaliLine rv, String sInst, ref String[] sWords, ref String sRawText)
 {
     switch (sInst)
     {
         case ".class":
             rv.Instruction = LineInstruction.Class;
             SetModifiers(rv, ref sWords, 1, sWords.Length - 1);
             rv.aClassName = sWords[sWords.Length - 1];
             break;
         case ".super":
             rv.Instruction = LineInstruction.Super;
             rv.aType = sWords[1];
             break;
         case ".implements":
             rv.Instruction = LineInstruction.Implements;
             rv.aType = sWords[1];
             break;
         case ".source":
             rv.Instruction = LineInstruction.Source;
             rv.aExtra = sRawText;
             break;
         case ".field":
             rv.Instruction = LineInstruction.Field;
             SetModifiers(rv, ref sWords, 1, sWords.Length - 1);
             sRawText = String.Join(" ", sWords.Where(x => !String.IsNullOrEmpty(x)).ToArray()).Trim();
             rv.aName = sRawText.Split(':')[0];
             rv.aType = sRawText.Split(':')[1];
             break;
         case ".method":
             rv.Instruction = LineInstruction.Method;
             SetModifiers(rv, ref sWords, 1, sWords.Length - 1);
             sRawText = String.Join(" ", sWords.Where(x => !String.IsNullOrEmpty(x)).ToArray()).Trim();
             rv.aExtra = sRawText;
             break;
         case ".prologue":
             rv.Instruction = LineInstruction.Prologue;
             break;
         case ".registers":
             rv.Instruction = LineInstruction.Registers;
             break;
         case ".line":
             rv.Instruction = LineInstruction.Line;
             break;
         case ".end":
             switch (sRawText)
             {
                 case ".end method":
                     rv.Instruction = LineInstruction.EndMethod;
                     break;
             }
             break;
         case ".param":
             rv.Instruction = LineInstruction.Parameter;
             sWords[1] = sWords[1].Replace(",", "");
             rv.lRegisters[sWords[1].Trim()] = String.Empty;
             rv.aName = sRawText.Substring(sRawText.IndexOf('"') + 1);
             rv.aName = rv.aName.Substring(0, rv.aName.IndexOf('"'));
             rv.aType = sRawText.Substring(sRawText.IndexOf('#') + 1).Trim();
             break;
         default:
             return false;
     }
     return true;
 }
Example #14
0
 /// <summary>
 /// Peek ahead and see if the specified string is present.
 /// </summary>
 /// <param name="str">The string we are looking for.</param>
 /// <returns>True if the string was found.</returns>
 public bool Peek(String str)
 {
     return !str.Where((t, i) => Peek(i) != t).Any();
 }
Example #15
0
        public string ProcessData()
        {
            string strLog = "";
            XmlDocument xmlDoc = new XmlDocument();
            IOAuthSession session;
            DateTime DueDate = DateTime.Now;
            string strd;
            string Subject;
            string jpgfilename;
            Email.Email eml = new Email.Email();

            try
            {
                session = XeroAPI();
                Repository repository = new Repository(session);
                //OpreateData opftp = new OpreateData();
                //string strLogs = opftp.GetDataFromServer(ref connectionSuccess);//, ref index);
                HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                DataSet dsProductNotification = new DataSet();
                String[] OrderId = null;
                foreach (string file in Directory.EnumerateFiles(FullPath, "*.htm"))
                {
                    filename = Path.GetFileName(file);
                    // filename = "201404161759591372889.htm";
                    htmlDoc.Load(file);
                    StartBrowser(htmlDoc.DocumentNode.OuterHtml);

                }

                // }
                foreach (string file in Directory.EnumerateFiles(FullPath, "*.htm"))
                {
                    int propertyId = 0;
                    string location=string.Empty;

                    filename = Path.GetFileName(file);
                    jpgfilename = filename.Replace("htm", "jpg");
                    // filename = "201404161759591372889.htm";
                    XmlNode rootElement = xmlDoc.CreateElement("Root");
                    xmlDoc.AppendChild(rootElement);
                    htmlDoc.Load(file);
                    htmlDoc.OptionWriteEmptyNodes = true;
                    htmlDoc.OptionOutputAsXml = true;
                    string value = "";
                    HtmlNodeCollection nodesitemheading = htmlDoc.DocumentNode.SelectNodes(".//b");
                    /*This is an order notification from Robin Parker at Marshall White Brighton<br />
                    <i>Relating to
                     campaign: 11 Lagnicourt Street, Hampton</i> */

                    String[] SplitValues = new String[1000];

                    XmlElement Element = xmlDoc.CreateElement("PrimaryContact");
                    try
                    {
                        SplitValues = Splits(sep(nodesitemheading[0].InnerText, "from "), new char[] { ' ' });
                    }
                    catch
                    {
                        File.Move(file, System.Configuration.ConfigurationSettings.AppSettings["Error"] + "\\" + filename);
                        File.Move(file.Replace("htm", "txt"), System.Configuration.ConfigurationSettings.AppSettings["Error"] + "\\" + filename.Replace("htm", "txt"));
                        xmlDoc.RemoveAll();
                        continue;
                    };

                    string cncl1 = "", cncl2 = "", cncl3 = "";

                    if (nodesitemheading[0].InnerText.Contains("The order listed below was cancelled by"))
                    {

                        IList<string> arrayAsList = (IList<string>)SplitValues;
                        int index;
                        index = arrayAsList.IndexOf("campaign:");
                        if (index == -1)
                            index = arrayAsList.IndexOf("\r\ncampaign:");
                        for (int i = index + 1; i < SplitValues.Length; i++)
                        {
                            if (SplitValues[i].Contains("of")) { break; };
                            cncl1 = cncl1 + " " + SplitValues[i];//email body subject
                            cncl1 = cncl1.Replace("Description", "").Replace("\r\n", "");
                        }

                        IList<string> arrayAsList1 = (IList<string>)SplitValues;
                        int index1 = arrayAsList.IndexOf("being");
                        for (int i = index1 + 2; i < SplitValues.Length; i++)
                        {
                            if (SplitValues[i].Contains("on")) { break; };
                            cncl2 = cncl2 + " " + SplitValues[i];//email body subject
                            cncl2 = cncl2.Replace("Required", "").Replace("\r\n", "");
                        }
                        IList<string> arrayAsList2 = (IList<string>)SplitValues;
                        int index2 = arrayAsList.IndexOf("on");
                        cncl3 = SplitValues[index2 + 1].Replace("Product", "");

                        InsertCancelledOrders(cncl1, cncl2, cncl3, filename);
                        File.Move(file, System.Configuration.ConfigurationSettings.AppSettings["Cancelled"] + "\\" + filename);
                        File.Move(file.Replace("htm", "txt"), System.Configuration.ConfigurationSettings.AppSettings["Cancelled"] + "\\" + filename.Replace("htm", "txt"));
                        xmlDoc.RemoveAll();
                        continue;
                    }

                    string str11 = "", str22 = "", str33 = "";
                    try
                    {
                        #region Fixed on 9 Oct 2014

                        if (SplitValues[3] == "at")
                        {
                            var midleName = SplitValues[1];
                            SplitValues = SplitValues.Where(x => x != midleName).ToArray();
                            var lastName = SplitValues[1];
                            SplitValues[1] = midleName + " " + lastName;
                        }

                        #endregion

                        str11 = SplitValues[0] + " " + SplitValues[1];//primary contact
                        str22 = SplitValues[3] + " " + SplitValues[4] + " " + SplitValues[5];//company name
                        str22 = str22.Replace("Relating", "");

                        //if (SplitValues[7].Contains("to"))
                        //{
                        //    str33 = "";
                        //    for (int i = 8; i < SplitValues.Length; i++)
                        //    {
                        //        str33 = str33 + " " + SplitValues[i];//email body subject
                        //    }
                        //}
                        //else
                        //    str33 = SplitValues[7] + " " + SplitValues[8] + " " + SplitValues[9] + " " + SplitValues[10] + SplitValues[11];//email body subject

                        IList<string> arrayAsList = (IList<string>)SplitValues;
                        int index;
                        index = arrayAsList.IndexOf("Relating".Replace("\r\n", ""));
                        if (index == -1)
                            index = arrayAsList.IndexOf("\r\ncampaign:");//campaign:
                        if (index == -1)
                            index = arrayAsList.IndexOf("campaign:");//campaign:

                        for (int i = index + 1; i < SplitValues.Length; i++)
                        {
                            if (SplitValues[i].Contains("of")) { break; };
                            str33 = str33 + " " + SplitValues[i];//email body subject
                            str33 = str33.Replace("Description", "").Replace("\r\n", "");
                        }

                        //if (SplitValues[7].Contains("Relating"))
                        //{
                        //    str33 = "";
                        //    for (int i = 10; i < SplitValues.Length; i++)
                        //    {
                        //        str33 = str33 + " " + SplitValues[i];//email body subject
                        //    }
                        //}
                    }
                    catch
                    {
                        File.Move(file, System.Configuration.ConfigurationSettings.AppSettings["Error"] + "\\" + filename);
                        File.Move(file.Replace("htm", "txt"), System.Configuration.ConfigurationSettings.AppSettings["Error"] + "\\" + filename.Replace("htm", "txt"));
                        xmlDoc.RemoveAll();
                        continue;
                    };
                    XmlElement PrimaryContactElement = xmlDoc.CreateElement("PrimaryContact");
                    PrimaryContactElement.InnerText = str11;
                    rootElement.AppendChild(PrimaryContactElement);

                    XmlElement CompanyNameElement = xmlDoc.CreateElement("CompanyName");
                    CompanyNameElement.InnerText = str22;
                    rootElement.AppendChild(CompanyNameElement);

                    XmlElement EmailBodySubjectElement = xmlDoc.CreateElement("EmailBodySubject");
                    EmailBodySubjectElement.InnerText = nodesitemheading[0].InnerText;
                    rootElement.AppendChild(EmailBodySubjectElement);

                    XmlElement PropertyNameElement = xmlDoc.CreateElement("PropertyName");
                    str33 = str33.Replace("campaign:", "");
                    PropertyNameElement.InnerText = str33;
                    rootElement.AppendChild(PropertyNameElement);
                    location = str33;

                    XmlElement FileNameElement = xmlDoc.CreateElement("FileName");
                    FileNameElement.InnerText = Path.GetFileName(file);
                    rootElement.AppendChild(FileNameElement);
                    string strfile = file.Replace("htm", "txt");
                    string[] lines = File.ReadAllLines(strfile);

                    string From = lines[0].ToString().Replace("From:", "");
                    XmlElement FromElement = xmlDoc.CreateElement("From");
                    FromElement.InnerText = From;
                    rootElement.AppendChild(FromElement);

                    string SentDate = lines[1].ToString().Replace("SentDate:", "");
                    XmlElement SentDateElement = xmlDoc.CreateElement("SentDate");
                    //DateTime objSentDate = Convert.ToDateTime(SentDate,CultureInfo.CreateSpecificCulture("en-US"));
                    DateTime objSentDate = DateTime.Parse(SentDate, CultureInfo.GetCultureInfo("en-gb"));
                    SentDateElement.InnerText = objSentDate.Month.ToString().PadLeft(2, '0') + "/" + objSentDate.Day.ToString().PadLeft(2, '0') + "/" + objSentDate.Year + " " + objSentDate.ToLongTimeString();
                    rootElement.AppendChild(SentDateElement);

                    Subject = lines[2].ToString().Replace("Subject:", "");
                    XmlElement SubjectElement = xmlDoc.CreateElement("Subject");
                    SubjectElement.InnerText = Subject;
                    rootElement.AppendChild(SubjectElement);

                    HtmlNodeCollection nodesitemcontacts = htmlDoc.DocumentNode.SelectNodes(".//td[@class='content']");
                    //htmlDoc.DocumentNode.SelectNodes(".//td[@class='content']")[0].ChildNodes
                    foreach (HtmlNode childNode in nodesitemcontacts)
                    {
                        if (childNode.ChildNodes.Count > 0)
                        {
                            foreach (HtmlNode childOfChildNode in childNode.ChildNodes)
                            {
                                if (childOfChildNode.Name == "#text")
                                {
                                    if (childOfChildNode.ChildNodes.Count == 0)
                                    {

                                        if (childOfChildNode.InnerText.Trim().Contains("Property ID") || childOfChildNode.InnerText.Trim().Contains("Property"))
                                        {
                                            //MessageBox.Show(childOfChildofChildNode.InnerText.Trim().Replace("Property ID:", ""));//Property Id
                                            XmlElement PropertyIdElement = xmlDoc.CreateElement("PropertyId");

                                            PropertyIdElement.InnerText = childOfChildNode.InnerText.Trim().Replace("Property ID:", "").Replace("\r\n", "").Replace("Property ID:", "");
                                            rootElement.AppendChild(PropertyIdElement);
                                            try
                                            {
                                                propertyId = int.Parse(PropertyIdElement.InnerText);
                                            }
                                            catch
                                            { }

                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("OrderItem"))
                                        {
                                            // MessageBox.Show(childOfChildofChildNode.InnerText.Trim().Replace("OrderItem:", ""));
                                            String[] SplitValue = Splits(childOfChildNode.InnerText.Trim().Replace("OrderItem:", ""), new char[] { ',' });//Order Item Id
                                            OrderId = SplitValue;
                                            SplitValueOrderItemId = Splits(childOfChildNode.InnerText.Trim().Replace("OrderItem:", ""), new char[] { ',' });
                                            XmlElement OrderItemIdElement = xmlDoc.CreateElement("OrderItemId");
                                            for (int i = 0; i < SplitValue.Length; i++)
                                            {
                                                string str = SplitValue[i];
                                                XmlElement IdElement = xmlDoc.CreateElement("Id");
                                                IdElement.InnerText = str.Trim();
                                                OrderItemIdElement.AppendChild(IdElement);
                                            }
                                            rootElement.AppendChild(OrderItemIdElement);
                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("Sales contacts"))
                                        {
                                            // MessageBox.Show(childOfChildofChildNode.InnerText.Trim().Replace("Sales contacts:", ""), "8");
                                            String[] SplitValue = Splits(childOfChildNode.InnerText.Trim().Replace("Sales contacts:", ""), new char[] { ',' });
                                            for (int i = 0; i < SplitValue.Length; i++)
                                            {
                                                string str = (SplitValue[i].Replace(" on ", ",").Replace("\r\non", ","));
                                                String[] strValue = Splits(str, new char[] { ',' });

                                                string str1 = strValue[0];//Sales contact name
                                                string str2 = strValue[1].Replace("or", "");//Sales contact phone number

                                                XmlElement SalesContactElement = xmlDoc.CreateElement("SalesContact");
                                                SalesContactElement.InnerText = str1.Trim(); ;
                                                rootElement.AppendChild(SalesContactElement);

                                                XmlElement SalesContactNumberElement = xmlDoc.CreateElement("SalesContactNumber");
                                                SalesContactNumberElement.InnerText = str2.Trim();
                                                rootElement.AppendChild(SalesContactNumberElement);

                                            }

                                            HtmlNodeCollection adminemail = htmlDoc.DocumentNode.SelectNodes(".//a[@href]");
                                            string stradmin = adminemail[1].InnerText;//Admin email address

                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("Admin contact"))
                                        {
                                            // MessageBox.Show(childOfChildofChildNode.InnerText.Trim(), "9");
                                            // String[] SplitValue = Splits(childOfChildNode.InnerText.Trim().Replace("Admin contact:", "").Replace(" on", ","), new char[] { ',' });
                                            String[] SplitValue = Splits(childOfChildNode.InnerText.Trim().Replace("Admin contact:", "").Replace(" on", ","), "or".ToCharArray());

                                            string admindetails = childOfChildNode.InnerText.Trim().Replace("Admin contact:", "");//Admin contact name
                                            string str1;
                                            try
                                            {
                                                // bool string1Matched = Regex.IsMatch(string1, @"\bthe\b", RegexOptions.IgnoreCase);
                                                str1 = admindetails.Substring(0, admindetails.IndexOf(" or "));
                                                str1 = str1.Substring(0, str1.IndexOf(" on "));//Admin name
                                                string str2;
                                                str2 = admindetails.Substring(0, admindetails.IndexOf(" or "));
                                                str2 = str2.Substring(str2.LastIndexOf(" on ") + 3);//Admin Phone

                                                string str3 = "";
                                                str3 = admindetails.Substring(admindetails.IndexOf(" or ") + 4);
                                                XmlElement AdminContactElement = xmlDoc.CreateElement("AdminContact");
                                                AdminContactElement.InnerText = str1.Trim();
                                                rootElement.AppendChild(AdminContactElement);

                                                XmlElement AdminContactNumberElement = xmlDoc.CreateElement("AdminContactNumber");
                                                AdminContactNumberElement.InnerText = str2.Trim();
                                                rootElement.AppendChild(AdminContactNumberElement);

                                                XmlElement AdminContactEmailElement = xmlDoc.CreateElement("AdminContactEmail");
                                                AdminContactEmailElement.InnerText = str3.Trim();
                                                rootElement.AppendChild(AdminContactEmailElement);
                                            }
                                            catch (Exception ex)
                                            {
                                                strLog = ex.StackTrace.ToString();
                                                WriteLog(strLog + " " + filename);
                                            }

                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("Supplier:"))
                                        {
                                            //MessageBox.Show(childOfChildofChildNode.InnerText.Trim(), "10");
                                            string str1 = childOfChildNode.InnerText.Replace("Supplier:", "");//Product

                                            XmlElement SupplierElement = xmlDoc.CreateElement("Supplier");
                                            SupplierElement.InnerText = str1.Trim();
                                            rootElement.AppendChild(SupplierElement);
                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("Description of product/service being ordered:"))
                                        {
                                            value = "Description of product";
                                            continue;
                                        }

                                        if (value == "Description of product")
                                        {
                                            //MessageBox.Show(childOfChildofChildNode.InnerText.Trim(), "11");
                                            string str = childOfChildNode.InnerText.Replace("Description of product/service being ordered: ", "");//Product Description
                                            value = "";

                                            XmlElement DescriptionElement = xmlDoc.CreateElement("Description");
                                            DescriptionElement.InnerText = str.Trim();
                                            rootElement.AppendChild(DescriptionElement);
                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("Required"))
                                        {
                                            // MessageBox.Show(childOfChildofChildNode.InnerText.Trim(), "12");

                                            string RequiredDate = childOfChildNode.InnerText.Replace("Required on", "").Replace("Required \r\non", "").Replace("\r\n", "");//Required Date
                                            DateTime objRequiredDate = DateTime.Parse(RequiredDate, CultureInfo.GetCultureInfo("en-gb"));
                                            XmlElement RequiredDateElement = xmlDoc.CreateElement("RequiredDate");
                                            // RequiredDateElement.InnerText = objRequiredDate.Month.ToString().PadLeft(2, '0') + "-" + objRequiredDate.Day.ToString().PadLeft(2, '0') + "-" + objRequiredDate.Year;
                                            RequiredDateElement.InnerText = objRequiredDate.ToShortDateString();
                                            rootElement.AppendChild(RequiredDateElement);
                                            DueDate = Convert.ToDateTime(objRequiredDate.ToShortDateString());
                                            //DueDate = DateTime.Parse(RequiredDate, "dd/MM/yyyy").ToString("MM/dd/yyyy");
                                        }

                                        if (value == "PROPERTY")
                                        {
                                            //    MessageBox.Show(childOfChildofChildNode.InnerText, "2");//Property Comments

                                            XmlElement PropertyDetailsElement = xmlDoc.CreateElement("PropertyDetails");
                                            PropertyDetailsElement.InnerText = childOfChildNode.InnerText;
                                            rootElement.AppendChild(PropertyDetailsElement);

                                            HtmlNodeCollection propertycomments = htmlDoc.DocumentNode.SelectNodes(".//i");
                                            string str = propertycomments[1].InnerText;//Property Comments
                                            value = "";

                                            XmlElement PropertyCommentsElement = xmlDoc.CreateElement("PropertyComments");
                                            PropertyCommentsElement.InnerText = str.Trim();
                                            rootElement.AppendChild(PropertyCommentsElement);

                                        }
                                        if (childOfChildNode.InnerText.Trim() == "PROPERTY")
                                        {
                                            value = "PROPERTY";
                                            continue;
                                        }

                                        //}
                                        // }

                                    }
                                }
                            }
                        }
                    }

                    HtmlNodeCollection Nds = htmlDoc.DocumentNode.SelectNodes(".//table[@cellpadding='3']");
                    int cnt = 1;

                    if (Nds == null)
                    {
                        if (Subject.Contains("cancellation"))
                        {
                            File.Move(file, System.Configuration.ConfigurationSettings.AppSettings["Cancelled"] + "\\" + filename);
                            File.Move(file.Replace("htm", "txt"), System.Configuration.ConfigurationSettings.AppSettings["Cancelled"] + "\\" + filename.Replace("htm", "txt"));

                        }
                    };

                    if (Nds != null)
                    {
                        foreach (HtmlNode childNds in Nds)
                        {

                            if (childNds.ChildNodes.Count > 0)
                            {
                                if (childNds.InnerText.Contains("This is an order"))
                                {
                                    continue;

                                }
                                else
                                {
                                    if (childNds.ChildNodes.Count > 0)
                                    {

                                        foreach (HtmlNode childofChildNds in childNds.ChildNodes)
                                        {
                                            XmlElement OrderItemDetailsElement = xmlDoc.CreateElement("OrderItemDetails");
                                            if (childofChildNds.InnerText.Trim() != "" && childofChildNds.InnerText.Contains("Client PriceCost") == false && childofChildNds.InnerText.Contains("Client \r\nPriceCost") == false && childofChildNds.InnerText.Trim() != "campaigntrack.com.auhelpdesk")
                                            {
                                                string str = childofChildNds.InnerText;
                                                str = str.Replace("$", "|");

                                                String[] SplitValue = Splits(str, new char[] { '|' });
                                                string str1 = SplitValue[0].ToString().Trim();
                                                string str2 = SplitValue[1].ToString().Trim();
                                                string str3 = SplitValue[2].ToString().Trim();
                                                //MessageBox.Show(str1 + ' ' + str2 + ' ' + str3);

                                                //for (int i = 1; i < SplitValue.Length; i++)
                                                //{
                                                //    if (i != 4 && i != 10 && i != 16) { continue; }
                                                //    if (str1 == "   " || str2 == "   " || str3 == "   ") { continue; }
                                                //    string str = SplitValue[i];
                                                //    XmlElement IdElement = xmlDoc.CreateElement("n");
                                                //    //cnt = cnt + 1;
                                                //    IdElement.InnerText = cnt.ToString() + "_" + str1 + "|" + str2 + "|" + str3;
                                                //    OrderItemDetailsElement.AppendChild(IdElement);
                                                //}
                                                if (str1 != "" || str2 != "" || str3 != "")
                                                {
                                                    XmlElement IdElement = xmlDoc.CreateElement("n");
                                                    IdElement.InnerText = cnt.ToString() + "_" + str1 + "|" + str2 + "|" + str3;
                                                    OrderItemDetailsElement.AppendChild(IdElement);
                                                    rootElement.AppendChild(OrderItemDetailsElement);
                                                }

                                                //dsProductNotification = ProductEmailNotification(str1);
                                                //if (dsProductNotification.Tables[0].Rows.Count > 0)
                                                //{

                                                //    //(String subject,String Message,string To,string CC, bool hasattachment)
                                                //    //   eml.SendMail("", "", dsProductNotification.Tables[0].Rows[0]["EmailTo"].ToString(), dsProductNotification.Tables[0].Rows[0]["EmailCC"].ToString(), false);

                                                //}
                                            }

                                        }
                                        { cnt = cnt + 1; }
                                    }

                                }

                            }
                        }
                    }
                    strd = xmlDoc.InnerXml.ToString();
                    strd = strd.Replace("&amp;", "and").Replace("andamp;", " and ");
                    strd = strd.Replace("'", "''");
                    DataSet ds = new DataSet();
                    strd = strd.Replace("\r\n",string.Empty);
                    strd = strd.Replace(";", string.Empty);
                    ds = ExecuteProcess(strd);
                    xmlDoc.RemoveAll();
                    if (propertyId != 0 && !string.IsNullOrEmpty(location))
                    {
                        ProprtyCoordinates(propertyId, location);
                    }
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        for (int j = 0; j < ds.Tables[1].Rows.Count; j++)
                        {
                            dsProductNotification = ProductSchedule((int)ds.Tables[1].Rows[j]["Xero_Id"]);

                            if (dsProductNotification.Tables[0].Rows.Count > 0)
                            {
                                string productGroupName = string.Empty;
                                string productGroupId = string.Empty;
                                try
                                {
                                    if (dsProductNotification.Tables[0].Rows[dsProductNotification.Tables[0].Rows.Count - 1]["ProductGroupId"] != null)
                                    {
                                        productGroupId = dsProductNotification.Tables[0].Rows[dsProductNotification.Tables[0].Rows.Count - 1]["ProductGroupId"].ToString();
                                    }
                                    if (dsProductNotification.Tables[0].Rows[dsProductNotification.Tables[0].Rows.Count - 1]["ProductGroupName"] != null)
                                    {
                                        productGroupName = dsProductNotification.Tables[0].Rows[dsProductNotification.Tables[0].Rows.Count - 1]["ProductGroupName"].ToString();
                                    }
                                }
                                catch
                                {
                                    productGroupId = string.Empty;
                                    productGroupName = string.Empty;
                                }

                                //(String subject,String Message,string To,string CC, bool hasattachment)
                                //   eml.SendMail("", "", dsProductNotification.Tables[0].Rows[0]["EmailTo"].ToString(), dsProductNotification.Tables[0].Rows[0]["EmailCC"].ToString(), false);

                                if (dsProductNotification.Tables[0].Rows[dsProductNotification.Tables[0].Rows.Count - 1]["Value"].ToString().Contains("@"))
                                {
                                    // eml.SendMail(Subject, htmlDoc.DocumentNode.OuterHtml, dsProductNotification.Tables[0].Rows[0]["EmailTo"].ToString(), "", false);
                                    eml.SendMail(Subject, htmlDoc.DocumentNode.OuterHtml, "*****@*****.**", "", false);

                                }
                                else
                                {
                                    DataSet dsRecordtoProcess = new DataSet();
                                    DataTable dtRecordtoProcess = new DataTable();
                                    dsRecordtoProcess = ReturnDataforCalenderEntry(ds.Tables[1].Rows[j]["OrderId"].ToString());
                                    dtRecordtoProcess = dsRecordtoProcess.Tables[0];
                                    CampaignTrack_MailScarapper.GoogleService.IGoogleNotificationService client = (CampaignTrack_MailScarapper.GoogleService.IGoogleNotificationService)new CampaignTrack_MailScarapper.GoogleService.GoogleNotificationServiceClient();

                                    //GoogleCalSvc s = new GoogleCalSvc();
                                    if (dtRecordtoProcess.Rows.Count > 0)
                                    {
                                        for (int i = 0; i < dtRecordtoProcess.Rows.Count; i++)
                                        {
                                            //s.CreateEvent(dtRecordtoProcess.Rows[i]["Title"].ToString(), dtRecordtoProcess.Rows[i]["Location"].ToString(), dtRecordtoProcess.Rows[i]["SalesContact"].ToString(), dtRecordtoProcess.Rows[i]["Startdate"].ToString(), dtRecordtoProcess.Rows[i]["Enddate"].ToString(), dtRecordtoProcess.Rows[i]["Comments"].ToString(), dtRecordtoProcess.Rows[i]["ProductDescription"].ToString(), dtRecordtoProcess.Rows[i]["OrderId"].ToString(), dtRecordtoProcess.Rows[i]["RequiredDate"].ToString(), dtRecordtoProcess.Rows[i]["ColorId"].ToString());
                                            string orderItemDetails = string.Empty;
                                            if (!string.IsNullOrEmpty(productGroupId))
                                            {
                                                orderItemDetails = "Order Item (Please do not delete or update Order Item Id) :" + dtRecordtoProcess.Rows[i]["OrderId"].ToString() + ", " + productGroupId + "-" + productGroupName;
                                            }
                                            else
                                            {
                                                orderItemDetails = "Order Item (Please do not delete or update Order Item Id) :" + dtRecordtoProcess.Rows[i]["OrderId"].ToString();
                                            }
                                            //string description = "SalesContact : " + dtRecordtoProcess.Rows[i]["SalesContact"].ToString() + Environment.NewLine + Environment.NewLine + "Required On :" + Convert.ToDateTime(dtRecordtoProcess.Rows[i]["RequiredDate"].ToString()).ToShortDateString() + Environment.NewLine + Environment.NewLine + "Product Description :" + dtRecordtoProcess.Rows[i]["ProductDescription"].ToString() + Environment.NewLine + Environment.NewLine + "Supplier Instructions :" + dtRecordtoProcess.Rows[i]["Comments"].ToString().Replace("Supplier Instructions", "") + Environment.NewLine + Environment.NewLine + "Order Item (Please do not delete or update Order Item Id) :" + dtRecordtoProcess.Rows[i]["OrderId"].ToString() + ", " + productGroupId + "-" + productGroupName;
                                            string description = "SalesContact : " + dtRecordtoProcess.Rows[i]["SalesContact"].ToString() + Environment.NewLine + Environment.NewLine + "Required On :" + Convert.ToDateTime(dtRecordtoProcess.Rows[i]["RequiredDate"].ToString()).ToShortDateString() + Environment.NewLine + Environment.NewLine + "Product Description :" + dtRecordtoProcess.Rows[i]["ProductDescription"].ToString() + Environment.NewLine + Environment.NewLine + "Supplier Instructions :" + dtRecordtoProcess.Rows[i]["Comments"].ToString().Replace("Supplier Instructions", "") + Environment.NewLine + Environment.NewLine + orderItemDetails;
                                            //client.CreateEvent(dtRecordtoProcess.Rows[i]["Title"].ToString(), dtRecordtoProcess.Rows[i]["Location"].ToString(), dtRecordtoProcess.Rows[i]["SalesContact"].ToString(), Convert.ToDateTime(dtRecordtoProcess.Rows[i]["Startdate"].ToString()), Convert.ToDateTime(dtRecordtoProcess.Rows[i]["Enddate"].ToString()), dtRecordtoProcess.Rows[i]["Comments"].ToString(), dtRecordtoProcess.Rows[i]["ProductDescription"].ToString(), dtRecordtoProcess.Rows[i]["OrderId"].ToString(), dtRecordtoProcess.Rows[i]["RequiredDate"].ToString(), dtRecordtoProcess.Rows[i]["ColorId"].ToString(), "*****@*****.**", description, string.Empty, false);
                                            //  if (s.CheckedCalendarEvent == 0) { s.CheckedCalendarEvent = 1; }
                                            //UpdateOrderEvent((int)ds.Tables[1].Rows[j]["row_id1"]);//OrderId
                                            //  s.A1CreateEvent("*****@*****.**", "abc", "05-12-2013", "06-12-2013", "Test", "def", "ghi");
                                        }
                                    }
                                }
                            }
                            UpdateOrderEvent((int)ds.Tables[1].Rows[j]["row_id1"]);//OrderId
                        }

                        Invoice invoice = new Invoice();
                        invoice.Type = "ACCREC";
                        invoice.Contact = new Contact { Name = ds.Tables[0].Rows[0]["XeroName"].ToString() };
                        invoice.Date = DateTime.Today;
                        invoice.DueDate = DateTime.Today.AddDays(30);
                        invoice.Status = "DRAFT";
                        invoice.TotalTax = 0;
                        invoice.HasAttachments = true;
                        invoice.LineAmountTypes = XeroApi.Model.LineAmountType.Inclusive;
                        invoice.Reference = ds.Tables[0].Rows[0]["Property"].ToString();
                        LineItems lineitems = new LineItems();
                        invoice.LineItems = new XeroApi.Model.LineItems();
                        for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                        {
                            if (ds.Tables[0].Rows[j]["CreateInvoice"].ToString() == "True")
                            {
                                ds.Tables[1].DefaultView.RowFilter = "OrderId='" + ds.Tables[0].Rows[j]["OrderId"].ToString() + "'";
                                for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
                                {

                                    LineItem lineItem = new LineItem();
                                    lineItem.ItemCode = ds.Tables[1].DefaultView[i]["XeroCode"].ToString();
                                    lineItem.Description = ds.Tables[1].DefaultView[i]["XeroItemDescription"].ToString();
                                    lineItem.Quantity = 1;
                                    lineItem.UnitAmount = Convert.ToDecimal(ds.Tables[1].DefaultView[i]["Cost1"]);
                                    lineItem.TaxType = ds.Tables[1].DefaultView[i]["SalesTaxType"].ToString().Replace("GST on Income", "OUTPUT");
                                    lineItem.AccountCode = ds.Tables[1].DefaultView[i]["SalesAccountCode"].ToString();
                                    invoice.LineItems.Add(lineItem);
                                }

                            }

                        }

                        var inv = repository.Create<XeroApi.Model.Invoice>(invoice);
                        if (invoice.ValidationStatus == ValidationStatus.ERROR)
                        {
                            foreach (var message in invoice.ValidationErrors)
                            {
                            }
                        }
                        try
                        {
                            Guid invoiceId = inv.InvoiceID;
                            string invoiceNo = inv.InvoiceNumber;
                            // System.Threading.Thread.Sleep(5000);
                            string AnyAttachmentFilename = FullPath + "\\" + jpgfilename;
                            var SalesInvoice = repository.Invoices.FirstOrDefault(it => it.InvoiceID == invoiceId);
                            var newAttachment = repository.Attachments.Create(SalesInvoice, new FileInfo(AnyAttachmentFilename));
                            InsertPropertyInvoice((int)ds.Tables[1].Rows[0]["Property_Id"], invoiceNo);
                            ds.Tables[1].DefaultView.RowFilter = string.Empty;
                            System.Threading.Thread.Sleep(5000);
                        }
                        catch (Exception ex)
                        {
                            strLog = ex.StackTrace.ToString() + "~~~~~~~~~~~~Error~~~~~~~~~~~:" + ex.Message.ToString();
                            WriteLog(strLog + "For Filename :" + filename);
                            File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["Error"] + filename);
                            filename = filename.Replace("htm", "txt");
                            File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["Error"] + filename);
                        }
                        System.Threading.Thread.Sleep(5000);
                        System.IO.File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["Archive"] + filename);
                        //System.IO.File.Delete(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + "\\" + filename);
                        filename = filename.Replace("htm", "txt");
                        //if (System.IO.File.Exists(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + "\\" + filename))
                        //{ System.IO.File.Delete(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + "\\" + filename); }
                        //filename = filename.Replace("txt", "jpg");
                        //System.IO.File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + "\\" + filename, System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + "\\Archive\\" + filename);

                    }
                    else
                    {
                        eml.SendMail("No Product Match..", "The file name is " + filename, "*****@*****.**", "", false);
                        File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["NoMatch"] + filename);
                        filename = filename.Replace("htm", "txt");
                        File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["NoMatch"] + filename);

                    };

                }
            }
            catch (Exception ex)
            {
                strLog = ex.StackTrace.ToString() + "~~~~~~~~~~~~Error~~~~~~~~~~~:" + ex.Message.ToString();
                //if (strLog.Contains("at Google.Apis.Requests.ClientServiceRequest") == false)
                //{
                    eml.SendMail("Error in parsing file..", "The file name is " + filename + ". Error :- " + strLog, "*****@*****.**", "", false);
                    WriteLog(strLog + "For Filename :" + filename);
                    File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["Error"] + filename);
                    filename = filename.Replace("htm", "txt");
                    File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["Error"] + filename);
                //}
            }

            return strLog;
        }
Example #16
0
        public void SetTagToEntity(EntityType entityType, int entityID, String[] tags)
        {
            using (var db = GetDb())
            using (var tx = db.BeginTransaction())
            {
                db.ExecuteNonQuery(new SqlDelete("crm_entity_tag")
                                                      .Where(Exp.Eq("entity_id", entityID) & Exp.Eq("entity_type", (int)entityType)));

                foreach (var tagName in tags.Where(t => !string.IsNullOrWhiteSpace(t)))
                {
                    AddTagToEntity(entityType, entityID, tagName, db);
                }
                tx.Commit();
            }
        }
        public ActionResult render_line(int symposium_id)
        {
            if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == true)
            {
                int[] int_arry = new int[4] { 1, 7, 7000, 10000 };

                Symposium found_symposium = db.Symposiums.Find(symposium_id);
                int vote_count = 0;
                foreach (var item in found_symposium.Projects)
                {
                    vote_count = vote_count + item.Votes.Count();

                }
                Vote[] found_symposium_votes = new Vote[vote_count];
                int q = 0;
                foreach (var item in found_symposium.Projects)
                {
                    foreach (var vote in item.Votes)
                    {
                        found_symposium_votes[q] = vote;
                        q++;
                    }
                }
                var all_votes = found_symposium_votes.OrderBy(v => v.created_at).ToList();
                DateTime[] times = new DateTime[all_votes.Count()];
                int i = 0;
                foreach (var timestamp in all_votes)
                {

                    times[i] = Convert.ToDateTime(timestamp.created_at);
                    i++;

                }
                ViewBag.Votes = all_votes;
                Symposium symposium = db.Symposiums.Find(symposium_id);
                var array = times.GroupBy(y => (int)(y.Ticks / TimeSpan.TicksPerMinute / 10)).Select(g => new { Value = g.Key, Count = g.Count() }).OrderBy(x => x.Value);
                if (array.FirstOrDefault() != null && array.Count() > 1)
                {
                    String[] x_axis = new String[times.Count()];
                    int iterator = 0;
                    foreach (var item in array)
                    {
                        long new_tick = convert_interval(item.Value);
                        DateTime myDate = new DateTime(new_tick);
                        int minutes = myDate.Minute;
                        String vote_date = myDate.ToString("hh:mm" + "-" + (minutes + 10));
                        x_axis[iterator] = vote_date;
                        iterator++;
                    }
                    DateTime am_or_pm;
                    if (array.FirstOrDefault() != null)
                    {
                        am_or_pm = new DateTime(convert_interval(array.First().Value));
                        string tt = am_or_pm.ToString("tt");
                        ViewBag.Morning_or_Evening = tt;
                    }

                    int[] counts = new int[array.Count()];
                    int r = 0;
                    foreach (var item in array)
                    {
                        counts[r] = item.Count;
                        r++;
                    }
                    ViewBag.Counts = counts;
                    var vote_intervals = x_axis.Where(x => !string.IsNullOrEmpty(x)).ToArray();
                    ViewBag.line_x_axis = vote_intervals;
                    return View(symposium);
                }
                else
                {
                    return RedirectToAction("no_information", "Reports");
                }
            }
            else
            {
                return RedirectToAction("desktop_vote", "Projects");
            }
        }
Example #18
0
        public static Extract IsBlockaPE(byte[] block)
        {
            Extract extracted_struct = new Extract();

            if (BitConverter.ToInt16(block, 0) != 0x5A4D)
                return null;

            var headerOffset = BitConverter.ToInt32(block, 0x3C);

            if (headerOffset > 3000)
            {
                // bad probably
                return null;
            }

            if (BitConverter.ToInt32(block, headerOffset) != 0x00004550)
                return null;

            var pos = headerOffset + 6;

            extracted_struct.NumberOfSections = BitConverter.ToInt16(block, pos); pos += 2;
            extracted_struct.SectionPosOffsets = new List<MiniSection>();
            //pos += 2;

            extracted_struct.TimeStamp = BitConverter.ToUInt32(block, pos); pos += 4;
            pos += 8;
            extracted_struct.secOff = BitConverter.ToUInt16(block, pos); pos += 2;
            pos += 2;
            var magic = BitConverter.ToUInt16(block, pos); pos += 2;
            extracted_struct.Is64 = magic == 0x20b;

            if (extracted_struct.Is64)
            {
                pos += 22;
                extracted_struct.ImageBaseOffset = pos;
                extracted_struct.ImageBase = BitConverter.ToUInt64(block, pos); pos += 8;
            }
            else
            {
                pos += 26;
                extracted_struct.ImageBaseOffset = pos;
                extracted_struct.ImageBase = BitConverter.ToUInt32(block, pos); pos += 4;
            }
            extracted_struct.SectionAlignment = BitConverter.ToUInt32(block, pos); pos += 4;
            extracted_struct.FileAlignment = BitConverter.ToUInt32(block, pos); pos += 4;

            pos += 16;

            extracted_struct.SizeOfImage = BitConverter.ToUInt32(block, pos); pos += 4;
            extracted_struct.SizeOfHeaders = BitConverter.ToUInt32(block, pos); pos += 4;
            // checksum
            pos += 4;
            // subsys/characteristics
            pos += 4;
            // SizeOf/Stack/Heap/Reserve/Commit
            if (extracted_struct.Is64)
                pos += 32;
            else
                pos += 16;
            // LoaderFlags
            pos += 4;
            // NumberOfRvaAndSizes
            pos += 4;
            // 16 DataDirectory entries, each is 8 bytes 4byte VA, 4byte Size
            // we care about #6 since it's where we will find the GUID
            pos += 6 * 8;
            extracted_struct.DebugDirPos = BitConverter.ToUInt32(block, pos); pos += 4;
            extracted_struct.DebugDirSize = BitConverter.ToUInt32(block, pos); pos += 4;


            var CurrEnd = extracted_struct.SizeOfHeaders;
            /// implicit section for header
            extracted_struct.SectionPosOffsets.Add(new MiniSection { VirtualSize = 0x1000, RawFileSize = 0x400, RawFilePointer = 0, VirtualOffset = 0, Name = "PEHeader" });

            // get to sections
            pos = headerOffset + (extracted_struct.Is64 ? 0x108 : 0xF8);
            for (int i = 0; i < extracted_struct.NumberOfSections; i++)
            {
                /*var rawStr = BitConverter.ToString(block, pos, 8); */
                var rawStr = new String(
                    new char[8] { (char) block[pos], (char) block[pos + 1], (char) block[pos + 2], (char) block[pos + 3],
                    (char) block[pos + 4], (char) block[pos + 5], (char) block[pos + 6], (char) block[pos + 7] }); pos += 8;

                var secStr = new string(rawStr.Where(c => char.IsLetterOrDigit(c) || char.IsPunctuation(c)).ToArray());

                var Size = BitConverter.ToUInt32(block, pos); pos += 4;
                var Pos = BitConverter.ToUInt32(block, pos); pos += 4;
                var rawSize = BitConverter.ToUInt32(block, pos); pos += 4;
                var rawPos = BitConverter.ToUInt32(block, pos); pos += 4;

                var currSecNfo = new MiniSection { VirtualSize = Size, VirtualOffset = Pos, RawFileSize = rawSize, RawFilePointer = rawPos, Name = secStr };
                extracted_struct.SectionPosOffsets.Add(currSecNfo);

                if (Verbose > 2)
                    Write($" section [{secStr}] ");

                if (secStr.StartsWith(@".reloc", StringComparison.Ordinal))
                {
                    extracted_struct.RelocSize = Size;
                    extracted_struct.RelocPos = Pos;
                }

                pos += 0x10;
            }

            return extracted_struct;
        }
Example #19
0
        public string GetAlphaNumericOnly(String input)
        {
            char[] filteredInputArray = input.Where(char.IsLetterOrDigit).ToArray();

            return new string(filteredInputArray);
        }
Example #20
0
        public dateVal values; // dateTime, measureName, 0=Mean [1 = Min, 2 = Max]

        #endregion Fields

        #region Constructors

        public inverter(String company, String name, String model, String serialNo, long power = 0, invType type = invType.INVERTER,
            int nbMeasures=30, int nbStrings=20, String sensorSN=null)
        {
            this.name = name;
            this.model = model;
            this.serialNo =serialNo;
            this.type = type;
            this.measureName = new Dictionary<string,List<int>>();
            if (power == 0)
            {
                string output = new string(model.Where(c => char.IsDigit(c)).ToArray());
                power = int.Parse(output);
            }
            this.company = company;
            this.nbMeasures = nbMeasures;
            this.nbStrings = nbStrings;
            this.sensorSN = sensorSN;
        }
		public void WriteProperty(IndentStreamWriter writer)
		{
			this.WriteDocument(writer);
			var declare = new String[]
			{
				this.propertyAccess,
				this.propertyStatic,
				this.propertyType, 
				this.propertyName,
			};
			var declareLine = String.Join(" ", declare.Where(w => w != PropertyReader.Missed));

			writer.WriteLineIndent(declareLine);
			using (new BraceWriter(writer))
			{
				if (this.propertyGettable)
				{
					writer.WriteIndent(String.Empty);
					if (!String.IsNullOrWhiteSpace(this.propertyGetAccess))
					{
						writer.Write("{0} ", this.propertyGetAccess);
					}
					writer.WriteLine("get");
					using (new BraceWriter(writer))
					{
						writer.WriteLineIndent(this.GetterTemplate, this.propertyCode);
					}
				}
				if (this.propertySettable)
				{
					writer.WriteIndent(String.Empty);
					if (!String.IsNullOrWhiteSpace(this.propertySetAccess))
					{
						writer.Write("{0} ", this.propertySetAccess);
					}
					writer.WriteLine("set");
					using (new BraceWriter(writer))
					{
						writer.WriteLineIndent(this.SetterTemplate, this.propertyCode);
					}
				}
			}
			writer.WriteLine();
		}
Example #22
0
 private static String[] GetCommandArgs(String[] args)
 {
     return args.Where(arg => arg.StartsWith("--"))
                .Select(arg => arg.Replace("--", String.Empty))
                .ToArray();
 }
 public static long SumDigits(String s)
 {
     // return the sum of the digits 0-9 that appear in the string, ignoring all other characters
     // e.g. "123" return 6
     short result;
     return s.Where(c => Int16.TryParse(c.ToString(), out result)).Sum(num => Int16.Parse(num.ToString()));
 }
Example #24
0
        public static bool ParseAsInstruction(SmaliLine rv, String sInst, ref String[] sWords, ref String sRawText)
        {
            switch (sInst)
            {
                case "const":
                    rv.Smali = LineSmali.Const;
                    sWords[1] = sWords[1].Replace(",", "");
                    rv.lRegisters[sWords[1]] = String.Empty;
                    rv.aValue = sWords[2];
                    break;
                case "const/16":
                    rv.Smali = LineSmali.Const16;
                    sWords[1] = sWords[1].Replace(",", "");
                    rv.lRegisters[sWords[1]] = String.Empty;
                    rv.aValue = sWords[2];
                    break;
                case "const/high16":
                    rv.Smali = LineSmali.ConstHigh16;
                    sWords[1] = sWords[1].Replace(",", "");
                    rv.lRegisters[sWords[1]] = String.Empty;
                    rv.aValue = sWords[2];
                    break;
                case "const/4":
                    rv.Smali = LineSmali.Const4;
                    sWords[1] = sWords[1].Replace(",", "");
                    rv.lRegisters[sWords[1]] = String.Empty;
                    rv.aValue = sWords[2];
                    break;
                case "const-string":
                    rv.Smali = LineSmali.ConstString;
                    sWords[1] = sWords[1].Replace(",", "");
                    rv.lRegisters[sWords[1]] = String.Empty;
                    rv.aValue = sRawText;
                    break;
                case "invoke-static":
                    rv.Smali = LineSmali.InvokeStatic;
                    rv.aName = sWords[sWords.Length - 1];
                    sWords[sWords.Length - 1] = String.Empty;
                    String sp = String.Join(" ", sWords.Where(x => !String.IsNullOrEmpty(x)).ToArray()).Trim();
                    if (sp.EndsWith(","))
                        sp = sp.Substring(0, sp.Length - 1);
                    ParseParameters(rv, sp);
                    rv.lRegisters[rv.lRegisters.Keys.First()] = rv.aName;
                    break;
                case "invoke-direct":
                    rv.Smali = LineSmali.InvokeDirect;
                    if (sWords[1].EndsWith(","))
                        sWords[1] = sWords[1].Substring(0, sWords[1].Length - 1);
                    ParseParameters(rv, sWords[1]);
                    rv.lRegisters[rv.lRegisters.Keys.First()] = sWords[2];
                    rv.aName = sWords[sWords.Length - 1];
                    break;
                case "move-result-object":
                    rv.Smali = LineSmali.MoveResultObject;
                    rv.lRegisters[sWords[1]] = String.Empty;
                    break;
                case "move-result":
                    rv.Smali = LineSmali.MoveResult;
                    rv.lRegisters[sWords[1]] = String.Empty;
                    break;
                case "return":
                case "return-object":
                    rv.Smali = LineSmali.Return;
                    if (sWords[1].EndsWith(","))
                        sWords[1] = sWords[1].Substring(0, sWords[1].Length - 1);
                    ParseParameters(rv, sWords[1]);
                    rv.lRegisters[rv.lRegisters.Keys.First()] = sWords[1];
                    break;
                case "return-void":
                    rv.Smali = LineSmali.ReturnVoid;
                    break;
                case "sget-object":
                    rv.Smali = LineSmali.SgetObject;
                    if (sWords[1].EndsWith(","))
                        sWords[1] = sWords[1].Substring(0, sWords[1].Length - 1);
                    ParseParameters(rv, sWords[1]);
                    rv.lRegisters[rv.lRegisters.Keys.First()] = sWords[2];
                    break;
                case "sput-object":
                    rv.Smali = LineSmali.SputObject;
                    if (sWords[1].EndsWith(","))
                        sWords[1] = sWords[1].Substring(0, sWords[1].Length - 1);
                    ParseParameters(rv, sWords[1]);
                    rv.lRegisters[rv.lRegisters.Keys.First()] = sWords[2];
                    break;
                case "new-instance":
                    rv.Smali = LineSmali.NewInstance;
                    if (sWords[1].EndsWith(","))
                        sWords[1] = sWords[1].Substring(0, sWords[1].Length - 1);
                    ParseParameters(rv, sWords[1]);
                    rv.lRegisters[rv.lRegisters.Keys.First()] = sWords[2];
                    break;
                case "iput-object":
                    rv.Smali = LineSmali.IputObject;
                    rv.aValue = sWords[sWords.Length - 1];
                    sWords[sWords.Length - 1] = String.Empty;
                    sp = String.Join(" ", sWords.Where(x => !String.IsNullOrEmpty(x)).ToArray()).Trim();
                    if (sp.EndsWith(","))
                        sp = sp.Substring(0, sp.Length - 1);
                    ParseParameters(rv, sp);
                    break;
                case "iput-boolean":
                    rv.Smali = LineSmali.IputBoolean;
                    if (sWords[1].EndsWith(","))
                        sWords[1] = sWords[1].Substring(0, sWords[1].Length - 1);
                    ParseParameters(rv, sWords[1]);
                    rv.lRegisters[rv.lRegisters.Keys.First()] = sWords[2];
                    rv.aName = sWords[ sWords.Length - 1]; //Always the last entry.
                    break;
                case "invoke-virtual":
                    rv.Smali = LineSmali.InvokeVirtual;
                    rv.aName = sWords[sWords.Length - 1];
                    sWords[sWords.Length - 1] = String.Empty;
                    sp = String.Join(" ", sWords.Where(x => !String.IsNullOrEmpty(x)).ToArray()).Trim();
                    if (sp.EndsWith(","))
                        sp = sp.Substring(0, sp.Length - 1);
                    ParseParameters(rv, sp);
                    rv.lRegisters[rv.lRegisters.Keys.First()] = rv.aName;
                    break;

                #region Unimplemented Functions

                case "add-double":
                case "add-double/2addr":
                case "add-float":
                case "add-float/2addr":
                case "add-int":
                case "add-int/2addr":
                case "add-int/lit16":
                case "add-int/lit8":
                case "add-long":
                case "add-long/2addr":
                case "aget":
                case "aget-boolean":
                case "aget-byte":
                case "aget-char":
                case "aget-object":
                case "aget-short":
                case "aget-wide":
                case "and-int":
                case "and-int/2addr":
                case "and-int/lit16":
                case "and-int/lit8":
                case "and-long":
                case "and-long/2addr":
                case "aput":
                case "aput-boolean":
                case "aput-byte":
                case "aput-char":
                case "aput-object":
                case "aput-short":
                case "aput-wide":
                case "array-length":
                case "check-cast":
                case "cmpg-double":
                case "cmpg-float":
                case "cmpl-double":
                case "cmpl-float":
                case "cmp-long":
                case "const-class":
                case "const-string/jumbo":
                case "const-wide":
                case "const-wide/16":
                case "const-wide/32":
                case "const-wide/high16":
                case "div-double":
                case "div-float":
                case "div-float/2addr":
                case "div-int":
                case "div-int/2addr":
                case "div-int/lit16":
                case "div-int/lit8":
                case "div-long":
                case "div-long/2addr":
                case "double-to-int":
                case "double-to-long":
                case "execute-inline":
                case "execute-inline/range":
                case "fill-array-data":
                case "filled-new-array":
                case "filled-new-array/range":
                case "float-to-double":
                case "float-to-int":
                case "float-to-long":
                case "iget":
                case "iget-boolean":
                case "iget-byte":
                case "iget-char":
                case "iget-object":
                case "iget-object-quick":
                case "iget-object-volatile":
                case "iget-quick":
                case "iget-short":
                case "iget-volatile":
                case "iget-wide":
                case "iget-wide-quick":
                case "iget-wide-volatile":
                case "instance-of":
                case "int-to-double":
                case "int-to-float":
                case "int-to-long":
                case "invoke-direct/range":
                case "invoke-direct-empty":
                case "invoke-interface":
                case "invoke-interface/range":
                case "invoke-object-init/range":
                case "invoke-static/range":
                case "invoke-super":
                case "invoke-super/range":
                case "invoke-super-quick":
                case "invoke-super-quick/range":
                case "invoke-virtual/range":
                case "invoke-virtual-quick":
                case "invoke-virtual-quick/range":
                case "iput":
                case "iput-byte":
                case "iput-char":
                case "iput-object-quick":
                case "iput-object-volatile":
                case "iput-quick":
                case "iput-short":
                case "iput-volatile":
                case "iput-wide":
                case "iput-wide-quick":
                case "iput-wide-volatile":
                case "long-to-double":
                case "long-to-float":
                case "long-to-int":
                case "move":
                case "move/16":
                case "move/from16":
                case "move-exception":
                case "move-object":
                case "move-object/16":
                case "move-object/from16":
                case "move-result-wide":
                case "move-wide":
                case "move-wide/16":
                case "move-wide/from16":
                case "mul-double":
                case "mul-float":
                case "mul-float/2addr":
                case "mul-int":
                case "mul-int/2addr":
                case "mul-int/lit16":
                case "mul-int/lit8":
                case "mul-long":
                case "mul-long/2addr":
                case "neg-double":
                case "neg-float":
                case "neg-int":
                case "neg-long":
                case "new-array":
                case "nop":
                case "not-int":
                case "not-long":
                case "or-int":
                case "or-int/2addr":
                case "or-int/lit16":
                case "or-long":
                case "or-long/2addr":
                case "packed-switch":
                case "rem-float":
                case "rem-float/2addr":
                case "rem-int":
                case "rem-int/2addr":
                case "rem-int/lit16":
                case "rem-int/lit8":
                case "rem-long":
                case "rem-long/2addr":
                case "return-void-barrier":
                case "return-wide":
                case "rsub-int":
                case "rsub-int/lit8":
                case "sget":
                case "sget-boolean":
                case "sget-byte":
                case "sget-char":
                case "sget-object-volatile":
                case "sget-short":
                case "sget-volatile":
                case "sget-wide":
                case "sget-wide-volatile":
                case "shl-int":
                case "shl-int/2addr":
                case "shl-long":
                case "shl-long/2addr":
                case "shr-int":
                case "shr-int/2addr":
                case "shr-long":
                case "shr-long/2addr":
                case "sparse-switch":
                case "sput":
                case "sput-boolean":
                case "sput-byte":
                case "sput-char":
                case "sput-object-volatile":
                case "sput-short":
                case "sput-volatile":
                case "sput-wide":
                case "sput-wide-volatile":
                case "sub-double":
                case "sub-float":
                case "sub-float/2addr":
                case "sub-int":
                case "sub-int/2addr":
                case "sub-long":
                case "sub-long/2addr":
                case "throw-verification-error":
                case "ushr-int":
                case "ushr-int/2addr":
                case "ushr-long":
                case "ushr-long/2addr":
                case "xor-int":
                case "xor-int/2addr":
                case "xor-long":
                case "xor-long/2addr":
                    rv.Smali = LineSmali.Unimplemented;
                    rv.aName = sRawText;
                    break;
                case "goto":
                case "goto/16":
                case "goto/32":
                case "if-eq":
                case "if-eqz":
                case "if-ge":
                case "if-gez":
                case "if-gt":
                case "if-gtz":
                case "if-le":
                case "if-lez":
                case "if-lt":
                case "if-ltz":
                case "if-ne":
                case "if-nez":
                    rv.Smali = LineSmali.Conditional;
                    rv.aName = sRawText;
                    break;
                default:
                    rv.Smali = LineSmali.Unknown;
                    rv.aName = sRawText;
                    break;
                #endregion
            }
            return true;
        }
Example #25
0
        /// <summary>
        /// Generates array of connected rooms based on current location
        /// </summary>
        /// <param name="location"> Current location represented as a decimal (chamberNumber.roomNumber) </param> 
        /// <returns></returns>
        public Room[] loadCaveandRoom(double location)
        {
            String[] mapInfo = File.ReadAllLines(address);

            int chamberNumber = (int) location;
            int roomNumber = (int)(((location - chamberNumber) * 10.0) + 0.5);

            Room[] myRooms = new Room[9];

            for (int i = 0; i < myRooms.Length; i++)
            {
                myRooms[i] = null;
            }

            String temp1; String[] temp2 = new String[2];
            for (int i = 0; i < mapInfo.Length; i++)
            {
                temp1 = mapInfo[i];
                temp2 = temp1.Split(' ', '\t');
                temp2 = temp2.Where(s => !string.IsNullOrEmpty(s)).ToArray();

                if (Convert.ToDouble(temp2[0]) == location)
                    break;
            }

            if (chamberNumber < 8)
            {
                NUMB_OF_ROOMS = 4;
                for (int i = 1; i < 1 + NUMB_OF_ROOMS; i++)
                {
                    myRooms[i] = new Room(0, 0);
                }

                if (roomNumber == 0)
                {
                    for (int i = 1; i < 1 + NUMB_OF_ROOMS; i++)
                    {
                        myRooms[i] = new Room(chamberNumber, i);
                    }
                }

                else
                {
                    switch (roomNumber)
                    {
                        case 1:
                            myRooms[2] = myRooms[4] = null;
                            myRooms[3].setRoomFromDecimal(chamberNumber);
                            break;
                        case 2:
                            myRooms[1] = myRooms[3] = null;
                            myRooms[4].setRoomFromDecimal(chamberNumber);
                            break;
                        case 3:
                            myRooms[2] = myRooms[4] = null;
                            myRooms[1].setRoomFromDecimal(chamberNumber);
                            break;
                        case 4:
                            myRooms[1] = myRooms[3] = null;
                            myRooms[2].setRoomFromDecimal(chamberNumber);
                            break;
                    }

                    myRooms[roomNumber].setRoomFromDecimal(Convert.ToDouble(temp2[1]));
                }
            }

            if (chamberNumber == 8)
            {
                NUMB_OF_ROOMS = 6;
                for (int i = 1; i < 1 + NUMB_OF_ROOMS; i++)
                {
                    myRooms[i] = new Room(0, 0);
                }

                if (roomNumber == 0)
                {
                    for (int i = 1; i < 1 + NUMB_OF_ROOMS; i++)
                    {
                        myRooms[i] = new Room(chamberNumber, i);
                    }
                }

                else
                {
                    switch (roomNumber)
                    {
                        case 1:
                        case 2:
                            myRooms[1].setRoomFromDecimal(Convert.ToDouble(temp2[1]));
                            myRooms[2] = myRooms[4] = null;
                            myRooms[3].setRoomFromDecimal(chamberNumber);
                            break;
                        case 3:
                            myRooms[2].setRoomFromDecimal(Convert.ToDouble(temp2[1]));
                            myRooms[1] = myRooms[3] = null;
                            myRooms[4].setRoomFromDecimal(chamberNumber);
                            break;
                        case 4:
                        case 5:
                            myRooms[3].setRoomFromDecimal(Convert.ToDouble(temp2[1]));
                            myRooms[2] = myRooms[4] = null;
                            myRooms[1].setRoomFromDecimal(chamberNumber);
                            break;
                        case 6:
                            myRooms[4].setRoomFromDecimal(Convert.ToDouble(temp2[1]));
                            myRooms[1] = myRooms[3] = null;
                            myRooms[2].setRoomFromDecimal(chamberNumber);
                            break;
                    }
                }
            }

            if (chamberNumber == 9 || chamberNumber == 10)
            {
                NUMB_OF_ROOMS = 8;
                for (int i = 1; i < 1 + NUMB_OF_ROOMS; i++)
                {
                    myRooms[i] = new Room(0, 0);
                }

                if (roomNumber == 0)
                {
                    for (int i = 1; i < 1 + NUMB_OF_ROOMS; i++)
                    {
                        myRooms[i] = new Room(chamberNumber, i);
                    }
                }

                else
                {
                    switch (roomNumber)
                    {
                        case 1:
                        case 2:
                        case 3:
                            myRooms[1].setRoomFromDecimal(Convert.ToDouble(temp2[1]));
                            myRooms[2] = myRooms[4] = null;
                            myRooms[3].setRoomFromDecimal(chamberNumber);
                            break;
                        case 4:
                            myRooms[2].setRoomFromDecimal(Convert.ToDouble(temp2[1]));
                            myRooms[1] = myRooms[3] = null;
                            myRooms[4].setRoomFromDecimal(chamberNumber);
                            break;
                        case 5:
                        case 6:
                        case 7:
                            myRooms[3].setRoomFromDecimal(Convert.ToDouble(temp2[1]));
                            myRooms[2] = myRooms[4] = null;
                            myRooms[1].setRoomFromDecimal(chamberNumber);
                            break;
                        case 8:
                            myRooms[4].setRoomFromDecimal(Convert.ToDouble(temp2[1]));
                            myRooms[1] = myRooms[3] = null;
                            myRooms[2].setRoomFromDecimal(chamberNumber);
                            break;
                    }
                }
            }

            return myRooms;
        }
Example #26
0
 /// <summary>
 /// Remove todos caracteres, deixando apenas números.
 /// </summary>
 /// <param name="Value">Valor com a máscara.</param>
 /// <returns>Retorna apanas números em uma String.</returns>
 public static String RemoveMask(String value)
 {
     return string.IsNullOrEmpty(value) ? string.Empty : new string(value.Where(char.IsLetterOrDigit).ToArray());
 }
Example #27
0
        public stringVal values; // dateVal, StringVal, ValueVal

        #endregion Fields

        #region Constructors

        public inverter(String company, String siteName, long sitePower, String serialNo, String otherName, long inverterPower, 
            String model, invType type = invType.INVERTER, String sensorSN = null, Boolean bInDBFlag = false)
        {
            this.company = company;
            this.siteName = siteName;
            this.sitePower = sitePower;
            this.serialNo = serialNo;
            this.otherName = otherName;
            this.inverterPower=inverterPower;
            this.model = model;
            this.type = type;
            this.sensorSN = sensorSN;
            this.bInDb = bInDBFlag;

            this.dataTP = new List<valueDTP>();
            this.measureInternalNameArray = new Dictionary<string, int>();     // internalNames
            if (inverterPower == 0)
            {
                string output = new string(model.Where(c => char.IsDigit(c)).ToArray());
                inverterPower = 0;
                long.TryParse(output, out inverterPower);
            }
            if (this.otherName.ToLower().Contains("webbox"))
                this.type = invType.WEBBOX;
            else
                if (this.otherName.ToLower().Contains("sensor"))
                    this.type = invType.SENSOR;
            this.values = new stringVal();
        }
        /// <summary>
        /// Does hmm comput to see if exercise was found or not
        /// </summary>
        /// <param name="exerciseToCheck"></param>
        /// <returns></returns>
        static Boolean exerciseFound(String exerciseToCheck)
        {
            if (!avgFramesPerLabel_Training.ContainsKey(exerciseToCheck)){
                log.Error("Invalid exercise name! " + exerciseToCheck + " not found in average frames per label dictionary");
                return false;
            }

            // only consider exercises if the number of frames are within a threshold
            double frameCount = observationSequences[0].Count();
            double avgFrameCountForExc = avgFramesPerLabel_Training[exerciseToCheck] ;
            double frameDifference = avgFrameCountForExc - frameCount;
            double frameDifferenceThreshold = Convert.ToInt32(avgFrameCountForExc * Constants.FRAME_THRESHOLD_PERCENT);

            if (Math.Abs(frameDifference) > frameDifferenceThreshold)
            {
                if (frameCount > avgFrameCountForExc)
                {
                    clearObservations();
                }
                return false;
            }
            if (debugging)
            {
                log.Debug("Frames DIfference is: " + frameDifference +
                    ", avg frames for exercise: " + exerciseToCheck + " is: " + avgFrameCountForExc +
                    ", Frames Threshold is " + frameDifferenceThreshold +
                    ", Frame Differ Count is: " + frameCount);
            }

            //prepare for hmm computations
            double[][][] inputs = new Double[numJoints][][];
            for (int i = 0; i < numJoints; i++)
            {
                inputs[i] = Sequence.Preprocess(observationSequences[i].ToArray());
            }

            //do hmm computation to find closest exercise match for each joint
            String[] outputLabels = new String[inputs.Length];
            String label;
            for (int i = 0; i < inputs.Length; i++)
            {
                int index = hmms[i].Compute(inputs[i]);
                label = (index >= 0) ? databases[i].Classes[index] : "NOT FOUND";
                outputLabels[i] = label;
            }

            //determine if exercise is done by analyzing evidence in each joint for the given exercise
            if (outputLabels.Any(x => x != "NOT FOUND"))
            {
                //return most occuring exercise label by considering labels for all the joints
                label = outputLabels.Where(x => x != "NOT FOUND").GroupBy(x => x).OrderByDescending(x => x.Count()).First().Key;
                int numLabels = outputLabels.Where(x => x == label).Count();

                if (numLabels < Constants.MIN_NUM_MATCHED_JOINTS)
                {
                    label = "NOT FOUND";
                }
            }
            else
            {
                label = "NOT FOUND";
            }

            if (label == exerciseToCheck)
            {
                return true;
            }
            return false;
        }