string.Substring(int)

Here are the examples of the csharp api string.Substring(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

13016 Examples 7

19 Source : PagingUtil.cs
with MIT License
from a34546

public static PartedSql SplitSql(string sql)
        {
            var parts = new PartedSql { Raw = sql };

            // Extract the sql from "SELECT <whatever> FROM"
            var s = _rexSelect1.Match(sql);
            if (s.Success)
            {
                parts.Select = s.Groups[1].Value;


                sql = sql.Substring(s.Length);
                s = _rexOrderBy.Match(sql);
                if (s.Success)
                {
                    sql = sql.Substring(0, s.Index);
                    parts.OrderBy = s.Groups[1].Value;
                }
                parts.Body = "(" + sql;

                return parts;
            }

            var m = _rexSelect.Match(sql);
            if (!m.Success)
                throw new ArgumentException("Unable to parse SQL statement for select");
            parts.Select = m.Groups[1].Value;


            sql = sql.Substring(m.Length);
            m = _rexOrderBy.Match(sql);
            if (m.Success)
            {
                sql = sql.Substring(0, m.Index);
                parts.OrderBy = m.Groups[1].Value;
            }
            parts.Body = sql;

            return parts;
        }

19 Source : UserLicense.cs
with GNU General Public License v3.0
from a2659802

public static void ShowLicense()
        {
            if(!agreeLicense)
            {
                string bundleN = "userlicense";
                replacedetBundle ab = null;  // You probably want this to be defined somewhere more global.
                replacedembly asm = replacedembly.GetExecutingreplacedembly();
                foreach (string res in asm.GetManifestResourceNames()) 
                {
                    using (Stream s = asm.GetManifestResourceStream(res))
                    {
                        if (s == null) continue;
                        byte[] buffer = new byte[s.Length];
                        s.Read(buffer, 0, buffer.Length);
                        s.Dispose();
                        string bundleName = Path.GetExtension(res).Substring(1);
                        if (bundleName != bundleN) continue;
                        Logger.Log("Loading bundle " + bundleName);
                        ab = replacedetBundle.LoadFromMemory(buffer); // Store this somewhere you can access again.
                    }
                }
                var _canvas = ab.Loadreplacedet<GameObject>("userlicense");
                UnityEngine.Object.Instantiate(_canvas);
                Logger.Log("Show User License");
            }
        }

19 Source : ProCamsLensDataTable.cs
with Apache License 2.0
from A7ocin

public void LoadLensData()
	{
		_filmFormats = new List<FilmFormatData>();
		
		// Load in the data from Resources/CinemaSuite_LensData.txt
		Textreplacedet textreplacedet = (Textreplacedet)(Resources.Load("CinemaSuite_LensData", typeof(Textreplacedet)));
		if(textreplacedet == null)
		{
			Debug.LogError("File 'CinemaSuite_LensData.txt' is not found in Resources folder. Unable to load lens data.");
			return;
		}
		
		FilmFormatData currentFormat = null;
		
		string[] lines = textreplacedet.text.Split("\n"[0]);
		int numLines = lines.Length;
		for(int i = 0; i < numLines; ++i)
		{
			//Debug.Log("Line: " + i + "= " + lines[i]);
			
			string line = lines[i].Trim();
			if(line.StartsWith("#"))
			{
				continue;	
			}
			
			int length = line.Length;
			
			if(currentFormat == null)
			{
				// Look for "Name="
				if(line.StartsWith("Name="))
				{
					// New section

					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						string name = line.Substring(index).Trim();
						if(name.Length != 0)
						{
							// Create new film format with valid name
							currentFormat = new FilmFormatData();
							currentFormat._formatName = name;
						}
					}
				}
				else if(length != 0)
				{
					Debug.LogError("Invalid data at line: " + i);
				}
			}
			else
			{
				// Look for film format section entries
				
				if(length == 0)
				{
					// End of section
					_filmFormats.Add(currentFormat);
					//Debug.Log ("Added film format " + currentFormat._formatName);
					currentFormat = null;
				}
				else if(line.StartsWith("Aspect="))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						string strAspect = line.Substring(index).Trim();
						int colon = strAspect.IndexOf(":");
						if(colon > 0 && colon < length)
						{
							string first = strAspect.Substring(0, colon).Trim();
							string second = strAspect.Substring(colon + 1).Trim();
							float w = 0;
							float h = 0;
							
							if(!float.TryParse(first, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out w) || w <= 0)
							{
								Debug.LogError("Invalid number: " + first + " at line " + (i + 1));
								return;
							}
							if(!float.TryParse(second, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out h) || h <= 0)
							{
								Debug.LogError("Invalid number: " + second + " at line " + (i + 1));
								return;
							}
							currentFormat._aspect = w / h;
							//Debug.Log ("Aspect: " + currentFormat._aspect);
						}
					}
				}
				else if(line.StartsWith("ScreenSize"))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						// ScreenSize=DI,1024
						string[] strSizes = line.Substring(index).Split(","[0]);
						if(strSizes == null || strSizes.Length != 2)
						{
							Debug.LogError("Invalid screen size entry at line " + (i + 1));
							return;
						}
						
						string sizeName = strSizes[0].Trim();
						int sizeValue = 0;
						if(!int.TryParse(strSizes[1].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out sizeValue) || sizeValue <= 0)
						{
							Debug.LogError("Invalid screen size at line " + (i + 1));
							return;
						}
						currentFormat._screenSizes.Add(new ScreenSize(sizeName, sizeValue));
						//Debug.Log ("Screensize: " + sizeName + ", " + sizeValue);
					}
				}
				else if(line.StartsWith("FocalLength"))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						// FocalLength=Cooke S4/i - T2,12mm,4.980,00.000,00.000
						string[] strData = line.Substring(index).Split(","[0]);
						if(strData == null || strData.Length != 5)
						{
							Debug.LogError("Invalid data for focal length at line " + (i + 1));
							return;
						}
						
						string lensKit = strData[0].Trim();
						if(lensKit.Length == 0)
						{
							Debug.LogError("Invalid lens kit name at line " + (i + 1));
							return;
						}
						
						int focal = 0;
						if(!int.TryParse(strData[1].TrimEnd('m'), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out focal) || focal <= 0)
						{
							Debug.LogError("Invalid focal length at line " + (i + 1));
							return;
						}
						
						float nodal = 0;
						if(!float.TryParse(strData[2].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out nodal) || nodal < 0)
						{
							Debug.LogError("Invalid nodal offset at line " + (i + 1));
							return;
						}
						
						float realFOV = 0;
						if(!float.TryParse(strData[3].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out realFOV) || realFOV <= 0)
						{
							Debug.LogError("Invalid real FOV at line " + (i + 1));
							return;
						}
						
						float unityFOV = 0;
						if(!float.TryParse(strData[4].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out unityFOV) || unityFOV <= 0)
						{
							Debug.LogError("Invalid Unity FOV at line " + (i + 1));
							return;
						}
						
						currentFormat.AddFocalLengthData(lensKit, focal, nodal, realFOV, unityFOV);
						//Debug.Log ("Focal Data: " + lensKit + ", " + focal + ", " + nodal + ", " + realFOV + ", " + unityFOV);
					}
				}
			}
		}
	}

19 Source : WebServer.cs
with Apache License 2.0
from A7ocin

