/// <summary>
        ///
        /// </summary>
        /// <param name="myString">String </param>
        /// <returns>The value in milliseconds</returns>
        public static Int32 ConvertStringToMilliseconds(String myString)
        {
            // Guard Block
            // String null
            // String ""
            // String "        "
            if (String.IsNullOrWhiteSpace(myString))
            {
                throw new ArgumentException("Value was null, empty, or not a recognized time format.");
            }

            // Try Parse in the hopes that they gave us a number without ANY suffix
            int num;
            bool res = int.TryParse(myString, out num);

            if (res)
            {
                // Log statement saying that we're good
            }
                // Hours suffix scenario - h
            else if (myString.EndsWith("h"))
            {
                myString = myString.TrimEnd(new char[] {'h'});
                bool x = int.TryParse(myString, out num);
                if (x)
                {
                    num = num * 3600000;
                }
                
            }
                // Minute suffix scenario - m
            else if (myString.EndsWith("m"))
            {
                myString = myString.TrimEnd(new char[] { 'm' });
                bool x = int.TryParse(myString, out num);
                if (x)
                {
                    num = num * 60000;
                }
            }
              // Second suffix scenario - s
            else if (myString.EndsWith("s"))
            {
                myString = myString.TrimEnd(new char[] { 's' });
                bool x = int.TryParse(myString, out num);
                if (x)
                {
                    num = num * 1000;
                }
            }
            else
            {
                throw new ArgumentException("Value is not a recognized time format.");
            }
            return num;
        }
Ejemplo n.º 2
0
 private XmlElement findAppDocOfModule(String pDir, String pIOCode) {
   XmlElement vRslt = null;
   String vAppCfgFN = pDir + "app.config";
   if(File.Exists(vAppCfgFN)) {
     XmlDocument vDoc = dom4cs.OpenDocument(vAppCfgFN).XmlDoc;
     XmlNodeList vMods = vDoc.DocumentElement.SelectNodes("load/module[not(@enabled) or (@enabled='true')]");
     foreach(XmlElement vMod in vMods) {
       //if((!vMod.HasAttribute("enabled") || String.Equals(vMod.GetAttribute("enabled"), "true", StringComparison.CurrentCultureIgnoreCase)) 
       //    && String.Equals(vMod.GetAttribute("iocode"), pIOCode, StringComparison.CurrentCultureIgnoreCase)) {
       if(String.Equals(vMod.GetAttribute("iocode"), pIOCode, StringComparison.CurrentCultureIgnoreCase)) {
         vRslt = vMod;
         break;
       }
     }
   }
   if((vRslt == null) && !String.IsNullOrEmpty(pDir)) {
     DirectoryInfo vCurDir = new DirectoryInfo(pDir);
     DirectoryInfo vPrntDir = Directory.GetParent(pDir.TrimEnd(new Char[]{'\\'}));
     if ((vPrntDir != null) && (vPrntDir.FullName.ToLower().StartsWith(this.BioSession.Cfg.LocalPath.ToLower()))) {
       String vNextIOCode = vCurDir.Name + "." + pIOCode;
       vRslt = this.findAppDocOfModule(vPrntDir.FullName + "\\", vNextIOCode);
     }
   }
   return vRslt;
 }