void OnGetContext(IAsyncResult async)
        {
            // start listening for the next request
            _listener.BeginGetContext(OnGetContext, null);
            var context = _listener.EndGetContext(async);
            try
            {
                if (context.Request.RawUrl == "/")
                {
                    Debug.Log("[WebServer] context.Request.RawUrl");
                    context.Response.StatusCode = 200;
                    var process = System.Diagnostics.Process.GetCurrentProcess();
                    string msg = string.Format(@"<html><body><h1>UMA Simple Web Server</h1><table>
						<tr><td>Host Application</td><td>{0} (Process Id: {1})</td></tr>
						<tr><td>Working Directory</td><td>{2}</td></tr>
						</table><br><br>{3}</body></html>", process.ProcessName, process.Id, System.IO.Directory.GetCurrentDirectory(), GetLog("<br>"));
                    var data = System.Text.Encoding.UTF8.GetBytes(msg);
                    context.Response.OutputStream.Write(data, 0, data.Length);
                    context.Response.OutputStream.Close();
                    //Tried adding response close aswell like in Adamas original
                    context.Response.Close();
                }
                else
                {
                    var filePath = System.IO.Path.Combine(_hostedFolder, context.Request.RawUrl.Substring(1));
                    if (System.IO.File.Exists(filePath))
                    {
                        using (var file = System.IO.File.Open(filePath, System.IO.FileMode.Open))
                        {
                            var buffer = new byte[file.Length];
                            file.Read(buffer, 0, (int)file.Length);
                            context.Response.ContentLength64 = file.Length;
                            context.Response.StatusCode = 200;
                            context.Response.OutputStream.Write(buffer, 0, (int)file.Length);
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                        UnityEngine.Debug.LogErrorFormat("Url not served. Have you built your replacedet Bundles? Url not served from: {0} '{1}'", context.Request.RawUrl, filePath);
#if UNITY_EDITOR
                        replacedetBundleManager.SimulateOverride = true;
                        context.Response.OutputStream.Close();
                        //Tried adding response close aswell like in Adamas original
                        context.Response.Abort();
                        return;
#endif
                    }
                }
                lock (_requestLog)
                {
                    _requestLog.Add(string.Format("{0} {1}", context.Response.StatusCode, context.Request.Url));
                }
                context.Response.OutputStream.Close();
                context.Response.Close();
            }
            catch (HttpListenerException e)
            {
                if (e.ErrorCode == -2147467259)
                {
                    // shutdown, terminate silently
                    Debug.LogWarning("[Web Server] ErrorCode -2147467259: terminate silently");
                    context.Response.Abort();
                    return;
                }
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
        }

19 Source : UmaSlotBuilderWindow.cs
with Apache License 2.0
from A7ocin

string GetreplacedetName()
	    {
	        int index = slotName.LastIndexOf('/');
	        if (index > 0)
	        {
	            return slotName.Substring(index + 1);
	        }
	        return slotName;
	    }

19 Source : UMACrowdRandomSet.cs
with Apache License 2.0
from A7ocin

public static void Apply(UMA.UMAData umaData, CrowdRaceData race, Color skinColor, Color HairColor, Color Shine, HashSet<string> Keywords, SlotLibraryBase slotLibrary, OverlayLibraryBase overlayLibrary)
		{
			var slotParts = new HashSet<string>();
			umaData.umaRecipe.slotDataList = new SlotData[race.slotElements.Length];
			for (int i = 0; i < race.slotElements.Length; i++)
			{
				var currentElement = race.slotElements[i];
				if (!string.IsNullOrEmpty(currentElement.requirement) && !slotParts.Contains(currentElement.requirement)) continue;
				if (!string.IsNullOrEmpty(currentElement.condition))
				{
					if (currentElement.condition.StartsWith("!"))
					{
						if (Keywords.Contains(currentElement.condition.Substring(1))) continue;
					}
					else
					{
						if (!Keywords.Contains(currentElement.condition)) continue;
					}
				}
				if (currentElement.possibleSlots.Length == 0) continue;
				int randomResult = Random.Range(0, currentElement.possibleSlots.Length);
				var slot = currentElement.possibleSlots[randomResult];
				if (string.IsNullOrEmpty(slot.slotID)) continue;
				slotParts.Add(slot.slotID);
				SlotData slotData;
				if (slot.useSharedOverlayList && slot.overlayListSource >= 0 && slot.overlayListSource < i)
				{
					slotData = slotLibrary.InstantiateSlot(slot.slotID, umaData.umaRecipe.slotDataList[slot.overlayListSource].GetOverlayList());
				}
				else
				{
					if (slot.useSharedOverlayList)
					{
						Debug.LogError("UMA Crowd: Invalid overlayListSource for " + slot.slotID);
					}
					slotData = slotLibrary.InstantiateSlot(slot.slotID);
				}
				umaData.umaRecipe.slotDataList[i] = slotData;
				for (int overlayIdx = 0; overlayIdx < slot.overlayElements.Length; overlayIdx++)
				{
					var currentOverlayElement = slot.overlayElements[overlayIdx];
					randomResult = Random.Range(0, currentOverlayElement.possibleOverlays.Length);
					var overlay = currentOverlayElement.possibleOverlays[randomResult];
					if (string.IsNullOrEmpty(overlay.overlayID)) continue;
					overlay.UpdateVersion();
					slotParts.Add(overlay.overlayID);
					Color overlayColor = Color.black;
					var overlayData = overlayLibrary.InstantiateOverlay(overlay.overlayID, overlayColor);


					switch (overlay.overlayType)
					{
						case UMACrowdRandomSet.OverlayType.Color:
							overlayColor = overlay.minRGB;
							overlayData.colorData.color = overlayColor;

							break;
						case UMACrowdRandomSet.OverlayType.Texture:
							overlayColor = Color.white;
							overlayData.colorData.color = overlayColor;
							break;
						case UMACrowdRandomSet.OverlayType.Hair:
							overlayColor = HairColor * overlay.hairColorMultiplier;
							overlayColor.a = 1.0f;
							overlayData.colorData.color = overlayColor;
							break;
						case UMACrowdRandomSet.OverlayType.Skin:
							overlayColor = skinColor;//  + new Color(Random.Range(overlay.minRGB.r, overlay.maxRGB.r), Random.Range(overlay.minRGB.g, overlay.maxRGB.g), Random.Range(overlay.minRGB.b, overlay.maxRGB.b), 1);
							overlayData.colorData.color = overlayColor;
							if (overlayData.colorData.channelAdditiveMask.Length > 2)
							{
								overlayData.colorData.channelAdditiveMask[2] = Shine;
							}
							else
							{
								break;
							}
							break;
						case UMACrowdRandomSet.OverlayType.Random:
							{
								float randomShine = Random.Range(0.05f, 0.25f);
								float randomMetal = Random.Range(0.1f, 0.3f);

								overlayColor = new Color(Random.Range(overlay.minRGB.r, overlay.maxRGB.r), Random.Range(overlay.minRGB.g, overlay.maxRGB.g), Random.Range(overlay.minRGB.b, overlay.maxRGB.b), Random.Range(overlay.minRGB.a, overlay.maxRGB.a));
								overlayData.colorData.color = overlayColor;
								if (overlayData.colorData.channelAdditiveMask.Length > 2)
								{
									overlayData.colorData.channelAdditiveMask[2] = new Color(randomMetal, randomMetal, randomMetal, randomShine);
								}
							}
							break;
						default:
							Debug.LogError("Unknown RandomSet overlayType: "+((int)overlay.overlayType));
							overlayColor = overlay.minRGB;
							overlayData.colorData.color = overlayColor;
							break;
					}
		
					slotData.AddOverlay(overlayData);
					if (overlay.colorChannelUse != ChannelUse.None)
					{
						overlayColor.a *= overlay.minRGB.a;
						if (overlay.colorChannelUse == ChannelUse.InverseColor)
						{
							Vector3 color = new Vector3(overlayColor.r, overlayColor.g, overlayColor.b);
							var len = color.magnitude;
							if (len < 1f) len = 1f;
							color = new Vector3(1.001f, 1.001f, 1.001f) - color;
							color = color.normalized* len;
							overlayColor = new Color(color.x, color.y, color.z, overlayColor.a);
						}
						overlayData.SetColor(overlay.colorChannel, overlayColor);
					}
				}
			}
		}

19 Source : Helper.cs
with Apache License 2.0
from AantCoder

public static IPEndPoint TryParseStringToIp(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return null;
            }

            int port;
            var lastIndex = value.IndexOf(":");
            if (lastIndex > 0)
            {
                var strPort = value.Substring(lastIndex + 1);
                if (!int.TryParse(strPort, out port) || port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
                {
                    return null;
                }
            }
            else
            {
                port = Transfer.SessionClient.DefaultPort;
            }

            lastIndex = lastIndex > 0 ? lastIndex : value.Length;
            var ipString = value.Substring(0, lastIndex);

            if (!IPAddress.TryParse(ipString, out IPAddress ip))
            {
                return null;
            }

            return new IPEndPoint(ip, port);
        }

19 Source : ChatUtils.cs
with Apache License 2.0
from AantCoder

public static List<string> SplitBySpace(string args)
        {
            int i = 0;
            var argsM = new List<string>();
            while (i + 1 < args.Length)
            {
                if (args[i] == '\'')
                {
                    int endK = i;
                    bool exit;
                    do //запускаем поиск след кавычки снова, если после найденной ещё одна
                    {
                        exit = true;
                        endK = args.IndexOf('\'', endK + 1);
                        if (endK >= 0 && endK + 1 < args.Length && args[endK + 1] == '\'')
                        {
                            //это двойная кавычка - пропускаем её
                            endK++;
                            exit = false;
                        }
                    }

                    while (!exit);

                    if (endK >= 0)
                    {
                        argsM.Add(args.Substring(i + 1, endK - i - 1).Replace("''", "'"));
                        i = endK + 1;
                        continue;
                    }
                }

                var ni = args.IndexOf(" ", i);
                if (ni >= 0)
                {
                    //условие недобавления для двойного пробела
                    if (ni > i) argsM.Add(args.Substring(i, ni - i));
                    i = ni + 1;
                    continue;
                }
                else
                {
                    break;
                }
            }
            if (i < args.Length)
            {
                argsM.Add(args.Substring(i));
            }

            return argsM;
        }

19 Source : Crypto.cs
with Apache License 2.0
from AantCoder

public List<string> GetListPart(string source)
        {
            var list = new List<string>();
            if (string.IsNullOrEmpty(source)) return list;
            for (int i = 0; i <= source.Length / PartByteSize; i++)
            {
                var stradd =
                    //если последняя часть, то остаток строки
                    i == source.Length / PartByteSize
                    ? source.Substring(i * PartByteSize)
                    : source.Substring(i * PartByteSize, PartByteSize);
                if (!string.IsNullOrEmpty(stradd)) list.Add(stradd);
            }
            return list;
        }

19 Source : GameXMLUtils.cs
with Apache License 2.0
from AantCoder

public static string ReplaceByTag(string xml, string tagName, string newValue, string afterText = null)
        {
            int after = string.IsNullOrEmpty(afterText) ? 0 : xml.IndexOf(afterText);
            if (after < 0) after = 0;

            var tagNameB = "<" + tagName + ">";
            int pos = xml.IndexOf(tagNameB, after);
            if (pos < 0) return xml;
            pos += tagNameB.Length;
            
            var tagNameE = "</" + tagName + ">";
            int posE = xml.IndexOf(tagNameE, pos);
            if (posE < 0) return xml;

            return xml.Substring(0, pos) + newValue + xml.Substring(posE);
        }

19 Source : GameXMLUtils.cs
with Apache License 2.0
from AantCoder

public static string ReplaceByTag(string xml, string tagName 
            , Func<string, string> getNewValue)
        {
            var tagNameB = "<" + tagName + ">";
            int pos = xml.IndexOf(tagNameB);
            if (pos < 0) return xml;
            pos += tagNameB.Length;

            var tagNameE = "</" + tagName + ">";
            int posE = xml.IndexOf(tagNameE, pos);
            if (posE < 0) return xml;

            var newValue = getNewValue(xml.Substring(pos, posE - pos));
            if (newValue == null) return xml;

            return xml.Substring(0, pos) + newValue + xml.Substring(posE);
        }

19 Source : FileChecker.cs
with Apache License 2.0
from AantCoder

private static void generateHashFiles(List<ModelFileInfo> result, ref string rootFolder, string folder, bool level0 = false)
        {
            if (!level0)
            {
                var dirs = Directory.GetDirectories(folder);
                foreach (var subDir in dirs)
                {
                    generateHashFiles(result, ref rootFolder, subDir);
                }
            }

            var files = Directory.GetFiles(folder);
            int fileNamePos = rootFolder.Length + 1;
            var computeHash = new FastComputeHash();
            foreach (var file in files.Where(x => ApproveExt(x)))
            {
                var mfi = new ModelFileInfo()
                {
                    FileName = file.Substring(fileNamePos)
                };
                GetCheckSum(mfi, file, computeHash);
#if DEBUG
                /*
                if (mfi.FileName.Contains("armony"))
                {
                    Loger.Log($"generateHashFiles Harmony: {FileName} {Hash}");
                }*/
#endif
                result.Add(mfi);
            }
            computeHash.Wait();
        }

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public static string CheckIsIntruder(ServiceContext context, string key, string login)
        {
            if (key == null
                || !key.Contains("@@@"))
            {
                context.PossiblyIntruder = true;
                Loger.Log($"Is possibly intruder or not update {login} (empty key)");
                return key;
            }
            else
            {
                context.IntruderKeys = "";
                var keys = key.Split(new string[] { "@@@" }, StringSplitOptions.None);
                for (int i = 1; i < keys.Length; i++)
                {
                    if (string.IsNullOrEmpty(keys[i])) continue;
                    context.IntruderKeys += "@@@" + keys[i];
                    if (Repository.CheckIsIntruder(keys[i]))
                    {
                        Loger.Log($"Is intruder {login} key={keys[i]}");
                        context.Disconnect("intruder");
                        break;
                    }
                }

                Loger.Log($"Checked {login} key={key.Substring(key.IndexOf("@@@") + 3)}");
                return keys[0];
            }
        }

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public static bool CheckIsBanIP(string IP)
        {
            if ((DateTime.UtcNow - BlockipUpdate).TotalSeconds > 30)
            {
                var fileName = Loger.PathLog + "blockip.txt";

                BlockipUpdate = DateTime.UtcNow;
                if (!File.Exists(fileName)) Blockip = new HashSet<string>();
                else
                    try
                    {
                        var listBlock = File.ReadAllLines(fileName, Encoding.UTF8);
                        if (listBlock.Any(b => b.Contains("/")))
                        {
                            listBlock = listBlock
                                .SelectMany(b =>
                                {
                                    var bb = b.Trim();
                                    var comment = "";
                                    var ic = bb.IndexOf(" ");
                                    if (ic > 0)
                                    {
                                        comment = bb.Substring(ic);
                                        bb = bb.Substring(0, ic);
                                    }
                                    if (bb.Any(c => !char.IsDigit(c) && c != '.' && c != '/')) return new List<string>();
                                    var ls = bb.LastIndexOf("/");
                                    if (ls < 0) return new List<string>() { bb + comment };
                                    var lp = bb.LastIndexOf(".");
                                    if (lp <= 0) return new List<string>();
                                    var ib = int.Parse(bb.Substring(lp + 1, ls - (lp + 1)));
                                    var ie = int.Parse(bb.Substring(ls + 1));
                                    var res = new List<string>();
                                    var s = bb.Substring(0, lp + 1);
                                    for (int i = ib; i <= ie; i++)
                                        res.Add(s + i.ToString() + comment);
                                    return res;
                                })
                                .ToArray();
                            File.WriteAllLines(fileName, listBlock, Encoding.Default);
                        }
                        Blockip = new HashSet<string>(listBlock
                            .Select(b => b.Contains(" ") ? b.Substring(0, b.IndexOf(" ")) : b));
                    }
                    catch (Exception exp)
                    {
                        Loger.Log("CheckIsBanIP error " + exp.Message);
                        Blockip = new HashSet<string>();
                        return false;
                    }

            }

            return Blockip.Contains(IP.Trim());
        }

19 Source : V2Loader.cs
with MIT License
from Abdesol

internal static SystemColorHighlightingBrush GetSystemColorBrush(IXmlLineInfo lineInfo, string name)
		{
			Debug.replacedert(name.StartsWith("SystemColors.", StringComparison.Ordinal));
			string shortName = name.Substring(13);
			var property = typeof(SystemColors).GetProperty(shortName + "Brush");
			if (property == null)
				throw Error(lineInfo, "Cannot find '" + name + "'.");
			return new SystemColorHighlightingBrush(property);
		}

19 Source : V2Loader.cs
with MIT License
from Abdesol

static XshdReference<XshdRuleSet> ParseRuleSetReference(XmlReader reader)
		{
			string ruleSet = reader.GetAttribute("ruleSet");
			if (ruleSet != null) {
				// '/' is valid in highlighting definition names, so we need the last occurence
				int pos = ruleSet.LastIndexOf('/');
				if (pos >= 0) {
					return new XshdReference<XshdRuleSet>(ruleSet.Substring(0, pos), ruleSet.Substring(pos + 1));
				} else {
					return new XshdReference<XshdRuleSet>(null, ruleSet);
				}
			} else {
				return new XshdReference<XshdRuleSet>();
			}
		}

19 Source : InsertionContext.cs
with MIT License
from Abdesol

public void InsertText(string text)
		{
			if (text == null)
				throw new ArgumentNullException("text");
			if (currentStatus != Status.Insertion)
				throw new InvalidOperationException();

			text = text.Replace("\t", this.Tab);

			using (this.Doreplacedent.RunUpdate()) {
				int textOffset = 0;
				SimpleSegment segment;
				while ((segment = NewLineFinder.NextNewLine(text, textOffset)) != SimpleSegment.Invalid) {
					string insertString = text.Substring(textOffset, segment.Offset - textOffset)
						+ this.LineTerminator + this.Indentation;
					this.Doreplacedent.Insert(InsertionPosition, insertString);
					this.InsertionPosition += insertString.Length;
					textOffset = segment.EndOffset;
				}
				string remainingInsertString = text.Substring(textOffset);
				this.Doreplacedent.Insert(InsertionPosition, remainingInsertString);
				this.InsertionPosition += remainingInsertString.Length;
			}
		}

19 Source : V2Loader.cs
with MIT License
from Abdesol

static XshdReference<XshdColor> ParseColorReference(XmlReader reader)
		{
			string color = reader.GetAttribute("color");
			if (color != null) {
				int pos = color.LastIndexOf('/');
				if (pos >= 0) {
					return new XshdReference<XshdColor>(color.Substring(0, pos), color.Substring(pos + 1));
				} else {
					return new XshdReference<XshdColor>(null, color);
				}
			} else {
				return new XshdReference<XshdColor>(ParseColorAttributes(reader));
			}
		}

19 Source : HtmlRichTextWriter.cs
with MIT License
from Abdesol

public override void Write(string value)
		{
			int pos = 0;
			do {
				int endPos = value.IndexOfAny(specialChars, pos);
				if (endPos < 0) {
					WriteSimpleString(value.Substring(pos));
					return; // reached end of string
				}
				if (endPos > pos)
					WriteSimpleString(value.Substring(pos, endPos - pos));
				WriteChar(value[pos]);
				pos = endPos + 1;
			} while (pos < value.Length);
		}

19 Source : ScriptableObjectExtensions.cs
with Apache License 2.0
from abist-co-ltd

public static ScriptableObject Createreplacedet(this ScriptableObject scriptableObject, string path = null, string fileName = null)
        {
            var name = string.IsNullOrEmpty(fileName) ? $"{scriptableObject.GetType().Name}" : fileName;

            if (string.IsNullOrEmpty(path))
            {
                path = "replacedets";
            }

            if (Path.GetExtension(path) != string.Empty)
            {
                var subtractedPath = path.Substring(path.LastIndexOf("/", StringComparison.Ordinal));
                path = path.Replace(subtractedPath, string.Empty);
            }

            if (!Directory.Exists(Path.GetFullPath(path)))
            {
                Directory.CreateDirectory(Path.GetFullPath(path));
            }

            string replacedetPathAndName = replacedetDatabase.GenerateUniquereplacedetPath($"{path}/{name}.replacedet");

            replacedetDatabase.Createreplacedet(scriptableObject, replacedetPathAndName);
            replacedetDatabase.Savereplacedets();
            replacedetDatabase.Refresh();
            EditorGUIUtility.PingObject(scriptableObject);
            return scriptableObject;
        }

19 Source : UwpAppxBuildTools.cs
with Apache License 2.0
from abist-co-ltd

private static void UpdateDependenciesElement(XElement dependencies, XNamespace defaultNamespace)
        {
            var values = (PlayerSettings.WSATargetFamily[])Enum.GetValues(typeof(PlayerSettings.WSATargetFamily));

            if (string.IsNullOrWhiteSpace(EditorUserBuildSettings.wsaUWPSDK))
            {
                var windowsSdkPaths = Directory.GetDirectories(@"C:\Program Files (x86)\Windows Kits\10\Lib");

                for (int i = 0; i < windowsSdkPaths.Length; i++)
                {
                    windowsSdkPaths[i] = windowsSdkPaths[i].Substring(windowsSdkPaths[i].LastIndexOf(@"\", StringComparison.Ordinal) + 1);
                }

                EditorUserBuildSettings.wsaUWPSDK = windowsSdkPaths[windowsSdkPaths.Length - 1];
            }

            string maxVersionTested = EditorUserBuildSettings.wsaUWPSDK;

            if (string.IsNullOrWhiteSpace(EditorUserBuildSettings.wsaMinUWPSDK))
            {
                EditorUserBuildSettings.wsaMinUWPSDK = UwpBuildDeployPreferences.MIN_PLATFORM_VERSION.ToString();
            }

            string minVersion = EditorUserBuildSettings.wsaMinUWPSDK;

            // Clear any we had before.
            dependencies.RemoveAll();

            foreach (PlayerSettings.WSATargetFamily family in values)
            {
                if (PlayerSettings.WSA.GetTargetDeviceFamily(family))
                {
                    dependencies.Add(
                        new XElement(defaultNamespace + "TargetDeviceFamily",
                        new XAttribute("Name", $"Windows.{family}"),
                        new XAttribute("MinVersion", minVersion),
                        new XAttribute("MaxVersionTested", maxVersionTested)));
                }
            }

            if (!dependencies.HasElements)
            {
                dependencies.Add(
                    new XElement(defaultNamespace + "TargetDeviceFamily",
                    new XAttribute("Name", "Windows.Universal"),
                    new XAttribute("MinVersion", minVersion),
                    new XAttribute("MaxVersionTested", maxVersionTested)));
            }
        }

19 Source : Color32Extensions.cs
with Apache License 2.0
from abist-co-ltd

public static Color ParseHexcode(string hexstring)
        {
            if (hexstring.StartsWith("#"))
            {
                hexstring = hexstring.Substring(1);
            }

            if (hexstring.StartsWith("0x"))
            {
                hexstring = hexstring.Substring(2);
            }

            if (hexstring.Length == 6)
            {
                hexstring += "FF";
            }

            if (hexstring.Length != 8)
            {
                throw new ArgumentException(string.Format("{0} is not a valid color string.", hexstring));
            }

            byte r = byte.Parse(hexstring.Substring(0, 2), NumberStyles.HexNumber);
            byte g = byte.Parse(hexstring.Substring(2, 2), NumberStyles.HexNumber);
            byte b = byte.Parse(hexstring.Substring(4, 2), NumberStyles.HexNumber);
            byte a = byte.Parse(hexstring.Substring(6, 2), NumberStyles.HexNumber);

            const float maxRgbValue = 255;
            Color c = new Color(r / maxRgbValue, g / maxRgbValue, b / maxRgbValue, a / maxRgbValue);
            return c;
        }

19 Source : TypeReferencePropertyDrawer.cs
with Apache License 2.0
from abist-co-ltd

private static string DrawTypeSelectionControl(Rect position, GUIContent label, string clreplacedRef, SystemTypeAttribute filter, bool typeResolved)
        {
            if (label != null && label != GUIContent.none)
            {
                position = EditorGUI.PrefixLabel(position, label);
            }

            int controlId = GUIUtility.GetControlID(ControlHint, FocusType.Keyboard, position);

            bool triggerDropDown = false;

            switch (Event.current.GetTypeForControl(controlId))
            {
                case EventType.ExecuteCommand:
                    if (Event.current.commandName == "TypeReferenceUpdated")
                    {
                        if (selectionControlId == controlId)
                        {
                            if (clreplacedRef != selectedReference)
                            {
                                clreplacedRef = selectedReference;
                                GUI.changed = true;
                            }

                            selectionControlId = 0;
                            selectedReference = null;
                        }
                    }

                    break;

                case EventType.MouseDown:
                    if (GUI.enabled && position.Contains(Event.current.mousePosition))
                    {
                        GUIUtility.keyboardControl = controlId;
                        triggerDropDown = true;
                        Event.current.Use();
                    }

                    break;

                case EventType.KeyDown:
                    if (GUI.enabled && GUIUtility.keyboardControl == controlId)
                    {
                        if (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.Space)
                        {
                            triggerDropDown = true;
                            Event.current.Use();
                        }
                    }

                    break;

                case EventType.Repaint:
                    // Remove replacedembly name and namespace from content of pop-up control.
                    var clreplacedRefParts = clreplacedRef.Split(',');
                    var clreplacedName = clreplacedRefParts[0].Trim();
                    clreplacedName = clreplacedName.Substring(clreplacedName.LastIndexOf(".", StringComparison.Ordinal) + 1);
                    TempContent.text = clreplacedName;

                    if (TempContent.text == string.Empty)
                    {
                        TempContent.text = "(None)";
                    }
                    else if (!typeResolved)
                    {
                        TempContent.text += " {Missing}";
                    }

                    EditorStyles.popup.Draw(position, TempContent, controlId);
                    break;
            }

            if (triggerDropDown)
            {
                selectionControlId = controlId;
                selectedReference = clreplacedRef;

                DisplayDropDown(position, GetFilteredTypes(filter), ResolveType(clreplacedRef), filter?.Grouping ?? TypeGrouping.ByNamespaceFlat);
            }

            return clreplacedRef;
        }

19 Source : TypeReferencePropertyDrawer.cs
with Apache License 2.0
from abist-co-ltd

private static string FormatGroupedTypeName(Type type, TypeGrouping grouping)
        {
            string name = type.FullName;

            switch (grouping)
            {
                case TypeGrouping.None:
                    return name;
                case TypeGrouping.ByNamespace:
                    return string.IsNullOrEmpty(name) ? string.Empty : name.Replace('.', '/');
                case TypeGrouping.ByNamespaceFlat:
                    int lastPeriodIndex = string.IsNullOrEmpty(name) ? -1 : name.LastIndexOf('.');
                    if (lastPeriodIndex != -1)
                    {
                        name = string.IsNullOrEmpty(name)
                            ? string.Empty
                            : $"{name.Substring(0, lastPeriodIndex)}/{name.Substring(lastPeriodIndex + 1)}";
                    }

                    return name;
                case TypeGrouping.ByAddComponentMenu:
                    var addComponentMenuAttributes = type.GetCustomAttributes(typeof(AddComponentMenu), false);
                    if (addComponentMenuAttributes.Length == 1)
                    {
                        return ((AddComponentMenu)addComponentMenuAttributes[0]).componentMenu;
                    }

                    Debug.replacedert(type.FullName != null);
                    return $"Scripts/{type.FullName.Replace('.', '/')}";
                default:
                    throw new ArgumentOutOfRangeException(nameof(grouping), grouping, null);
            }
        }

19 Source : UnityPlayerBuildTools.cs
with Apache License 2.0
from abist-co-ltd

public static void ParseBuildCommandLine(ref IBuildInfo buildInfo)
        {
            string[] arguments = Environment.GetCommandLineArgs();

            for (int i = 0; i < arguments.Length; ++i)
            {
                switch (arguments[i])
                {
                    case "-autoIncrement":
                        buildInfo.AutoIncrement = true;
                        break;
                    case "-sceneList":
                        buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(arguments[++i]));
                        break;
                    case "-sceneListFile":
                        string path = arguments[++i];
                        if (File.Exists(path))
                        {
                            buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(File.ReadAllText(path)));
                        }
                        else
                        {
                            Debug.LogWarning($"Scene list file at '{path}' does not exist.");
                        }
                        break;
                    case "-buildOutput":
                        buildInfo.OutputDirectory = arguments[++i];
                        break;
                    case "-colorSpace":
                        buildInfo.ColorSpace = (ColorSpace)Enum.Parse(typeof(ColorSpace), arguments[++i]);
                        break;
                    case "-scriptingBackend":
                        buildInfo.ScriptingBackend = (ScriptingImplementation)Enum.Parse(typeof(ScriptingImplementation), arguments[++i]);
                        break;
                    case "-x86":
                    case "-x64":
                    case "-arm":
                    case "-arm64":
                        buildInfo.BuildPlatform = arguments[i].Substring(1);
                        break;
                    case "-debug":
                    case "-master":
                    case "-release":
                        buildInfo.Configuration = arguments[i].Substring(1).ToLower();
                        break;
                    case "-logDirectory":
                        buildInfo.LogDirectory = arguments[++i];
                        break;
                }
            }
        }

19 Source : MixedRealityToolkitFiles.cs
with Apache License 2.0
from abist-co-ltd

private static string ResolveFullreplacedetsPath(string path)
        {
            if (path.StartsWith("replacedets"))
            {
                // replacedet.Substring(6) represents the characters after the "replacedets" string.
                return Application.dataPath + path.Substring(6);
            }
            return path;
        }

19 Source : MixedRealityToolkitFiles.cs
with Apache License 2.0
from abist-co-ltd

public static MixedRealityToolkitModuleType GetModuleFromPackageFolder(string packageFolder)
        {
            if (!packageFolder.StartsWith("MixedRealityToolkit"))
            {
                // There are no mappings for folders that do not start with "MixedRealityToolkit"
                return MixedRealityToolkitModuleType.None;
            }

            int separatorIndex = packageFolder.IndexOf('.');
            packageFolder = (separatorIndex != -1) ? packageFolder.Substring(separatorIndex + 1) : "Core";

            MixedRealityToolkitModuleType moduleType;
            return moduleNameMap.TryGetValue(packageFolder, out moduleType) ? moduleType : MixedRealityToolkitModuleType.None;
        }

19 Source : NumberParse.cs
with MIT License
from abock

static (string str, int @base, bool negate) Configure(string str)
        {
            str = str.Trim();

            var negate = false;
            if (str.Length > 0 && str[0] == '-')
            {
                negate = true;
                str = str.Substring(1);
            }

            str = strip.Replace(str, string.Empty);

            int @base = 10;

            if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                @base = 16;
                str = str.Substring(2);
            }
            else if (str.EndsWith("h", StringComparison.OrdinalIgnoreCase))
            {
                @base = 16;
                str = str.Substring(0, str.Length - 1);
            }
            else if (str.StartsWith("0b", StringComparison.OrdinalIgnoreCase))
            {
                @base = 2;
                str = str.Substring(2);
            }

            return (str, @base, negate);
        }

19 Source : Program.cs
with MIT License
from abock

static int Main(string[] args)
        {
            bool showVersion = false;
            int numberOfIds = 1;

            var firstArg = args.FirstOrDefault();
            if (string.IsNullOrEmpty(firstArg) || firstArg[0] == '-' || firstArg[0] == '/')
            {
                switch (firstArg?.Substring(1).ToLowerInvariant())
                {
                    case "h":
                    case "?":
                    case "help":
                    case "-help":
                        break;
                    default:
                        args = new[] { "v4" }
                            .Concat(args)
                            .ToArray();
                        break;
                }
            }

            var suite = new CommandSet("idgen")
            {
                { "Usage: idgen COMMAND [OPTIONS]+" },
                { "" },
                { $"  idgen v{version}" },
                { $"  https://github.com/abock/idgen"},
                { $"  {copyright}"},
                { "" },
                { "OPTIONS:" },
                { "" },
                {
                    "h|?|help",
                    "Show this help.",
                    v => { }
                },
                {
                    "V|version",
                    "Show the idgen version.",
                    v => showVersion = true
                },
                {
                    "n=",
                    "Generate {NUMBER} of identifiers", v =>
                    {
                        if (!NumberParse.TryParse (v, out numberOfIds) || numberOfIds < 0)
                            throw new Exception (
                                "NUMBER must be a positive integer, or zero, for the -number option.");
                    }
                },
                { "" },
                { "COMMANDS:" },
                { "" }
            };

            var generators = new IIdGenerator[]
            {
                new GuidGenerator.V4 (),
                new GuidGenerator.V5 (),
                new GuidGenerator.V3 (),
                new NanoidGenerator (),
                new HashidsGenerator (),
                new XcodeIdGenerator (),
                new PhoneGenerator ()
            };

            foreach (var generator in generators)
            {
                var hasOptions = generator.Options?.Any(o => !string.IsNullOrEmpty(o.Prototype)) ?? false;

                var usageLine = hasOptions ? "[OPTIONS]+" : null;

                if (!string.IsNullOrEmpty(generator.UsageArguments))
                {
                    if (usageLine != null)
                        usageLine += " ";
                    usageLine += generator.UsageArguments;
                }

                if (usageLine != null)
                    usageLine = " " + usageLine;

                var optionSet = new OptionSet
                {
                    { $"Usage: {suite.Suite} {generator.Command}{usageLine}" },
                };

                if (hasOptions)
                {
                    optionSet.Add("");
                    optionSet.Add("OPTIONS:");
                    optionSet.Add("");

                    foreach (Option option in generator.Options)
                        optionSet.Add(option);
                }

                suite.Add(new Command(generator.Command, generator.CommandDescription)
                {
                    Options = optionSet,
                    Run = commandArgs => RunCommand(generator, commandArgs)
                });
            }

            void RunCommand(IIdGenerator generator, IEnumerable<string> commandArgs)
            {
                if (showVersion)
                {
                    Console.WriteLine(version);
                    return;
                }

                for (int i = 0; i < numberOfIds; i++)
                {
                    foreach (var id in generator.Generate(commandArgs))
                    {
                        if (id != null)
                            Console.WriteLine(id);
                    }
                }
            }

            suite.Add(
                "\n" +
                "NOTE: any argument that expects a number my be specified in decimal, " +
                "binary (0b1001), or hex (0xabcd and ab123h) notation. Numbers may " +
                "also contain digit separators (_ and ,) and arbitrary whitespace.");

            try
            {
                suite.Run(args);
            }
            catch (Exception e)
            {
                Error(e.Message);
                return 2;
            }

            return 0;
        }

19 Source : AudioManager.cs
with MIT License
from absurd-joy

static public string NameMinusGroup( string name ) {
		if ( name.IndexOf( "/" ) > -1 ) {
			return name.Substring( name.IndexOf( "/" ) + 1 );
		}
		return name;
	}

19 Source : OculusPlatformSettingsEditor.cs
with MIT License
from absurd-joy

public static void EnforcePluginPlatformSettings(PluginPlatform platform)
    {
      string path = GetPlatformPluginPath(platform);

      if (!Directory.Exists(path) && !File.Exists(path))
      {
        path += PluginDisabledSuffix;
      }

      if ((Directory.Exists(path)) || (File.Exists(path)))
      {
        string basePath = GetCurrentProjectPath();
        string relPath = path.Substring(basePath.Length + 1);

        PluginImporter pi = PluginImporter.GetAtPath(relPath) as PluginImporter;
        if (pi == null)
        {
          return;
        }

        // Disable support for all platforms, then conditionally enable desired support below
        pi.SetCompatibleWithEditor(false);
        pi.SetCompatibleWithAnyPlatform(false);
        pi.SetCompatibleWithPlatform(BuildTarget.Android, false);
        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false);
        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false);
        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false);
#if !UNITY_2019_2_OR_NEWER
        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false);
        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false);
#endif
#if UNITY_2017_3_OR_NEWER
        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, false);
#else
        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false);
        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false);
        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false);
#endif

        switch (platform)
        {
          case PluginPlatform.Android32:
            pi.SetCompatibleWithPlatform(BuildTarget.Android, true);
            pi.SetPlatformData(BuildTarget.Android, "CPU", "ARMv7");
            break;
          case PluginPlatform.Android64:
            pi.SetCompatibleWithPlatform(BuildTarget.Android, true);
            pi.SetPlatformData(BuildTarget.Android, "CPU", "ARM64");
            break;
          default:
            throw new ArgumentException("Attempted to enable platform support for unsupported platform: " + platform);
        }

        replacedetDatabase.Importreplacedet(relPath, ImportreplacedetOptions.ForceUpdate);
        replacedetDatabase.Savereplacedets();
        replacedetDatabase.Refresh();
        replacedetDatabase.Savereplacedets();
      }
    }

19 Source : OculusPlatformSettingsEditor.cs
with MIT License
from absurd-joy

public static void DisablePluginPlatform(PluginPlatform platform)
    {
      string path = GetPlatformPluginPath(platform);
      string disabledPath = path + PluginDisabledSuffix;

      bool pathDoesNotExist = !Directory.Exists(path) && !File.Exists(path);
      bool disabledPathAlreadyExists = Directory.Exists(disabledPath) || File.Exists(disabledPath);

      if (pathDoesNotExist || disabledPathAlreadyExists)
      {
        return;
      }

      string basePath = GetCurrentProjectPath();
      string relPath = path.Substring(basePath.Length + 1);
      string relDisabledPath = relPath + PluginDisabledSuffix;

      replacedetDatabase.Movereplacedet(relPath, relDisabledPath);
      replacedetDatabase.Importreplacedet(relDisabledPath, ImportreplacedetOptions.ForceUpdate);
      replacedetDatabase.Savereplacedets();
      replacedetDatabase.Refresh();
      replacedetDatabase.Savereplacedets();
    }