Ejemplo n.º 3
0
        public ActionResult GridViewPartialDelete(System.String BI)
        {
            var model  = db.Students;
            var model2 = db.Ispits;

            //skidaju se navodnici jer ih devexpress stavlja iz nekog razloga
            BI = BI.TrimStart(' ', '"');
            BI = BI.TrimEnd(' ', '"');
            if (BI != null)
            {
                try
                {
                    //var item = model.FirstOrDefault(it => it.BI == BI);
                    var item = model.Where(x => x.BI == BI).FirstOrDefault();
                    if (item != null)
                    {
                        model.Remove(item);
                        List <Ispit> listOfIspits = model2.Where(x => x.BI == BI).ToList();
                        //brisemo sve ispite tog studenta
                        foreach (Ispit ispit in listOfIspits)
                        {
                            model2.Remove(ispit);
                        }
                    }

                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    ViewData["EditError"] = e.Message;
                }
            }
            return(PartialView("_GridViewPartial", model.ToList()));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Convert from Common Data Format to DICOM format.
        /// </summary>
        /// <returns>DICOM format.</returns>
        public override System.String ToDicomFormat()
        {
            // format the name using all the components
            System.String nameComponents = _surname + "^" +
                                           _firstName + "^" +
                                           _middleName + "^" +
                                           _prefix + "^" +
                                           _suffix;

            // trim off any trailing component delimiters
            System.String dicomName = nameComponents.TrimEnd('^');

            // add the ideographic name representation
            if (_ideographicName != System.String.Empty)
            {
                dicomName += ("=" + _ideographicName);
            }

            // add the phonetic name representation
            if (_phoneticName != System.String.Empty)
            {
                if (_ideographicName == System.String.Empty)
                {
                    // add empty ideographic name
                    dicomName += "=";
                }
                dicomName += ("=" + _phoneticName);
            }

            return(dicomName);
        }
Ejemplo n.º 5
0
        public Dictionary<string, string> JsonToDictionary(String input, String firstCol)
        {
            //if(input.IndexOf("{"
            //input = input.Replace('\"','');
            /*
            input = input.Substring(input.IndexOf("{" + firstCol) + 1);
            input = input.Substring(0, input.IndexOf("}"));
            */
            /*
            while (input.IndexOf('\\') >= 0)
            {
                int index = input.IndexOf('\\');
                input = input.Substring(0, index) + input.Substring(index + 1);
            }
            */

            input = input.Substring(1);
            input = input.Substring(0,input.Length-1);

            while (input.IndexOf('\"') >= 0)
            {
                int index = input.IndexOf('\"');
                input = input.Substring(0, index) + input.Substring(index + 1);
            }
            /*
            input.Replace(':', '=');
            input.Replace(',', ';');
            */
            return input.TrimEnd(',').Split(',').ToDictionary(item => item.Split(':')[0], item => item.Split(':')[1]);
        }
        public ActionResult GridViewPartialDelete(System.String BI, System.String PredmetId)
        {
            var model = db.Ispits;

            BI = BI.TrimStart(' ', '"');
            BI = BI.TrimEnd(' ', '"');

            PredmetId = PredmetId.TrimStart(' ', '"');
            PredmetId = PredmetId.TrimEnd(' ', '"');

            if (BI != null)
            {
                try
                {
                    var item = model.Where(x => x.BI == BI && x.PredmetId == PredmetId).FirstOrDefault();

                    if (item != null)
                    {
                        model.Remove(item);
                    }
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    ViewData["EditError"] = e.Message;
                }
            }
            return(PartialView("_GridViewPartial", model.ToList()));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Converts 4-byte integer array into character string.
        /// </summary>
        /// <param name="ibuf">Integer array to convert</param>
        /// <param name="nbyte">The number of bytes to convert (expected to be
        /// a multiple of 4)</param>
        /// <returns></returns>
        internal static string I4ch(int* ibuf, int nbyte)
        {
            Debug.Assert((nbyte%4) == 0);

            char[] res = new char[nbyte];
            for (int i=0, j=0; i<nbyte/4; i++, j+=4)
            {
                int val = ibuf[i];
            #if (_SUN)
                res[j+3] = (char)(val & 0x000000FF);
                res[j+2] = (char)((val & 0x0000FF00) >> 8);
                res[j+1] = (char)((val & 0x00FF0000) >> 16);
                res[j]   = (char)((val & 0xFF000000) >> 24);
            #else
                res[j]   = (char)(val & 0x000000FF);
                res[j+1] = (char)((val & 0x0000FF00) >> 8);
                res[j+2] = (char)((val & 0x00FF0000) >> 16);
                res[j+3] = (char)((val & 0xFF000000) >> 24);
            #endif
            }

            // Force any embedded nulls into blanks.

            for (int i=0; i<nbyte; i++)
            {
                if (res[i]=='\0')
                    res[i] = ' ';
            }

            // Strip off trailing white space
            string s = new String(res);
            return s.TrimEnd(null);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Removes spaces end <see cref="DirectorySeparatorChar "/> at the end of a string
        /// </summary>
        internal static String InternalTrimTrailingSeparator( String path )
        {
            Contract.Requires( !String.IsNullOrWhiteSpace( path ) );
            Contract.Ensures( !String.IsNullOrWhiteSpace( Contract.Result<String>() ) );

            return path.TrimEnd( WhiteSpace ).TrimEnd( DirectorySeparatorChar );
        }
Ejemplo n.º 9
0
        public ServerConnectionModel(String hostIP, String userName, String userPassword)
        {
            Host = hostIP;
            User = userName;
            Password = userPassword;

                Host.TrimEnd('/');
        }
Ejemplo n.º 10
0
				public uint Offset; //the offset of this section in the nxz

				public SectionEntry(Stream stream)
				{
					BinaryReader rdr = new BinaryReader(stream);
					Name = new String(rdr.ReadChars(rdr.ReadByte()));
					Name = Name.TrimEnd('\0');//dont include the required terminator
					type = (Types)rdr.ReadByte();
					Length = rdr.ReadUInt32();
					u3 = rdr.ReadInt32();
				}
 //hex轉byte用的
 public static byte[] StringToByteArray(String hex)
 {
     hex = hex.TrimEnd('\r', '\n');//trim CRLF
     int NumberChars = hex.Length;
     byte[] bytes = new byte[NumberChars / 2];
     for (int i = 0; i < NumberChars; i += 2)
         bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
     return bytes;
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Map C# (server) class namespace to JS (client) namespace. Use * and % to define prefix mappings.
 /// </summary>
 /// <param name="ns">Name of the C# (server) namespace. If the name ends with *, prefix match is used. If the name ends with % only that part of namespace is mapped. </param>
 /// <param name="cns">Name of the JS (client) namespace.</param>
 public void RegisterNamespaceMapping(String ns, String cns)
 {
     namespaceMapping.Add(new NamespaceMapping
     {
         Namespace = ns.TrimEnd('*'),
         ClientNamespace = (cns ?? "").TrimEnd('*'),
         Mode = GetNamespaceMappingMode(ns, cns)
     });
 }
Ejemplo n.º 13
0
        public async Task CopyToContainerAsync(
            IAsyncCommandContext context,
            String source,
            CancellationToken cancellationToken)
        {
            //set maxConcurrentUploads up to 2 untill figure out how to use WinHttpHandler.MaxConnectionsPerServer modify DefaultConnectionLimit
            int maxConcurrentUploads = Math.Min(Environment.ProcessorCount, 2);
            //context.Output($"Max Concurrent Uploads {maxConcurrentUploads}");

            IEnumerable<String> files;
            if (File.Exists(source))
            {
                files = new List<String>() { source };
                _sourceParentDirectory = Path.GetDirectoryName(source);
            }
            else
            {
                files = Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories);
                _sourceParentDirectory = source.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
            }

            context.Output(StringUtil.Loc("TotalUploadFiles", files.Count()));
            foreach (var file in files)
            {
                _fileUploadQueue.Enqueue(file);
            }

            using (_uploadCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
            {
                List<Task> allRunningTasks = new List<Task>();
                // start reporting task to keep tracking upload progress.
                allRunningTasks.Add(ReportingAsync(context, files.Count(), _uploadCancellationTokenSource.Token));

                // start parallel upload task.
                for (int i = 0; i < maxConcurrentUploads; i++)
                {
                    allRunningTasks.Add(ParallelUploadAsync(context, i, _uploadCancellationTokenSource.Token));
                }

                // the only expected type of exception will throw from both parallel upload task and reporting task is OperationCancelledException.
                try
                {
                    await Task.WhenAll(allRunningTasks);
                }
                catch (OperationCanceledException)
                {
                    // throw aggregate exception for all non-operationcancelexception we catched during file upload.
                    if (_exceptionsDuringFileUpload.Count > 0)
                    {
                        throw new AggregateException(_exceptionsDuringFileUpload).Flatten();
                    }

                    throw;
                }
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Создает экземпляр класса
 /// </summary>
 /// <param name="address">Адрес</param>
 /// <param name="id">Код</param>
 /// <param name="inn">ИНН</param>
 /// <param name="kpp">КПП</param>
 /// <param name="name">Наименование</param>
 /// <param name="section">Номер секции ФР</param>
 /// <param name="warrant">Номер свидетельства ИП</param>
 public OwnerData(String id, String name, String address, String inn, String kpp,
     String warrant, Int32 section)
 {
     _id = id.TrimEnd();
     _name = name.TrimEnd();
     _address = address.TrimEnd();
     _inn = inn.TrimEnd();
     _kpp = kpp.TrimEnd();
     _warrant = warrant.TrimEnd();
     _section = section;
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Convert from DICOM format to Common Data Format.
        /// </summary>
        /// <param name="dicomFormat">DICOM format.</param>
        public override void FromDicomFormat(System.String dicomFormat)
        {
            // remove any trailing spaces from the name
            dicomFormat = dicomFormat.TrimEnd(' ');

            // split the incoming dicom format into the three component groups
            System.String[] nameComponentGroups = new System.String[3];
            nameComponentGroups = dicomFormat.Split('=');

            // split the first component group into the five components
            if (nameComponentGroups.Length > 0)
            {
                System.String[] nameComponents = new System.String[5];
                nameComponents = nameComponentGroups[0].Split('^');

                // save the individual components
                switch (nameComponents.Length)
                {
                case 1:
                    _surname = nameComponents[0];
                    break;

                case 2:
                    _surname   = nameComponents[0];
                    _firstName = nameComponents[1];
                    break;

                case 3:
                    _surname    = nameComponents[0];
                    _firstName  = nameComponents[1];
                    _middleName = nameComponents[2];
                    break;

                case 4:
                    _surname    = nameComponents[0];
                    _firstName  = nameComponents[1];
                    _middleName = nameComponents[2];
                    _prefix     = nameComponents[3];
                    break;

                case 5:
                    _surname    = nameComponents[0];
                    _firstName  = nameComponents[1];
                    _middleName = nameComponents[2];
                    _prefix     = nameComponents[3];
                    _suffix     = nameComponents[4];
                    break;

                default:
                    break;
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Combines several path elements
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public static String Combine(String left, String right)
        {
            // remove delimiter
            right = right.TrimStart(Delimiter);
            left = left.TrimEnd(Delimiter);

            // build the path
            if (right.Length == 0)
                return left;
            else
                return left + Delimiter + right;
        }
Ejemplo n.º 17
0
        public Dictionary<String, String> fromJSON(String json)
        {
            Dictionary<String, String> dict = new Dictionary<String, String>();

            Char[] splits = new Char[1];
            splits[0] = ',';

            if (!String.IsNullOrEmpty(json))
            {
                json = json.Trim();

                // Remove leading and trailing breakets
                if (json.StartsWith("{"))
                {
                    json = json.Remove(0, 1);
                    json = json.TrimStart();
                }
                if (json.EndsWith("}"))
                {
                    json = json.Remove(json.Length - 1);
                    json = json.TrimEnd();
                }

                String[] jsonItems = json.Split(splits, StringSplitOptions.RemoveEmptyEntries);

                // iterate all comma-separeted key-value-pairs
                for (int i = 0; i < jsonItems.Length; i++)
                {
                    String currentPart = jsonItems[i];
                    // check if it's a 'real' item-separator or maybe a comma inside a 'marked' string
                    if (checkForConsistentQuotes(currentPart) && currentPart.Contains(":"))
                    {
                        processKeyValuePair(dict, currentPart);
                    }
                    // we splitted inside a string, so do some error-handling
                    else if (i < jsonItems.Length - 1)
                    {
                        // add upcoming parts as long as we do not have a 'working' part
                        do
                        {
                            i++;
                            currentPart += "," + jsonItems[i];
                        }
                        while (!(checkForConsistentQuotes(currentPart) && currentPart.Contains(":")));

                        processKeyValuePair(dict, currentPart);
                    }
                }
            }

            return dict;
        }
Ejemplo n.º 18
0
		public String PathCombine(String path1, String path2) {
			path1 = path1.TrimEnd("/\\".ToCharArray());
			path2 = path2.TrimStart("/\\".ToCharArray());
			if(Environment.OSVersion.Platform == PlatformID.Win32NT) {
				path1 = path1.Replace("/","\\");
				path2 = path2.Replace("/","\\");
			}

			if(string.IsNullOrWhiteSpace(path1) || string.IsNullOrEmpty(path1))
				return path2;
			else
				return String.Format("{0}{1}{2}",path1,Path.DirectorySeparatorChar,path2);
		}
Ejemplo n.º 19
0
 public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
 {
     var str = new String(chars);
     str = str.Replace(" ", "");
     for(int i = charIndex ; i < charIndex + str.Length ; i += 2)
     {
         var charOffset = i - charIndex;
         var byteString = new String(new char[] { str[i], str[i + 1] });
         var b = byte.Parse(byteString.TrimEnd(), NumberStyles.HexNumber);
         bytes[byteIndex + charOffset / 2] = b;
     }
     return str.Length / 2;
 }
Ejemplo n.º 20
0
        public static void checkName(String Value)
        {
            //this is to check if all the words in value starts with an uppercase letter, to properly give names
            try
            {


                if (String.IsNullOrEmpty(Value.TrimEnd()))
                    return;

                Value = Value.TrimEnd();
                String[] splitter = Value.Split(' ');
                ArrayList AL = new ArrayList();
                AL.AddRange(splitter);

                for (int x = 0; x < AL.Count; x++)
                {
                    String cur = ((String)AL[x]).Substring(0, 1);
                    cur = cur.ToUpper();
                    if (!((String)AL[x]).StartsWith(cur))
                    {
                        InputException IE = new InputException("Each word needs to start with an uppercase letter", Source);
                        valList.AddException(IE);
                        throw IE;
                    }
                }
            }
            catch (InputException ie)
            {
                throw ie;
            }
            catch (Exception ex)
            {
                InputException IE = new InputException("There can only be one space between each word", Source);
                valList.AddException(IE);
                throw IE;
            }
        }
Ejemplo n.º 21
0
        public StoreQueryParam ContainsAll(String[] values)
        {
            propertyFormat = "";

            foreach (String value in values)
            {
                propertyFormat += String.Format(" {{0}} LIKE '%{1}%' AND", "0", value);
            }
            // Remove last OR
            propertyFormat = propertyFormat.TrimEnd('A', 'N', 'D');
            // Set the value to nothing, just to keep the String.Format ok.
            this.propertyValue = String.Empty;
            return this;
        }
Ejemplo n.º 22
0
        public StoreQueryParam ContainsAll(params Enum[] enumValues)
        {
            propertyFormat = "";

            foreach (Enum enumValue in enumValues)
            {
                propertyFormat += String.Format(" {{0}} & {1} = {1} AND", "0", Convert.ToInt64(enumValue));
            }
            // Remove last OR
            propertyFormat = propertyFormat.TrimEnd('A', 'N', 'D');
            // Set the value to nothing, just to keep the String.Format ok.
            this.propertyValue = String.Empty;
            return this;
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Преобразует строку в значение типа события
 /// </summary>
 /// <param name="value">Исходная строка</param>
 /// <returns>Значение типа события</returns>
 public static EventType ConvertTo(String value)
 {
     switch (value.TrimEnd())
     {
         case "Ошибка":
             return EventType.Error;
         case "Информация":
             return EventType.Information;
         case "Предупреждение":
             return EventType.Warning;
         default:
             return EventType.Undefined;
     }
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Convert from Common Data Format to DICOM format.
        /// </summary>
        /// <returns>DICOM format.</returns>
        public override System.String ToDicomFormat()
        {
            // format the name using all the components
            System.String nameComponents = _surname + "^" +
                                           _firstName + "^" +
                                           _middleName + "^" +
                                           _prefix + "^" +
                                           _suffix;

            // trim off any trailing component delimiters
            System.String dicomName = nameComponents.TrimEnd('^');

            return(dicomName);
        }
Ejemplo n.º 25
0
        public User(String name)
        {
            username = name;

            String xName = Regex.Replace(name, "[^0-9A-Za-z]", "");
            email = xName + "@" + xName + ".com";
            url = "http://www." + xName + ".com";

            Random rand = new Random();
            for (int n = 0; n < 4; n++)
            {
                ip += rand.Next(1, 255).ToString() + ".";
            }
            ip = ip.TrimEnd(new char[] { '.' });
        }
Ejemplo n.º 26
0
    public static string MakeRelativePath(String fromPath, String toPath)
    {
        toPath = toPath.TrimEnd('\\', '/');
        fromPath = fromPath.TrimEnd('\\', '/');

        if (!toPath.Contains(fromPath))
        {
            return "";
        }
        var path = toPath.Substring(fromPath.Length).Trim('\\', '/');
        if (path.Length == 0)
        {
            return Path.DirectorySeparatorChar.ToString();
        }
        return path;
    }
Ejemplo n.º 27
0
        public static void checkIfNumber(String Value)
        {
            //this checks if the input can be parsed as an integer
            if (String.IsNullOrEmpty(Value.TrimEnd()))
                return;

            try
            {
                int.Parse(Value);
            }
            catch (Exception e)
            {
                InputException IE = new InputException("The value needs to be a number",Source);
                valList.AddException(IE);
                throw IE;
            }
        }
Ejemplo n.º 28
0
        public String[] ParseMessage(String message)
        {
            String[] messageData = new String[2];

            message = message.TrimEnd(new char[] { '\0' });
            if (message.StartsWith("#") && message.EndsWith("##"))
            {
                message = message.Trim(new char[] { '#' });
                messageData = message.Split(new char[] { '#' }, 2);
            }
            else
            {
                throw new ArgumentException("Invalid message. Message format: #_ID_#_OPTIONAL_MESSAGE_##.");
            }

            return messageData;
        }
Ejemplo n.º 29
0
        private void skinButton1_Click(object sender, EventArgs e)
        {
            Cloud_Script_Url = "";
            Cloud_Url = skinTextBox1.Text;
            Cloud_Url = Cloud_Url.Trim();

            char[] charsToTrim = { '/'};
            Cloud_Url = Cloud_Url.TrimEnd(charsToTrim); //去除结尾的反斜杠

            int check_intFlag = Cloud_Url.IndexOf("http://");
            if(check_intFlag!=0)
            {
                MessageBox.Show("请提供以http://开头的链接地址!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                toolStripStatusLabel2.Text = "请提供以http://开头的链接地址!";
                skinTextBox1.Text = "";
            }
            else
            {
                toolStripStatusLabel2.Text = "运行正常";
                Cloud_Script_Url = Cloud_Url+"/script.php";
               // MessageBox.Show(Cloud_Url);
                //检测 云端脚本的返回值 参数为check 返回值为LinkOk

                switch (CheckUrlExist(Cloud_Script_Url))
                {
                    case 0:
                        MessageBox.Show("提供的云端链接不可到达!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        toolStripStatusLabel2.Text = "提供的云端链接不可达!";
                        break;
                    case 1:
                        MessageBox.Show("云端脚本文件不存在!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        toolStripStatusLabel2.Text = "云端脚本文件不存在!";
                        break;
                    case 2:
                        MessageBox.Show("云端脚本文件配置错误!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        toolStripStatusLabel2.Text = "云端脚本文件配置错误!";
                        break;
                    default:
                        MessageBox.Show("新云端环境配置完毕,确认重启!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        File.WriteAllText(Cloud_flag, Cloud_Url+"/"+Environment.NewLine+Cloud_Script_Url); //写入云端路径
                        Application.Restart();
                        break;
                }

            }
        }
Ejemplo n.º 30
0
        //THIS TAKES SUSPECIOUSLY LONG TIME: MAYBE MOVE AWAY FROM STREAM?
        //I changed it to a streamreader because wikipedia.org has an incredibly long robots.txt
        //And a string can't contain all that information
        private List<string> GetRobotsTxt(String url)
        {
            List<String> rules= new List<String>();
            bool foundMe = false;
            WebClient client = new WebClient();

            try{
                url= url.TrimEnd('/');
                using (Stream stream = client.OpenRead(new Uri(url+"/robots.txt")))
                {
                    using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.ASCII))
                    {

                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            if (foundMe)
                            {
                                if ((line.ToLower().Contains("allow") || line.ToLower().Contains("disallow")) && !line.ToLower().StartsWith("#"))
                                {
                                    rules.Add(line);
                                }
                                //else{break;}
                            }
                            if (foundMe && line.ToLower().Contains("user-agent:"))
                            {
                                //foundMe =false; //If my rules are separated in different places of te robots.txt then it is just bad formattin on their part
                                break;
                            }
                            if (line.ToLower().Contains("user-agent: *"))
                            {
                                foundMe = true;
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                return rules;
                //Console.Write(url + " Robot.cs: ");
                //Console.WriteLine(ex.Message);
            }
            return rules;
        }
Ejemplo n.º 31
0
        public static string CleanLine(String Line)
        {
            char SOH = (char)1;
            char STX = (char)2;
            char RS = (char)30;
            char US = (char)31;
            // change the dot to a [ for start of string
            string startingChars = System.Text.Encoding.GetEncoding(932).GetString(new byte[2] { 0x1e, 0xfc });
            if (Line.StartsWith(startingChars))
                Line = "[" + Line.Substring(2);

            Line = Line.Replace(US.ToString() + "y", String.Empty);

            if (Line.Contains(" " + RS.ToString() + STX.ToString()))
            {
                Line = Line.Replace(" " + RS.ToString() + SOH.ToString(), "**&*&!!@#$@$#$");
                Line = Line.Replace("**&*&!!@#$@$#$", " ");
            }

            Line = Line.Replace("1", "")
                .Replace(" " + RS.ToString() + STX.ToString(), " ") // green start
                .Replace(RS.ToString() + SOH.ToString(), "")   // green end
                .Replace("Ð", "")
                .Replace(US.ToString() + "{", "")
                .Replace(US.ToString() + "?", "")
                .Replace(US.ToString() + "", "")
                .Replace(US.ToString() + "·", "E")
                .Replace(RS.ToString() + "·", "[")
                .Replace(RS.ToString() + "キ", "[")
                .Replace(RS.ToString() + "・", "[")
                .Replace(US.ToString() + "。", "")
                .Replace(US.ToString() + "ミ", "")
                .Replace("·", "");

            // trim the 1 that occasionally shows up at the end
            if (Line.EndsWith("1"))
                Line = Line.TrimEnd('1');

            Line = Regex.Replace(Line, @"^.?\??\[.+?\] ", ""); //remove timestamp

            return Line;
        }
Ejemplo n.º 32
0
        // Метод возвращает список с номерами трех цветов, которые необходимо еще раз предъявить тестируемому
        // Метод возвращает Null, если таковых нет
        public static List<int> CheckAnswers(String answerStr)
        {
            if (String.IsNullOrWhiteSpace(answerStr))
            {
                return null;
            }

            String[] items = answerStr.TrimEnd().Split(' ');
            List<LusherPairAnswerItem> answerItems = new List<LusherPairAnswerItem>();

            for (int i = 0; i < 28; i++)
            {
                LusherPairAnswerItem lusherPairAnswerItem = new LusherPairAnswerItem();
                String[] colorNumbers = items[i].Split(',');
                lusherPairAnswerItem.color_1 = Convert.ToInt32(colorNumbers[0]);
                lusherPairAnswerItem.color_2 = Convert.ToInt32(colorNumbers[1]);
                lusherPairAnswerItem.color_3 = Convert.ToInt32(colorNumbers[2]);
                answerItems.Add(lusherPairAnswerItem);
            }

            List<LusherPairColorItem> list = CountAndSortDescColors(answerItems.Select(x => x.color_3).ToArray());

            List<int> specialNumbers = new List<int>();

            int index = 0;
            while (index < list.Count - 2)
            {
                if (list[index].points == list[index + 1].points && list[index].points == list[index + 2].points)
                {
                    specialNumbers.Add(list[index].number);
                    specialNumbers.Add(list[index+1].number);
                    specialNumbers.Add(list[index+2].number);
                    break;
                }
                index++;
            }
            if (specialNumbers.Count == 0)
            {
                return null;
            }
            return specialNumbers;
        }
Ejemplo n.º 33
0
        public static String GetUNCPath(String path)
        {
            path = path.TrimEnd('\\', '/') + Path.DirectorySeparatorChar;
            DirectoryInfo d = new DirectoryInfo(path);
            String root = d.Root.FullName.TrimEnd('\\');

            if (!root.StartsWith(@"\\"))
            {
                ManagementObject mo = new ManagementObject();
                mo.Path = new ManagementPath(String.Format("Win32_LogicalDisk='{0}'", root));

                // DriveType 4 = Network Drive
                if (Convert.ToUInt32(mo["DriveType"]) == 4)
                    root = Convert.ToString(mo["ProviderName"]);
                else
                    root = @"\\" + System.Net.Dns.GetHostName() + "\\" + root.TrimEnd(':') + "$\\";
            }

            return Recombine(root, d);
        }
Ejemplo n.º 34
0
 /**
  * static method that converts string, that represents a status, to  Status enum
  * In case that the given string is incorrect then the value "Idle" is returned.
  */
 public static Status convertToStatusObj(String statusStr)
 {
     Status statusObj;
     statusStr = statusStr.ToLower(System.Globalization.CultureInfo.InvariantCulture);
     statusStr = statusStr.TrimEnd(' ');
     switch (statusStr)
     {
         case "idle":
             statusObj = Status.Idle;
             break;
         case "waiting":
             statusObj = Status.Waiting;
             break;
         case "active":
             statusObj = Status.Active;
             break;
         default:
             statusObj= Status.Idle;
             break;
     }
     return statusObj;
 }
Ejemplo n.º 35
0
        /**
         * Subst mounts (or aliases) long directory paths into a short letter drive for the current user
         */
        public static void SetSubstDrive(char driveLetter, String path)
        {
            if (String.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path cannot be empty");
            }

            // Important to remove last backslash. Otherwise it would cause subst to fail with "path not found"
            path = path.TrimEnd('\\');

            if (!Directory.Exists(path))
            {
                GSTrace.WriteLine("Creating directory " + path);
                Directory.CreateDirectory(path);
                if (!Directory.Exists(path))
                {
                    throw new FileNotFoundException(path);
                }
            }

            String existingPath = FileUtils.GetSubstDrive(driveLetter);
            if (existingPath != null)
            {
                if (path.Equals(existingPath)) {
                    return;
                }
                DeleteSubstDrive(driveLetter);
            }

            String output = Subst(driveLetter+": " + path);
            if (output.Replace("\n", "").Trim().Length > 0)
            {
                // probable path not found
                throw new FileNotFoundException(output);
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Convert from HL7 format to Common Data Format.
        /// </summary>
        /// <param name="hl7Format">HL7 format.</param>
        public override void FromHl7Format(System.String hl7Format)
        {
            // <family name (ST)> ^
            // <given name (ST)> ^
            // <middle initial or name (ST)> ^
            // <suffix (e.g., JR or III) (ST)> ^
            // <prefix (e.g., DR) (ST)> ^
            // <degree (e.g., MD) (ST)>
            // remove any trailing spaces from the name
            hl7Format = hl7Format.TrimEnd(' ');

            // split the HL7 format into the six components
            System.String[] nameComponents = new System.String[6];
            nameComponents = hl7Format.Split('^');

            // save the individual components
            switch (nameComponents.Length)
            {
            case 1:
                _surname = nameComponents[0];
                break;

            case 2:
                _surname   = nameComponents[0];
                _firstName = nameComponents[1];
                break;

            case 3:
                _surname    = nameComponents[0];
                _firstName  = nameComponents[1];
                _middleName = nameComponents[2];
                break;

            case 4:
                _surname    = nameComponents[0];
                _firstName  = nameComponents[1];
                _middleName = nameComponents[2];
                _suffix     = nameComponents[3];
                break;

            case 5:
                _surname    = nameComponents[0];
                _firstName  = nameComponents[1];
                _middleName = nameComponents[2];
                _suffix     = nameComponents[3];
                _prefix     = nameComponents[4];
                break;

            case 6:
                _surname    = nameComponents[0];
                _firstName  = nameComponents[1];
                _middleName = nameComponents[2];
                _suffix     = nameComponents[3];
                _prefix     = nameComponents[4];
                _degree     = nameComponents[5];
                break;

            default:
                break;
            }
        }
Ejemplo n.º 37
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="affectedEntity"></param>
 /// <param name="tag"></param>
 /// <param name="root"></param>
 /// <param name="format"></param>
 public TagValueAutoSetUid(AffectedEntityEnum affectedEntity, DvtkData.Dimse.Tag tag, System.String root, int format)
     : base(affectedEntity, tag)
 {
     _root   = root.TrimEnd('.');
     _format = format;
 }
Ejemplo n.º 38
0
 public static System.String CutEnd(this System.String s, System.String what)
 {
     return(s.TrimEnd(what.ToCharArray()));
 }