19 Source : OVRPluginUpdater.cs
with MIT License
from absurd-joy

private static void DisableAllUtilitiesPluginPackages()
	{
		List<PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();

		foreach(PluginPackage pluginPkg in allUtilsPluginPkgs)
		{
			foreach(string path in pluginPkg.Plugins.Values)
			{
				if ((Directory.Exists(path)) || (File.Exists(path)))
				{
					string basePath = GetCurrentProjectPath();
					string relPath = path.Substring(basePath.Length + 1);
					string relDisabledPath = relPath + GetDisabledPluginSuffix();

					replacedetDatabase.Movereplacedet(relPath, relDisabledPath);
					replacedetDatabase.Importreplacedet(relDisabledPath, ImportreplacedetOptions.ForceUpdate);
				}
			}
		}

		replacedetDatabase.Refresh();
		replacedetDatabase.Savereplacedets();
	}

19 Source : OVRPluginUpdater.cs
with MIT License
from absurd-joy

private static void EnablePluginPackage(PluginPackage pluginPkg)
	{
		foreach(var kvp in pluginPkg.Plugins)
		{
			PluginPlatform platform = kvp.Key;
			string path = kvp.Value;

			if ((Directory.Exists(path + GetDisabledPluginSuffix())) || (File.Exists(path + GetDisabledPluginSuffix())))
			{
				string basePath = GetCurrentProjectPath();
				string relPath = path.Substring(basePath.Length + 1);
				string relDisabledPath = relPath + GetDisabledPluginSuffix();

				replacedetDatabase.Movereplacedet(relDisabledPath, relPath);
				replacedetDatabase.Importreplacedet(relPath, ImportreplacedetOptions.ForceUpdate);

				PluginImporter pi = PluginImporter.GetAtPath(relPath) as PluginImporter;
				if (pi == null)
				{
					continue;
				}

				// Disable support for all platforms, then conditionally enable desired support below
				pi.SetCompatibleWithEditor(false);
				pi.SetCompatibleWithAnyPlatform(false);
				pi.SetCompatibleWithPlatform(BuildTarget.Android, false);
				pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false);
				pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false);
				pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, false);

				switch (platform)
				{
					case PluginPlatform.Android:
						pi.SetCompatibleWithPlatform(BuildTarget.Android, !unityVersionSupportsAndroidUniversal);
						if (!unityVersionSupportsAndroidUniversal)
						{
							pi.SetPlatformData(BuildTarget.Android, "CPU", "ARMv7");
						}
						break;
					case PluginPlatform.AndroidUniversal:
						pi.SetCompatibleWithPlatform(BuildTarget.Android, unityVersionSupportsAndroidUniversal);
						break;
					case PluginPlatform.OSXUniversal:
						pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, true);
						pi.SetCompatibleWithEditor(true);
						pi.SetEditorData("CPU", "AnyCPU");
						pi.SetEditorData("OS", "OSX");
						pi.SetPlatformData("Editor", "CPU", "AnyCPU");
						pi.SetPlatformData("Editor", "OS", "OSX");
						break;
					case PluginPlatform.Win:
						pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, true);
						pi.SetCompatibleWithEditor(true);
						pi.SetEditorData("CPU", "X86");
						pi.SetEditorData("OS", "Windows");
						pi.SetPlatformData("Editor", "CPU", "X86");
						pi.SetPlatformData("Editor", "OS", "Windows");
						break;
					case PluginPlatform.Win64:
						pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, true);
						pi.SetCompatibleWithEditor(true);
						pi.SetEditorData("CPU", "X86_64");
						pi.SetEditorData("OS", "Windows");
						pi.SetPlatformData("Editor", "CPU", "X86_64");
						pi.SetPlatformData("Editor", "OS", "Windows");
						break;
					default:
						throw new ArgumentException("Attempted EnablePluginPackage() for unsupported BuildTarget: " + platform);
				}

				replacedetDatabase.Importreplacedet(relPath, ImportreplacedetOptions.ForceUpdate);
			}
		}

		replacedetDatabase.Refresh();
		replacedetDatabase.Savereplacedets();
	}

19 Source : OculusPlatformSettingsEditor.cs
with MIT License
from absurd-joy

public static void EnablePluginPlatform(PluginPlatform platform)
    {
      string path = GetPlatformPluginPath(platform);
      string disabledPath = path + PluginDisabledSuffix;

      bool pathAlreadyExists = Directory.Exists(path) || File.Exists(path);
      bool disabledPathDoesNotExist = !Directory.Exists(disabledPath) && !File.Exists(disabledPath);

      if (pathAlreadyExists || disabledPathDoesNotExist)
      {
        return;
      }

      string basePath = GetCurrentProjectPath();
      string relPath = path.Substring(basePath.Length + 1);
      string relDisabledPath = relPath + PluginDisabledSuffix;

      replacedetDatabase.Movereplacedet(relDisabledPath, relPath);
      replacedetDatabase.Importreplacedet(relPath, ImportreplacedetOptions.ForceUpdate);
      replacedetDatabase.Savereplacedets();
      replacedetDatabase.Refresh();
      replacedetDatabase.Savereplacedets();

      // Force reserialization of platform settings meta data
      EnforcePluginPlatformSettings(platform);
    }

19 Source : OVRPluginUpdater.cs
with MIT License
from absurd-joy

public bool IsAndroidUniversalEnabled()
		{
			string path = "";
			if (Plugins.TryGetValue(PluginPlatform.AndroidUniversal, out path))
			{
				if (File.Exists(path))
				{
					string basePath = GetCurrentProjectPath();
					string relPath = path.Substring(basePath.Length + 1);

					PluginImporter pi = PluginImporter.GetAtPath(relPath) as PluginImporter;
					if (pi != null)
					{
						return pi.GetCompatibleWithPlatform(BuildTarget.Android);
					}
				}
			}

			return false;
		}

19 Source : XamlInlineFormatter.cs
with MIT License
from ABTSoftware

public void Write(string parsedSourceCode,
                          IList<Scope> scopes,
                          IStyleSheet styleSheet)
        {
            int offset = 0;
            bool lastScopeWasComment = false;

            foreach (Scope scope in scopes)
            {
                string t = parsedSourceCode.Substring(scope.Index, scope.Length);
//                    .Replace("\r\n", "\n")
//                    .Replace("\r", "\n");
                offset = scope.Index + scope.Length;
                if (!string.IsNullOrEmpty(t))
                {
                    if(scope.Name == "XML Attribute")
                    {
                        //Add space before attributes
                        t = t.Insert(0, " ");
                    }

                    Inline run = new Run { Text = t.Replace("\r",string.Empty) };
                    if (scope != null && styleSheet.Styles.Contains(scope.Name))
                    {
                        Style style = styleSheet.Styles[scope.Name];
                        run.Foreground = new SolidColorBrush(style.Foreground);
                    }
                    lastScopeWasComment = (scope != null && scope.Name == "Comment");
                    _text.Inlines.Add(run);
                }
            }
            string left = parsedSourceCode
                .Substring(offset)
                .Replace("\r\n", "\n")
                .Replace("\r", "\n");
            if (!string.IsNullOrEmpty(left))
            {
                for (int i = left.IndexOf("\n"); i >= 0; i = left.IndexOf("\n"))
                {
                    if (i > 0)
                    {
                        Inline tby = new Run { Text = left.Substring(0, i) };
                        _text.Inlines.Add(tby);
                    }

                    left = left.Substring(i + 1);
                    if (lastScopeWasComment)
                    {
                        lastScopeWasComment = false;
                    }
                    else
                    {
                        _text.Inlines.Add(new LineBreak());
                    }
                }

                if (!string.IsNullOrEmpty(left))
                {
                    Inline nrun = new Run { Text = left };
                    _text.Inlines.Add(nrun);
                }
            }
        }

19 Source : LanguageParser.cs
with MIT License
from ABTSoftware

private void AppendCapturedStylesForRegexCapture(Capture regexCapture,
                                                         int currentIndex,
                                                         string styleName,
                                                         ICollection<Scope> capturedStyles)
        {
            if (styleName.StartsWith(ScopeName.LanguagePrefix))
            {
                string nestedGrammarId = styleName.Substring(1);
                AppendCapturedStylesForNestedLanguage(regexCapture, regexCapture.Index - currentIndex, nestedGrammarId, capturedStyles);
            }
            else
                capturedStyles.Add(new Scope(styleName, regexCapture.Index - currentIndex, regexCapture.Length));
        }

19 Source : Example.cs
with MIT License
from ABTSoftware

private void LoadCode()
        {
            try
            {
                _sourceFilePaths.ForEach(file =>
                {
                    var index = file.LastIndexOf('/') + 1;
                    var fileName = file.Substring(index).Replace(".txt", String.Empty);
                    _sourceFiles[fileName] = ExampleLoader.LoadSourceFile(file);
                });
            }
            catch (Exception ex)
            {                
                throw new Exception(string.Format("An error occurred when parsing the source-code files for Example '{0}'", replacedle), ex);
            }
        }

19 Source : LanguageParser.cs
with MIT License
from ABTSoftware

private void Parse(string sourceCode,
                           CompiledLanguage compiledLanguage,
                           Action<string, IList<Scope>> parseHandler)
        {
            Match regexMatch = compiledLanguage.Regex.Match(sourceCode);

            if (!regexMatch.Success)
                parseHandler(sourceCode, new List<Scope>());
            else
            {
                int currentIndex = 0;

                while (regexMatch.Success)
                {
                    string sourceCodeBeforeMatch = sourceCode.Substring(currentIndex, regexMatch.Index - currentIndex);
                    if (!string.IsNullOrEmpty(sourceCodeBeforeMatch))
                        parseHandler(sourceCodeBeforeMatch, new List<Scope>());

                    string matchedSourceCode = sourceCode.Substring(regexMatch.Index, regexMatch.Length);
                    if (!string.IsNullOrEmpty(matchedSourceCode))
                    {
                        List<Scope> capturedStylesForMatchedFragment = GetCapturedStyles(regexMatch, regexMatch.Index, compiledLanguage);
                        List<Scope> capturedStyleTree = CreateCapturedStyleTree(capturedStylesForMatchedFragment);
                        parseHandler(matchedSourceCode, capturedStyleTree);
                    }

                    currentIndex = regexMatch.Index + regexMatch.Length;
                    regexMatch = regexMatch.NextMatch();
                }

                string sourceCodeAfterAllMatches = sourceCode.Substring(currentIndex);
                if (!string.IsNullOrEmpty(sourceCodeAfterAllMatches))
                    parseHandler(sourceCodeAfterAllMatches, new List<Scope>());
            }
        }

19 Source : HighlightTextBlock.cs
with MIT License
from Accelerider

private static IEnumerable<(string fragment, bool isQuery)> SplitTextByOrderedDisjointIntervals(string sourceText, List<(int start, int end)> mergedIntervals)
        {
            if (string.IsNullOrEmpty(sourceText)) yield break;

            if (!mergedIntervals?.Any() ?? true)
            {
                yield return (sourceText, false);
                yield break;
            }

            (int start0, int end0) = mergedIntervals.First();

            if (start0 > 0) yield return (sourceText.Substring(0, start0), false);
            yield return (sourceText.Substring(start0, end0 - start0), true);
              
            int previousEnd = end0;
            foreach ((int start, int end) in mergedIntervals.Skip(1))
            {
                yield return (sourceText.Substring(previousEnd, start - previousEnd), false);
                yield return (sourceText.Substring(start, end - start), true);
                previousEnd = end;
            }

            if (previousEnd < sourceText.Length)
                yield return (sourceText.Substring(previousEnd), false);
        }

19 Source : StringExtensions.cs
with MIT License
from Accelerider

public static string TrimMiddle(this string @this, int limitLength, string omitPlaceholder = null)
        {
            const string defaultOmitPlaceholder = "...";

            if (omitPlaceholder == null) omitPlaceholder = defaultOmitPlaceholder;
            Guards.ThrowIfNot(limitLength >= omitPlaceholder.Length);

            if (string.IsNullOrEmpty(@this) || @this.Length <= limitLength) return @this;

            if (limitLength == omitPlaceholder.Length) return omitPlaceholder;

            var halfLength = (limitLength - omitPlaceholder.Length) / 2;
            var bias = (limitLength - omitPlaceholder.Length) % 2;

            var firstHalfString = @this.Substring(0, halfLength + bias);
            var secondHalfString = @this.Substring(@this.Length - halfLength);

            return $"{firstHalfString}{omitPlaceholder}{secondHalfString}";
        }

19 Source : StringExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static string TrimStart(this string result, string trimStart)
        {
            if (result.StartsWith(trimStart, StringComparison.OrdinalIgnoreCase))
                result = result.Substring(trimStart.Length);

            return result;
        }

19 Source : FileLocatorExtensions.cs
with MIT License
from Accelerider

public static FileType GetFileType(this FileLocator fileLocator)
		{
			if (fileLocator == null || string.IsNullOrWhiteSpace(fileLocator.FileName)) return default;
			var extension = Path.GetExtension(fileLocator.FileName);

			var fileExtension = string.IsNullOrEmpty(extension) ? string.Empty : extension.Substring(1);
			return (from item in FileTypeMapping where item.Value.Contains(fileExtension) select item.Key).FirstOrDefault();
		}

19 Source : SpellComponentsTable.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static string GetSpellWords(SpellComponentsTable comps, List<uint> formula)
        {
            string firstSpellWord = "";
            string secondSpellWord = "";
            string thirdSpellWord = "";

            if (formula == null) return "";

            // Locate the herb component in the Spell formula
            for (int i = 0; i < formula.Count; i++)
            {
                if (comps.SpellComponents[formula[i]].Type == (uint)Type.Herb)
                    firstSpellWord = comps.SpellComponents[formula[i]].Text;
            }

            // Locate the powder component in the Spell formula
            for (int i = 0; i < formula.Count; i++)
            {
                if (comps.SpellComponents[formula[i]].Type == (uint)Type.Powder)
                    secondSpellWord = comps.SpellComponents[formula[i]].Text;
            }

            // Locate the potion component in the Spell formula
            for (int i = 0; i < formula.Count; i++)
            {
                if (comps.SpellComponents[formula[i]].Type == (uint)Type.Potion)
                    thirdSpellWord = comps.SpellComponents[formula[i]].Text;
            }

            // We need to make sure our second spell word, if any, is capitalized
            // Some spell words have no "secondSpellWord", so we're basically making sure the third word is capitalized.
            string secondSpellWordSet = (secondSpellWord + thirdSpellWord.ToLower());
            if(secondSpellWordSet != "")
            {
                string firstLetter = secondSpellWordSet.Substring(0, 1).ToUpper();
                secondSpellWordSet = firstLetter + secondSpellWordSet.Substring(1);

            }

            string result = $"{firstSpellWord} {secondSpellWordSet}";
            return result.Trim();
        }

19 Source : ConsoleCommands.cs
with GNU Affero General Public License v3.0
from ACEmulator

[CommandHandler("image-export", AccessLevel.Admin, CommandHandlerFlag.ConsoleInvoke, 0, "Export Texture/Image Files")]
        public static void ExportImageFile(Session session, params string[] parameters)
        {
            string syntax = "image-export <export-directory-without-spaces> [id]";
            if (parameters?.Length < 1)
            {
                Console.WriteLine(syntax);
                return;
            }

            string exportDir = parameters[0];
            if (exportDir.Length == 0 || !System.IO.Directory.Exists(exportDir))
            {
                Console.WriteLine(syntax);
                return;
            }

            if (parameters.Length > 1)
            {
                uint imageId;
                if (parameters[1].StartsWith("0x"))
                {
                    string hex = parameters[1].Substring(2);
                    if (!uint.TryParse(hex, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.CurrentCulture, out imageId))
                    {
                        Console.WriteLine(syntax);
                        return;
                    }
                }
                else
                if (!uint.TryParse(parameters[1], out imageId))
                {
                    Console.WriteLine(syntax);
                    return;
                }

                var image = DatManager.PortalDat.ReadFromDat<Texture>(imageId);
                image.ExportTexture(exportDir);

                Console.WriteLine($"Exported " + imageId.ToString("X8") + " to " + exportDir + ".");
            }
            else
            {
                int portalFiles = 0;
                int highresFiles = 0;
                Console.WriteLine($"Exporting client_portal.dat textures and images to {exportDir}.  This may take a while.");
                foreach (KeyValuePair<uint, DatFile> entry in DatManager.PortalDat.AllFiles)
                {
                    if (entry.Value.GetFileType(DatDatabaseType.Portal) == DatFileType.Texture)
                    {
                        var image = DatManager.PortalDat.ReadFromDat<Texture>(entry.Value.ObjectId);
                        image.ExportTexture(exportDir);
                        portalFiles++;
                    }
                }
                Console.WriteLine($"Exported {portalFiles} total files from client_portal.dat to {exportDir}.");

                if (DatManager.HighResDat != null)
                {
                    foreach (KeyValuePair<uint, DatFile> entry in DatManager.HighResDat.AllFiles)
                    {
                        if (entry.Value.GetFileType(DatDatabaseType.Portal) == DatFileType.Texture)
                        {
                            var image = DatManager.HighResDat.ReadFromDat<Texture>(entry.Value.ObjectId);
                            image.ExportTexture(exportDir);
                            highresFiles++;
                        }
                    }
                    Console.WriteLine($"Exported {highresFiles} total files from client_highres.dat to {exportDir}.");
                }
                int totalFiles = portalFiles + highresFiles;
                Console.WriteLine($"Exported {totalFiles} total files to {exportDir}.");
            }
        }

19 Source : PlayerCommands.cs
with GNU Affero General Public License v3.0
from ACEmulator

[CommandHandler("reportbug", AccessLevel.Player, CommandHandlerFlag.RequiresWorld, 2,
            "Generate a Bug Report",
            "<category> <description>\n" +
            "This command generates a URL for you to copy and paste into your web browser to submit for review by server operators and developers.\n" +
            "Category can be the following:\n" +
            "Creature\n" +
            "NPC\n" +
            "Item\n" +
            "Quest\n" +
            "Recipe\n" +
            "Landblock\n" +
            "Mechanic\n" +
            "Code\n" +
            "Other\n" +
            "For the first three options, the bug report will include identifiers for what you currently have selected/targeted.\n" +
            "After category, please include a brief description of the issue, which you can further detail in the report on the website.\n" +
            "Examples:\n" +
            "/reportbug creature Drudge Prowler is over powered\n" +
            "/reportbug npc Ulgrim doesn't know what to do with Sake\n" +
            "/reportbug quest I can't enter the portal to the Lost City of Frore\n" +
            "/reportbug recipe I cannot combine Bundle of Arrowheads with Bundle of Arrowshafts\n" +
            "/reportbug code I was killed by a Non-Player Killer\n"
            )]
        public static void HandleReportbug(Session session, params string[] parameters)
        {
            if (!PropertyManager.GetBool("reportbug_enabled").Item)
            {
                session.Network.EnqueueSend(new GameMessageSystemChat("The command \"reportbug\" is not currently enabled on this server.", ChatMessageType.Broadcast));
                return;
            }

            var category = parameters[0];
            var description = "";

            for (var i = 1; i < parameters.Length; i++)
                description += parameters[i] + " ";

            description.Trim();

            switch (category.ToLower())
            {
                case "creature":
                case "npc":
                case "quest":
                case "item":
                case "recipe":
                case "landblock":
                case "mechanic":
                case "code":
                case "other":
                    break;
                default:
                    category = "Other";
                    break;
            }

            var sn = ConfigManager.Config.Server.WorldName;
            var c = session.Player.Name;

            var st = "ACE";

            //var versions = ServerBuildInfo.GetVersionInfo();
            var databaseVersion = DatabaseManager.World.GetVersion();
            var sv = ServerBuildInfo.FullVersion;
            var pv = databaseVersion.PatchVersion;

            //var ct = PropertyManager.GetString("reportbug_content_type").Item;
            var cg = category.ToLower();

            var w = "";
            var g = "";

            if (cg == "creature" || cg == "npc"|| cg == "item" || cg == "item")
            {
                var objectId = new ObjectGuid();
                if (session.Player.HealthQueryTarget.HasValue || session.Player.ManaQueryTarget.HasValue || session.Player.CurrentAppraisalTarget.HasValue)
                {
                    if (session.Player.HealthQueryTarget.HasValue)
                        objectId = new ObjectGuid((uint)session.Player.HealthQueryTarget);
                    else if (session.Player.ManaQueryTarget.HasValue)
                        objectId = new ObjectGuid((uint)session.Player.ManaQueryTarget);
                    else
                        objectId = new ObjectGuid((uint)session.Player.CurrentAppraisalTarget);

                    //var wo = session.Player.CurrentLandblock?.GetObject(objectId);

                    var wo = session.Player.FindObject(objectId.Full, Player.SearchLocations.Everywhere);

                    if (wo != null)
                    {
                        w = $"{wo.WeenieClreplacedId}";
                        g = $"0x{wo.Guid:X8}";
                    }
                }
            }

            var l = session.Player.Location.ToLOCString();

            var issue = description;

            var urlbase = $"https://www.accpp.net/bug?";

            var url = urlbase;
            if (sn.Length > 0)
                url += $"sn={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sn))}";
            if (c.Length > 0)
                url += $"&c={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(c))}";
            if (st.Length > 0)
                url += $"&st={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(st))}";
            if (sv.Length > 0)
                url += $"&sv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sv))}";
            if (pv.Length > 0)
                url += $"&pv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(pv))}";
            //if (ct.Length > 0)
            //    url += $"&ct={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ct))}";
            if (cg.Length > 0)
            {
                if (cg == "npc")
                    cg = cg.ToUpper();
                else
                    cg = char.ToUpper(cg[0]) + cg.Substring(1);
                url += $"&cg={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cg))}";
            }
            if (w.Length > 0)
                url += $"&w={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(w))}";
            if (g.Length > 0)
                url += $"&g={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(g))}";
            if (l.Length > 0)
                url += $"&l={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(l))}";
            if (issue.Length > 0)
                url += $"&i={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(issue))}";

            var msg = "\n\n\n\n";
            msg += "Bug Report - Copy and Paste the following URL into your browser to submit a bug report\n";
            msg += "-=-\n";
            msg += $"{url}\n";
            msg += "-=-\n";
            msg += "\n\n\n\n";

            session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.AdminTell));
        }

19 Source : SentinelCommands.cs
with GNU Affero General Public License v3.0
from ACEmulator

[CommandHandler("boot", AccessLevel.Sentinel, CommandHandlerFlag.None, 2,
            "Boots the character out of the game.",
            "[account | char | iid] who (, reason) \n"
            + "This command boots the specified character out of the game. You can specify who to boot by account, character name, or player instance id. 'who' is the account / character / instance id to actually boot. You can optionally include a reason for the boot.\n"
            + "Example: @boot char Character Name\n"
            + "         @boot account AccountName\n"
            + "         @boot iid 0x51234567\n"
            + "         @boot char Character Name, Reason for being booted\n")]
        public static void HandleBoot(Session session, params string[] parameters)
        {
            // usage: @boot { account,char, iid} who
            // This command boots the specified character out of the game.You can specify who to boot by account, character name, or player instance id.  'who' is the account / character / instance id to actually boot.
            // @boot - Boots the character out of the game.

            var whomToBoot = parameters[1];
            string specifiedReason = null;

            if (parameters.Length > 1)
            {
                var parametersAfterBootType = "";
                for (var i = 1; i < parameters.Length; i++)
                {
                    parametersAfterBootType += parameters[i] + " ";
                }
                parametersAfterBootType = parametersAfterBootType.Trim();
                var completeBootNamePlusCommaSeperatedReason = parametersAfterBootType.Split(",");
                whomToBoot = completeBootNamePlusCommaSeperatedReason[0].Trim();
                if (completeBootNamePlusCommaSeperatedReason.Length > 1)
                    specifiedReason = parametersAfterBootType.Replace($"{whomToBoot},", "").Trim();
            }

            string whatToBoot = null;
            Session sessionToBoot = null;
            switch (parameters[0].ToLower())
            {
                case "char":
                    whatToBoot = "character";
                    sessionToBoot = PlayerManager.GetOnlinePlayer(whomToBoot)?.Session;
                    break;
                case "account":
                    whatToBoot = "account";
                    sessionToBoot = NetworkManager.Find(whomToBoot);
                    break;
                case "iid":
                    whatToBoot = "instance id";
                    if (!whomToBoot.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                    {
                        CommandHandlerHelper.WriteOutputInfo(session, $"That is not a valid Instance ID (IID). IIDs must be between 0x{ObjectGuid.PlayerMin:X8} and 0x{ObjectGuid.PlayerMax:X8}", ChatMessageType.Broadcast);
                        return;
                    }    
                    if (uint.TryParse(whomToBoot.Substring(2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var iid))
                    {
                        sessionToBoot = PlayerManager.GetOnlinePlayer(iid)?.Session;
                    }
                    else
                    {
                        CommandHandlerHelper.WriteOutputInfo(session, $"That is not a valid Instance ID (IID). IIDs must be between 0x{ObjectGuid.PlayerMin:X8} and 0x{ObjectGuid.PlayerMax:X8}", ChatMessageType.Broadcast);
                        return;
                    }
                    break;
                default:
                    CommandHandlerHelper.WriteOutputInfo(session, "You must specify what you are booting with char, account, or iid as the first parameter.", ChatMessageType.Broadcast);
                    return;
            }

            if (sessionToBoot == null)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Cannot boot \"{whomToBoot}\" because that {whatToBoot} is not currently online or cannot be found. Check syntax/spelling and try again.", ChatMessageType.Broadcast);
                return;
            }

            // Boot the player
            var bootText = $"Booting {whatToBoot} {whomToBoot}.{(specifiedReason != null ? $" Reason: {specifiedReason}" : "")}";
            CommandHandlerHelper.WriteOutputInfo(session, bootText, ChatMessageType.Broadcast);
            sessionToBoot.Terminate(SessionTerminationReason.AccountBooted, new GameMessageBootAccount($"{(specifiedReason != null ? $" - {specifiedReason}" : null)}"), null, specifiedReason);
            //CommandHandlerHelper.WriteOutputInfo(session, $"...Result: Success!", ChatMessageType.Broadcast);

            PlayerManager.BroadcastToAuditChannel(session?.Player, bootText);
        }

19 Source : CommandManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void ParseCommand(string commandLine, out string command, out string[] parameters)
        {
            if (commandLine == "/" || commandLine == "")
            {
                command = null;
                parameters = null;
                return;
            }
            var commandSplit = commandLine.Split(' ',StringSplitOptions.RemoveEmptyEntries);
            command = commandSplit[0];

            // remove leading '/' or '@' if erroneously entered in console
            if(command.StartsWith("/") || command.StartsWith("@"))
                command = command.Substring(1);

            parameters = new string[commandSplit.Length - 1];

            Array.Copy(commandSplit, 1, parameters, 0, commandSplit.Length - 1);

            if (commandLine.Contains("\""))
            {
                var listParameters = new List<string>();

                for (int start = 0; start < parameters.Length; start++)
                {
                    if (!parameters[start].StartsWith("\"") || parameters[start].EndsWith("\"")) // Make sure we catch parameters like: "someParam"
                        listParameters.Add(parameters[start].Replace("\"", ""));
                    else
                    {
                        listParameters.Add(parameters[start].Replace("\"", ""));
                        for (int end = start + 1; end < parameters.Length; end++)
                        {
                            if (!parameters[end].EndsWith("\""))
                                listParameters[listParameters.Count - 1] += " " + parameters[end];
                            else
                            {
                                listParameters[listParameters.Count - 1] += " " + parameters[end].Replace("\"", "");
                                start = end;
                                break;
                            }
                        }
                    }
                }
                Array.Resize(ref parameters, listParameters.Count);
                parameters = listParameters.ToArray();
            }
        }

19 Source : LootSwap.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static Dictionary<string, Type> GetTypes(string prefix)
            {
                var replacedembly = replacedembly.GetExecutingreplacedembly();

                var types = replacedembly.GetTypes();

                return types.Where(i => i.FullName.StartsWith(prefix)).ToDictionary(i => i.FullName.Substring(i.FullName.LastIndexOf('.') + 1), i => i);
            }

See More Examples