Here are the examples of the csharp api string.Contains(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
14848 Examples
19
Source : ThingEntry.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public bool SetFaction(string fractionColonist, Func<string> fractionRoyalty)
{
if (string.IsNullOrEmpty(Data) || !Data.Contains(" Clreplaced=\"Pawn\"")) return false;
if (MainHelper.DebugMode) File.WriteAllText(Loger.PathLog + "MailPawnB" + (++nnnn).ToString() + ".xml", Data);
//логика коррекции основывается на 3х группыах:
//колонист, человек не колонист (пират или пленник), животное
bool col = Data.Contains("<kindDef>Colonist</kindDef>");
if (!col) col = Data.Contains("ColonistGeneral</kindDef>"); //для мода с андроидами
bool isAnimal = GameXMLUtils.GetByTag(Data, "def") == GameXMLUtils.GetByTag(Data, "kindDef");
//для всех людей устанавливаем фракцию игрока (у животных не меняем)
if (!isAnimal)
{
string fraction = fractionColonist; //col ? fractionColonist : fractionPirate;
Data = GameXMLUtils.ReplaceByTag(Data, "faction", fraction);
if (!col) Data = GameXMLUtils.ReplaceByTag(Data, "kindDef", "Colonist"); //"Pirate"
//if (MainHelper.DebugMode) Loger.Log(" Replace faction=>" + fraction);
}
//если это гости, то убираем у них это свойство - оно должно выставиться потом
Data = GameXMLUtils.ReplaceByTag(Data, "guest", @"
<hostFaction>null</hostFaction>
<interactionMode>NoInteraction</interactionMode>
<spotToWaitInsteadOfEscaping>(-1000, -1000, -1000)</spotToWaitInsteadOfEscaping>
<lastPrisonBreakTicks>-1</lastPrisonBreakTicks>
");
//локализуем фракцию роялти
var tagRoyalty = GameXMLUtils.GetByTag(Data, "royalty");
if (tagRoyalty != null)
{
string oldTR;
do
{
oldTR = tagRoyalty;
tagRoyalty = GameXMLUtils.ReplaceByTag(tagRoyalty, "faction", fractionRoyalty());
} while (oldTR != tagRoyalty);
Data = GameXMLUtils.ReplaceByTag(Data, "royalty", tagRoyalty);
}
/*
Data = GameXMLUtils.ReplaceByTag(Data, "hostFaction", "null", "<guest>");
Data = GameXMLUtils.ReplaceByTag(Data, "prisoner", "False", "<guest>");*/
/* попытка передавать заключенных не получилась
Data = GameXMLUtils.ReplaceByTag(Data, "hostFaction",
(val) =>
{
if (MainHelper.DebugMode) Loger.Log(" Replace hostFaction "+ val + "=>" + fractionColonist);
return val == "null" ? null : fractionColonist;
});
*/
//возвращаем true, если это человек и не колонист (пират или пленник)
if (MainHelper.DebugMode) File.WriteAllText(Loger.PathLog + "MailPawnA" + nnnn.ToString() + ".xml", Data);
return !col && !isAnimal;
}
19
Source : Repository.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public static bool CheckIsIntruder(string key)
{
if ((DateTime.UtcNow - BlockkeyUpdate).TotalSeconds > 30)
{
var fileName = Loger.PathLog + "blockkey.txt";
BlockkeyUpdate = DateTime.UtcNow;
if (!File.Exists(fileName)) Blockkey = new HashSet<string>();
else
try
{
var listBlock = File.ReadAllLines(fileName, Encoding.UTF8)
.Select(b => b.Replace("@@@", "").Trim())
.Select(b => b.Contains(" ") ? b.Substring(0, b.IndexOf(" ")) : b)
.Where(b => b != String.Empty)
.ToArray();
Blockkey = new HashSet<string>(listBlock);
}
catch (Exception exp)
{
Loger.Log("CheckIsIntruder error " + exp.Message);
Blockkey = new HashSet<string>();
return false;
}
}
var k = key.Replace("@@@", "").Trim();
return Blockkey.Contains(k);
}
19
Source : Repository.cs
with Apache License 2.0
from AantCoder
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 : RepositorySaveData.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public byte[] LoadPlayerData(string login, int numberSave)
{
if (numberSave < 1 || numberSave > CountSaveDataPlayer) return null;
var fileName = GetFileNameBase(login) + numberSave.ToString();
var info = new FileInfo(fileName);
if (!info.Exists || info.Length < 10) return null;
//читаем содержимое
bool readAsXml;
using (var file = File.OpenRead(fileName))
{
var buff = new byte[10];
file.Read(buff, 0, 10);
readAsXml = Encoding.ASCII.GetString(buff, 0, 10).Contains("<?xml");
}
//считываем текст как xml сейва или как сжатого zip'а
var saveFileData = File.ReadAllBytes(fileName);
if (readAsXml)
{
return saveFileData;
}
else
{
return GZip.UnzipByteByte(saveFileData);
}
}
19
Source : ServerCoreSerializationBinder.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public override Type BindToType(string replacedemblyName, string typeName)
{
if (replacedemblyName.Contains("OCServer"))
{
var bindToType = Type.GetType(typeName.Replace("OCServer", "ServerOnlineCity"));
return bindToType;
}
else
{
var bindToType = LoadTypeFromreplacedembly(replacedemblyName, typeName.Replace("OCServer", "ServerOnlineCity"));
return bindToType;
}
}
19
Source : Form1.cs
with Apache License 2.0
from abaga129
with Apache License 2.0
from abaga129
private void SetPins(string data)
{
if (data.Contains("03IH"))
groupBox3.BackColor = Color.Red;
else
groupBox3.BackColor = Color.Orchid;
if (data.Contains("05IH"))
groupBox5.BackColor = Color.Red;
else
groupBox5.BackColor = Color.Orchid;
if (data.Contains("07IH"))
groupBox7.BackColor = Color.Red;
else
groupBox7.BackColor = Color.LimeGreen;
if (data.Contains("08IH"))
groupBox8.BackColor = Color.Red;
else
groupBox8.BackColor = Color.BlueViolet;
if (data.Contains("10IH"))
groupBox10.BackColor = Color.Red;
else
groupBox10.BackColor = Color.BlueViolet;
if (data.Contains("11IH"))
groupBox11.BackColor = Color.Red;
else
groupBox11.BackColor = Color.LimeGreen;
if (data.Contains("12IH"))
groupBox12.BackColor = Color.Red;
else
groupBox12.BackColor = Color.Silver;
if (data.Contains("13IH"))
groupBox13.BackColor = Color.Red;
else
groupBox13.BackColor = Color.LimeGreen;
if (data.Contains("15IH"))
groupBox15.BackColor = Color.Red;
else
groupBox15.BackColor = Color.LimeGreen;
if (data.Contains("16IH"))
groupBox16.BackColor = Color.Red;
else
groupBox16.BackColor = Color.LimeGreen;
if (data.Contains("18IH"))
groupBox18.BackColor = Color.Red;
else
groupBox18.BackColor = Color.LimeGreen;
if (data.Contains("19IH"))
groupBox19.BackColor = Color.Red;
else
groupBox19.BackColor = Color.MediumBlue;
if (data.Contains("21IH"))
groupBox21.BackColor = Color.Red;
else
groupBox21.BackColor = Color.MediumBlue;
if (data.Contains("22IH"))
groupBox22.BackColor = Color.Red;
else
groupBox22.BackColor = Color.LimeGreen;
if (data.Contains("23IH"))
groupBox23.BackColor = Color.Red;
else
groupBox23.BackColor = Color.MediumBlue;
if (data.Contains("24IH"))
groupBox24.BackColor = Color.Red;
else
groupBox24.BackColor = Color.MediumBlue;
if (data.Contains("26IH"))
groupBox26.BackColor = Color.Red;
else
groupBox26.BackColor = Color.MediumBlue;
if (data.Contains("27IH"))
groupBox27.BackColor = Color.Red;
else
groupBox27.BackColor = Color.Gold;
if (data.Contains("28IH"))
groupBox28.BackColor = Color.Red;
else
groupBox28.BackColor = Color.Gold;
if (data.Contains("29IH"))
groupBox29.BackColor = Color.Red;
else
groupBox29.BackColor = Color.LimeGreen;
if (data.Contains("31IH"))
groupBox31.BackColor = Color.Red;
else
groupBox31.BackColor = Color.LimeGreen;
if (data.Contains("32IH"))
groupBox32.BackColor = Color.Red;
else
groupBox32.BackColor = Color.LimeGreen;
if (data.Contains("33IH"))
groupBox33.BackColor = Color.Red;
else
groupBox33.BackColor = Color.LimeGreen;
if (data.Contains("35IH"))
groupBox35.BackColor = Color.Red;
else
groupBox35.BackColor = Color.Silver;
if (data.Contains("36IH"))
groupBox36.BackColor = Color.Red;
else
groupBox36.BackColor = Color.LimeGreen;
if (data.Contains("37IH"))
groupBox37.BackColor = Color.Red;
else
groupBox37.BackColor = Color.LimeGreen;
if (data.Contains("38IH"))
groupBox38.BackColor = Color.Red;
else
groupBox38.BackColor = Color.Silver;
if (data.Contains("40IH"))
groupBox40.BackColor = Color.Red;
else
groupBox40.BackColor = Color.Silver;
}
19
Source : Repository.cs
with Apache License 2.0
from AantCoder
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 : DevReloadMiddleware.cs
with GNU General Public License v3.0
from abiosoft
with GNU General Public License v3.0
from abiosoft
private void OnChanged(object source, FileSystemEventArgs e)
{
// return if it's an ignored directory
foreach (string ignoredDirectory in _options.IgnoredSubDirectories)
{
var sep = Path.DirectorySeparatorChar;
if (e.FullPath.Contains($"{sep}{ignoredDirectory}{sep}")) return;
}
FileInfo fileInfo = new FileInfo(e.FullPath);
if (_options.StaticFileExtensions.Length > 0)
{
foreach (string extension in _options.StaticFileExtensions)
{
if (fileInfo.Extension.Equals($".{extension.TrimStart('.')}"))
{
_time = System.DateTime.Now.ToString();
break;
}
}
}
else
{
_time = System.DateTime.Now.ToString();
}
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
}
19
Source : WeatherMonitor.cs
with GNU General Public License v3.0
from abishekaditya
with GNU General Public License v3.0
from abishekaditya
public void OnNext(Weather value)
{
Console.WriteLine(_name);
if (_name.Contains("T"))
{
string op = $"| Temperature : {value.Temperature} Celsius |";
Console.Write(op);
}
if (_name.Contains("P"))
{
string op = $"| Pressure : {value.Pressure} atm |";
Console.Write(op);
}
if (_name.Contains("H"))
{
string op = $"| Humidity : {value.Humidity * 100} % |";
Console.Write(op);
}
if (!(_name.Contains("T") || _name.Contains("P") || _name.Contains("H")))
{
OnError(new Exception());
}
Console.WriteLine();
}
19
Source : StringExtensions.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static string ToProperCase(this string value)
{
// If there are 0 or 1 characters, just return the string.
if (value == null) { return value; }
if (value.Length < 2) { return value.ToUpper(); }
// If there's already spaces in the string, return.
if (value.Contains(" ")) { return value; }
// Start with the first character.
string result = value.Substring(0, 1).ToUpper();
// Add the remaining characters.
for (int i = 1; i < value.Length; i++)
{
if (char.IsLetter(value[i]) &&
char.IsUpper(value[i]))
{
// Add a space if the previous character is not upper-case.
// e.g. "LeftHand" -> "Left Hand"
if (i != 1 && // First character is upper-case in result.
(!char.IsLetter(value[i - 1]) || char.IsLower(value[i - 1])))
{
result += " ";
}
// If previous character is upper-case, only add space if the next
// character is lower-case. Otherwise replacedume this character to be inside
// an acronym.
// e.g. "OpenVRLeftHand" -> "Open VR Left Hand"
else if (i < value.Length - 1 &&
char.IsLetter(value[i + 1]) && char.IsLower(value[i + 1]))
{
result += " ";
}
}
result += value[i];
}
return result;
}
19
Source : MixedRealitySearchUtility.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void CheckFieldForKeywords(SerializedProperty property, SearchConfig config, ProfileSearchResult result)
{
int numMatchedKeywords = 0;
int numExactMatches = 0;
int numFieldMatches = 0;
int numTooltipMatches = 0;
int numContentMatches = 0;
string propertyName = property.name.ToLower();
string toolTip = property.tooltip.ToLower();
foreach (string keyword in config.Keywords)
{
bool keywordMatch = false;
if (propertyName.Contains(keyword))
{
keywordMatch = true;
numFieldMatches++;
if (propertyName == keyword)
{
numExactMatches++;
}
}
if (config.SearchTooltips)
{
if (toolTip.Contains(keyword))
{
keywordMatch = true;
numTooltipMatches++;
}
}
if (config.SearchFieldContent)
{
switch (property.propertyType)
{
case SerializedPropertyType.ObjectReference:
if (property.objectReferenceValue != null && property.objectReferenceValue.name.ToLower().Contains(keyword))
{
keywordMatch = true;
numContentMatches++;
}
break;
case SerializedPropertyType.String:
if(!string.IsNullOrEmpty(property.stringValue) && property.stringValue.ToLower().Contains(keyword))
{
keywordMatch = true;
numContentMatches++;
}
break;
}
}
if (keywordMatch)
{
numMatchedKeywords++;
}
}
bool requirementsMet = numMatchedKeywords > 0;
if (config.RequireAllKeywords && config.Keywords.Count > 1)
{
requirementsMet &= numMatchedKeywords >= config.Keywords.Count;
}
if (requirementsMet)
{
int matchStrength = numMatchedKeywords + numExactMatches;
if (numMatchedKeywords >= config.Keywords.Count)
{ // If we match all keywords in a multi-keyword search, double the score
matchStrength *= 2;
}
// Weight the score based on match type
matchStrength += numFieldMatches * 3;
matchStrength += numTooltipMatches * 2;
matchStrength += numContentMatches * 1;
result.ProfileMatchStrength += matchStrength;
result.Fields.Add(new FieldSearchResult()
{
Property = property.Copy(),
MatchStrength = numMatchedKeywords,
});
}
}
19
Source : UnityJoystickManager.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
protected virtual SupportedControllerType GetCurrentControllerType(string joystickName)
{
// todo: this should be using an allow list, not a disallow list
if (string.IsNullOrEmpty(joystickName) ||
joystickName.Contains("OpenVR") ||
joystickName.Contains("Spatial"))
{
return 0;
}
if (joystickName.ToLower().Contains("xbox"))
{
return SupportedControllerType.Xbox;
}
Debug.Log($"{joystickName} does not have a defined controller type, falling back to generic controller type");
return SupportedControllerType.GenericUnity;
}
19
Source : PackageManifestUpdater.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
internal static void EnsureMSBuildForUnity()
{
PackageManifest manifest = null;
string manifestPath = GetPackageManifestFilePath();
if (string.IsNullOrWhiteSpace(manifestPath))
{
return;
}
// Read the package manifest into a list of strings (for easy finding of entries)
// and then deserialize.
List<string> manifestFileLines = new List<string>();
using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(manifestStream))
{
// Read the manifest file a line at a time.
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
manifestFileLines.Add(line);
}
// Go back to the start of the file.
manifestStream.Seek(0, 0);
// Deserialize the scoped registries portion of the package manifest.
manifest = JsonUtility.FromJson<PackageManifest>(reader.ReadToEnd());
}
}
if (manifest == null)
{
Debug.LogError($"Failed to read the package manifest file ({manifestPath})");
return;
}
// Ensure that pre-existing scoped registries are retained.
List<ScopedRegistry> scopedRegistries = new List<ScopedRegistry>();
if ((manifest.scopedRegistries != null) && (manifest.scopedRegistries.Length > 0))
{
scopedRegistries.AddRange(manifest.scopedRegistries);
}
// Attempt to find an entry in the scoped registries collection for the MSBuild for Unity URL
bool needToAddRegistry = true;
foreach (ScopedRegistry registry in scopedRegistries)
{
if (registry.url == MSBuildRegistryUrl)
{
needToAddRegistry = false;
}
}
// If no entry was found, add one.
if (needToAddRegistry)
{
ScopedRegistry registry = new ScopedRegistry();
registry.name = MSBuildRegistryName;
registry.url = MSBuildRegistryUrl;
registry.scopes = MSBuildRegistryScopes;
scopedRegistries.Add(registry);
}
// Update the manifest's scoped registries, as the collection may have been modified.
manifest.scopedRegistries = scopedRegistries.ToArray();
int dependenciesStartIndex = -1;
int scopedRegistriesStartIndex = -1;
int scopedRegistriesEndIndex = -1;
int packageLine = -1;
// Presume that we need to add the MSBuild for Unity package. If this value is false,
// we will check to see if the currently configured version meets or exceeds the
// minimum requirements.
bool needToAddPackage = true;
// Attempt to find the MSBuild for Unity package entry in the dependencies collection
// This loop also identifies the dependencies collection line and the start / end of a
// pre-existing scoped registries collections
for (int i = 0; i < manifestFileLines.Count; i++)
{
if (manifestFileLines[i].Contains("\"scopedRegistries\":"))
{
scopedRegistriesStartIndex = i;
}
if (manifestFileLines[i].Contains("],") && (scopedRegistriesStartIndex != -1) && (scopedRegistriesEndIndex == -1))
{
scopedRegistriesEndIndex = i;
}
if (manifestFileLines[i].Contains("\"dependencies\": {"))
{
dependenciesStartIndex = i;
}
if (manifestFileLines[i].Contains(MSBuildPackageName))
{
packageLine = i;
needToAddPackage = false;
}
}
// If no package was found add it to the dependencies collection.
if (needToAddPackage)
{
// Add the package to the collection (pad the entry with four spaces)
manifestFileLines.Insert(dependenciesStartIndex + 1, $" \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",");
}
else
{
// Replace the line that currently exists
manifestFileLines[packageLine] = $" \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",";
}
// Update the manifest file.
// First, serialize the scoped registry collection.
string serializedRegistriesJson = JsonUtility.ToJson(manifest, true);
// Ensure that the file is truncated to ensure it is always valid after writing.
using (FileStream outFile = new FileStream(manifestPath, FileMode.Truncate, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(outFile))
{
bool scopedRegistriesWritten = false;
// Write each line of the manifest back to the file.
for (int i = 0; i < manifestFileLines.Count; i++)
{
if ((i >= scopedRegistriesStartIndex) && (i <= scopedRegistriesEndIndex))
{
// Skip these lines, they will be replaced.
continue;
}
if (!scopedRegistriesWritten && (i > 0))
{
// Trim the leading '{' and '\n' from the serialized scoped registries
serializedRegistriesJson = serializedRegistriesJson.Remove(0, 2);
// Trim, the trailing '\n' and '}'
serializedRegistriesJson = serializedRegistriesJson.Remove(serializedRegistriesJson.Length - 2);
// Append a trailing ',' to close the scopedRegistries node
serializedRegistriesJson = serializedRegistriesJson.Insert(serializedRegistriesJson.Length, ",");
writer.WriteLine(serializedRegistriesJson);
scopedRegistriesWritten = true;
}
writer.WriteLine(manifestFileLines[i]);
}
}
}
}
19
Source : DevicePortal.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static string FinalizeUrl(string targetUrl)
{
string ssl = Rest.UseSSL ? "s" : string.Empty;
if (targetUrl.Contains(DeviceInfo.LocalMachine) || targetUrl.Contains(DeviceInfo.LocalIPAddress))
{
targetUrl = $"{DeviceInfo.LocalIPAddress}:10080";
ssl = string.Empty;
}
return $@"http{ssl}://{targetUrl}";
}
19
Source : ScenePickPropertyDrawer.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
BuildOptions();
var currentGuid = property.stringValue.Split(';')[0];
var currentId = System.Array.FindIndex(PropertyData, (x) => x.Contains(currentGuid));
if (currentId == -1)
{
// Not found, display the missing text
currentId = Options.Length - 1;
}
else if (currentId > 0 && property.stringValue != PropertyData[currentId])
{
// If the string has changed, update the property.
// This will happen if the scene is renamed.
property.stringValue = PropertyData[currentId];
EditorUtility.SetDirty(property.serializedObject.targetObject);
}
EditorGUI.BeginProperty(position, new GUIContent(property.name), property);
var newId = EditorGUI.Popup(position, label, currentId, Options);
if (newId != currentId)
{
property.stringValue = PropertyData[newId];
EditorUtility.SetDirty(property.serializedObject.targetObject);
}
EditorGUI.EndProperty();
}
19
Source : FileUtilities.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static FileInfo[] FindFilesInreplacedets(string fileName)
{
// Findreplacedets doesn't take a file extension
string[] replacedetGuids = replacedetDatabase.Findreplacedets(Path.GetFileNameWithoutExtension(fileName));
List<FileInfo> fileInfos = new List<FileInfo>();
for (int i = 0; i < replacedetGuids.Length; i++)
{
string replacedetPath = replacedetDatabase.GUIDToreplacedetPath(replacedetGuids[i]);
// Since this is an replacedet search without extension, some filenames may contain parts of other filenames.
// Therefore, double check that the path actually contains the filename with extension.
if (replacedetPath.Contains(fileName))
{
fileInfos.Add(new FileInfo(replacedetPath));
}
}
return fileInfos.ToArray();
}
19
Source : LeapMotionConfigurationChecker.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
[MenuItem("Mixed Reality Toolkit/Utilities/Leap Motion/Configure CSC File for Leap Motion")]
static void UpdateCSC()
{
// The csc file will always be in the root of replacedets
string cscFilePath = Path.Combine(Application.dataPath, "csc.rsp");
// Each line of the csc file
List<string> cscFileLines = new List<string>();
// List of the warning numbers after "-nowarn: " in the csc file
List<string> warningNumbers = new List<string>();
// List of new warning numbers to add to the csc file
List<string> warningNumbersToAdd = new List<string>()
{
"618",
"649"
};
using (StreamReader streamReader = new StreamReader(cscFilePath))
{
while (streamReader.Peek() > -1)
{
string cscFileLine = streamReader.ReadLine();
if (cscFileLine.Contains("-nowarn"))
{
string[] currentWarningNumbers = cscFileLine.Split(',', ':');
warningNumbers = currentWarningNumbers.ToList();
// Remove "nowarn" from the warningNumbers list
warningNumbers.Remove("-nowarn");
foreach (string warningNumberToAdd in warningNumbersToAdd)
{
// Add the new warning numbers if they are not already in the file
if (!warningNumbers.Contains(warningNumberToAdd))
{
warningNumbers.Add(warningNumberToAdd);
}
}
cscFileLines.Add(string.Join(",", warningNumbers));
}
else
{
cscFileLines.Add(cscFileLine);
}
}
}
using (StreamWriter streamWriter = new StreamWriter(cscFilePath))
{
foreach (string cscLine in cscFileLines)
{
if (cscLine.StartsWith("1701"))
{
string warningNumbersJoined = string.Join(",", warningNumbers);
streamWriter.WriteLine(string.Concat("-nowarn:", warningNumbersJoined));
}
else
{
streamWriter.WriteLine(cscLine);
}
}
}
Debug.Log($"Saving {cscFilePath}");
}
19
Source : UwpAppxBuildTools.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static async Task<string> FindMsBuildPathAsync()
{
// Finding msbuild.exe involves different work depending on whether or not users
// have VS2017 or VS2019 installed.
foreach (VSWhereFindOption findOption in VSWhereFindOptions)
{
string arguments = findOption.arguments;
if (string.IsNullOrWhiteSpace(EditorUserBuildSettings.wsaUWPVisualStudioVersion))
{
arguments += " -latest";
}
else
{
// Add version number with brackets to find only the specified version
arguments += $" -version [{EditorUserBuildSettings.wsaUWPVisualStudioVersion}]";
}
var result = await new Process().StartProcessAsync(
new ProcessStartInfo
{
FileName = "cmd.exe",
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
Arguments = arguments,
WorkingDirectory = @"C:\Program Files (x86)\Microsoft Visual Studio\Installer"
});
foreach (var path in result.Output)
{
if (!string.IsNullOrEmpty(path))
{
string[] paths = path.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
if (paths.Length > 0)
{
// if there are multiple visual studio installs,
// prefer enterprise, then pro, then community
string bestPath = paths.OrderByDescending(p => p.ToLower().Contains("enterprise"))
.ThenByDescending(p => p.ToLower().Contains("professional"))
.ThenByDescending(p => p.ToLower().Contains("community")).First();
string finalPath = $@"{bestPath}{findOption.pathSuffix}";
if (File.Exists(finalPath))
{
return finalPath;
}
}
}
}
}
return string.Empty;
}
19
Source : PackageManifestUpdater.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
internal static bool IsMSBuildForUnityEnabled()
{
string manifestPath = GetPackageManifestFilePath();
if (string.IsNullOrWhiteSpace(manifestPath))
{
return false;
}
// Load the manifest file.
string manifestFileContents = File.ReadAllText(manifestPath);
if (string.IsNullOrWhiteSpace(manifestFileContents))
{
return false;
}
// Read the package manifest a line at a time.
using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(manifestStream))
{
// Read the manifest file a line at a time.
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line.Contains(MSBuildPackageName))
{
// Split the line into packageName : packageVersion
string[] lineComponents = line.Split(new char[] { ':' }, 2);
return IsAppropriateMBuildVersion(MSBuildPackageVersion, lineComponents[1]);
}
}
}
}
return false;
}
19
Source : LeapMotionConfigurationChecker.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static bool LeapCorereplacedetsVersionSupport()
{
string versionLeapPath = Path.Combine(Application.dataPath, pathDifference, "LeapMotion", "Core", "Version.txt");
using (StreamReader streamReader = new StreamReader(versionLeapPath))
{
while (streamReader.Peek() > -1)
{
string line = streamReader.ReadLine();
foreach (string versionNumberSupported in leapCorereplacedetsVersionsSupported)
{
// If the leap core replacedets version number is supported
if (line.Contains(versionNumberSupported))
{
currentLeapCorereplacedetsVersion = versionNumberSupported;
return true;
}
}
}
return false;
}
}
19
Source : OpenVRDeviceManager.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
protected override GenericJoystickController GetOrAddController(string joystickName)
{
using (GetOrAddControllerPerfMarker.Auto())
{
// If a device is already registered with the ID provided, just return it.
if (ActiveControllers.ContainsKey(joystickName))
{
var controller = ActiveControllers[joystickName];
Debug.replacedert(controller != null);
return controller;
}
Handedness controllingHand;
if (joystickName.Contains("Left"))
{
controllingHand = Handedness.Left;
}
else if (joystickName.Contains("Right"))
{
controllingHand = Handedness.Right;
}
else
{
controllingHand = Handedness.None;
}
var currentControllerType = GetCurrentControllerType(joystickName);
Type controllerType;
switch (currentControllerType)
{
case SupportedControllerType.GenericOpenVR:
controllerType = typeof(GenericOpenVRController);
break;
case SupportedControllerType.ViveWand:
controllerType = typeof(ViveWandController);
break;
case SupportedControllerType.ViveKnuckles:
controllerType = typeof(ViveKnucklesController);
break;
case SupportedControllerType.OculusTouch:
controllerType = typeof(OculusTouchController);
break;
case SupportedControllerType.OculusRemote:
controllerType = typeof(OculusRemoteController);
break;
case SupportedControllerType.WindowsMixedReality:
controllerType = typeof(WindowsMixedRealityOpenVRMotionController);
break;
default:
return null;
}
IMixedRealityInputSystem inputSystem = Service as IMixedRealityInputSystem;
var pointers = RequestPointers(currentControllerType, controllingHand);
var inputSource = inputSystem?.RequestNewGenericInputSource($"{currentControllerType} Controller {controllingHand}", pointers, InputSourceType.Controller);
var detectedController = Activator.CreateInstance(controllerType, TrackingState.NotTracked, controllingHand, inputSource, null) as GenericOpenVRController;
if (detectedController == null || !detectedController.Enabled)
{
// Controller failed to be set up correctly.
Debug.LogError($"Failed to create {controllerType.Name} controller");
// Return null so we don't raise the source detected.
return null;
}
for (int i = 0; i < detectedController.InputSource?.Pointers?.Length; i++)
{
detectedController.InputSource.Pointers[i].Controller = detectedController;
}
ActiveControllers.Add(joystickName, detectedController);
return detectedController;
}
}
19
Source : OpenVRDeviceManager.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
protected override SupportedControllerType GetCurrentControllerType(string joystickName)
{
if (string.IsNullOrEmpty(joystickName) || !joystickName.Contains("OpenVR"))
{
return 0;
}
if (joystickName.Contains("Oculus Rift CV1"))
{
return SupportedControllerType.OculusTouch;
}
if (joystickName.Contains("Oculus remote"))
{
return SupportedControllerType.OculusRemote;
}
if (joystickName.Contains("Vive Wand"))
{
return SupportedControllerType.ViveWand;
}
if (joystickName.Contains("Vive Knuckles"))
{
return SupportedControllerType.ViveKnuckles;
}
if (joystickName.Contains("WindowsMR"))
{
return SupportedControllerType.WindowsMixedReality;
}
Debug.Log($"{joystickName} does not have a defined controller type, falling back to generic controller type");
return SupportedControllerType.GenericOpenVR;
}
19
Source : MixedRealityProjectConfigurator.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static void ApplyXRSettings()
{
// Ensure compatibility with the pre-2019.3 XR architecture for customers / platforms
// with legacy requirements.
#pragma warning disable 0618
BuildTargetGroup targetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
List<string> targetSDKs = new List<string>();
foreach (string sdk in PlayerSettings.GetAvailableVirtualRealitySDKs(targetGroup))
{
if (sdk.Contains("OpenVR") || sdk.Contains("Windows"))
{
targetSDKs.Add(sdk);
}
}
if (targetSDKs.Count != 0)
{
PlayerSettings.SetVirtualRealitySDKs(targetGroup, targetSDKs.ToArray());
PlayerSettings.SetVirtualRealitySupported(targetGroup, true);
}
#pragma warning restore 0618
}
19
Source : DevicePortal.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static async Task<bool> InstallAppAsync(string appFullPath, DeviceInfo targetDevice, bool waitForDone = true)
{
Debug.replacedert(!string.IsNullOrEmpty(appFullPath));
var isAuth = await EnsureAuthenticationAsync(targetDevice);
if (!isAuth)
{
return false;
}
Debug.Log($"Starting app install on {targetDevice.ToString()}...");
// Calculate the cert and dependency paths
string fileName = Path.GetFileName(appFullPath);
string certFullPath = Path.ChangeExtension(appFullPath, ".cer");
string certName = Path.GetFileName(certFullPath);
string arch = "ARM";
if (appFullPath.Contains("x86"))
{
arch = "x86";
}
else if (appFullPath.Contains("ARM64"))
{
arch = "ARM64";
}
string depPath = $@"{Path.GetDirectoryName(appFullPath)}\Dependencies\{arch}\";
var form = new WWWForm();
try
{
// APPX file
Debug.replacedert(appFullPath != null);
using (var stream = new FileStream(appFullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new BinaryReader(stream))
{
form.AddBinaryData(fileName, reader.ReadBytes((int)reader.BaseStream.Length), fileName);
}
}
// CERT file
Debug.replacedert(certFullPath != null);
using (var stream = new FileStream(certFullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new BinaryReader(stream))
{
form.AddBinaryData(certName, reader.ReadBytes((int)reader.BaseStream.Length), certName);
}
}
// Dependencies
IOFileInfo[] depFiles = new DirectoryInfo(depPath).GetFiles();
foreach (IOFileInfo dep in depFiles)
{
using (var stream = new FileStream(dep.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new BinaryReader(stream))
{
string depFilename = Path.GetFileName(dep.FullName);
form.AddBinaryData(depFilename, reader.ReadBytes((int)reader.BaseStream.Length), depFilename);
}
}
}
}
catch (Exception e)
{
Debug.LogException(e);
return false;
}
// Query
string query = $"{string.Format(InstallQuery, FinalizeUrl(targetDevice.IP))}?package={UnityWebRequest.EscapeURL(fileName)}";
var response = await Rest.PostAsync(query, form, targetDevice.Authorization);
if (!response.Successful)
{
if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
{
return await InstallAppAsync(appFullPath, targetDevice, waitForDone);
}
Debug.LogError($"Failed to install {fileName} on {targetDevice.ToString()}.");
return false;
}
var status = AppInstallStatus.Installing;
// Wait for done (if requested)
while (waitForDone && status == AppInstallStatus.Installing)
{
status = await GetInstallStatusAsync(targetDevice);
switch (status)
{
case AppInstallStatus.InstallSuccess:
Debug.Log($"Successfully installed {fileName} on {targetDevice.ToString()}.");
return true;
case AppInstallStatus.InstallFail:
Debug.LogError($"Failed to install {fileName} on {targetDevice.ToString()}.");
return false;
}
}
return true;
}
19
Source : LeapMotionConfigurationChecker.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void RemoveTestingFolders()
{
// If one of the leap test directories exists, then we replacedume the rest have not been deleted
if (Directory.Exists(Path.Combine(Application.dataPath, pathDifference, pathsToDelete[0])))
{
foreach (string path in pathsToDelete)
{
// Get the full path including the path difference in case the core replacedets are not imported to the root of the project
string fullPath = Path.Combine(Application.dataPath, pathDifference, path);
// If we are deleting a specific file, then we also need to remove the meta replacedociated with the file
if (File.Exists(fullPath) && fullPath.Contains(".cs"))
{
// Delete the test files
FileUtil.DeleteFileOrDirectory(fullPath);
// Also delete the meta files
FileUtil.DeleteFileOrDirectory(fullPath + ".meta");
}
if (Directory.Exists(fullPath))
{
// Delete the test directories
FileUtil.DeleteFileOrDirectory(fullPath);
// Delete the test directories meta files
FileUtil.DeleteFileOrDirectory(fullPath.TrimEnd('/') + ".meta");
}
}
}
}
19
Source : OVRADBTool.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public int RunCommand(string[] arguments, WaitingProcessToExitCallback waitingProcessToExitCallback, out string outputString, out string errorString)
{
int exitCode = -1;
if (!isReady)
{
Debug.LogWarning("OVRADBTool not ready");
outputString = string.Empty;
errorString = "OVRADBTool not ready";
return exitCode;
}
string args = string.Join(" ", arguments);
ProcessStartInfo startInfo = new ProcessStartInfo(adbPath, args);
startInfo.WorkingDirectory = androidSdkRoot;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
outputStringBuilder = new StringBuilder("");
errorStringBuilder = new StringBuilder("");
Process process = Process.Start(startInfo);
process.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceivedHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataReceivedHandler);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
try
{
do
{
if (waitingProcessToExitCallback != null)
{
waitingProcessToExitCallback();
}
} while (!process.WaitForExit(100));
process.WaitForExit();
}
catch (Exception e)
{
Debug.LogWarningFormat("[OVRADBTool.RunCommand] exception {0}", e.Message);
}
exitCode = process.ExitCode;
process.Close();
outputString = outputStringBuilder.ToString();
errorString = errorStringBuilder.ToString();
outputStringBuilder = null;
errorStringBuilder = null;
if (!string.IsNullOrEmpty(errorString))
{
if (errorString.Contains("Warning"))
{
UnityEngine.Debug.LogWarning("OVRADBTool " + errorString);
}
else
{
UnityEngine.Debug.LogError("OVRADBTool " + errorString);
}
}
return exitCode;
}
19
Source : OVRPlatformTool.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
static void Command(TargetPlatform targetPlatform, string dataPath, string uploadCommand)
{
string platformUtilPath = CheckForPlatformUtil(dataPath);
activeProcess = true;
InitializePlatformUtilProcess(platformUtilPath, uploadCommand);
ovrPlatUtilProcess.Exited += new EventHandler(
(s, e) =>
{
activeProcess = false;
}
);
ovrPlatUtilProcess.OutputDataReceived += new DataReceivedEventHandler(
(s, e) =>
{
if (e.Data != null && e.Data.Length != 0 && !e.Data.Contains("\u001b"))
{
OVRPlatformTool.log += e.Data + "\n";
}
}
);
ovrPlatUtilProcess.ErrorDataReceived += new DataReceivedEventHandler(
(s, e) =>
{
OVRPlatformTool.log += e.Data + "\n";
}
);
try
{
ovrPlatUtilProcess.Start();
ovrPlatUtilProcess.BeginOutputReadLine();
ovrPlatUtilProcess.BeginErrorReadLine();
}
catch
{
if (ThrowPlatformUtilStartupError(platformUtilPath))
{
Command(targetPlatform, dataPath, uploadCommand);
}
}
}
19
Source : OVRPlatformTool.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
static bool LaunchParameterValidator(string fieldText, ref string error)
{
if (fieldText.Contains("\""))
{
error = "The field contains illegal characters.";
return false;
}
return true;
}
19
Source : OvrAvatarMaterialManager.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public static ovrAvatarBodyPartType GetComponentType(string objectName)
{
if (objectName.Contains("0"))
{
return ovrAvatarBodyPartType.Body;
}
else if (objectName.Contains("1"))
{
return ovrAvatarBodyPartType.Clothing;
}
else if (objectName.Contains("2"))
{
return ovrAvatarBodyPartType.Eyewear;
}
else if (objectName.Contains("3"))
{
return ovrAvatarBodyPartType.Hair;
}
else if (objectName.Contains("4"))
{
return ovrAvatarBodyPartType.Beard;
}
return ovrAvatarBodyPartType.Count;
}
19
Source : AndroidVideoEditorUtil.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static int FindInScope(string search, int start, List<string> lines)
{
var regex = new System.Text.RegularExpressions.Regex(search);
int depth = 0;
for (int i = start; i < lines.Count; i++)
{
if (depth == 0 && regex.IsMatch(lines[i]))
{
return i;
}
// count the number of open and close braces. If we leave the current scope, break
if (lines[i].Contains("{"))
{
depth++;
}
if (lines[i].Contains("}"))
{
depth--;
}
if (depth < 0)
{
break;
}
}
return -1;
}
19
Source : AndroidVideoEditorUtil.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static int GetScopeEnd(int start, List<string> lines)
{
int depth = 0;
for (int i = start; i < lines.Count; i++)
{
// count the number of open and close braces. If we leave the current scope, break
if (lines[i].Contains("{"))
{
depth++;
}
if (lines[i].Contains("}"))
{
depth--;
}
if (depth < 0)
{
return i;
}
}
return -1;
}
19
Source : ONSPAudioPluginUpdater.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
static void OnDelayCall()
{
if (System.Environment.CommandLine.Contains("-batchmode"))
{
unityRunningInBatchmode = true;
}
if (ShouldAttemptPluginUpdate())
{
AttemptSpatializerPluginUpdate(true);
}
}
19
Source : OVRPluginUpdater.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
static void OnDelayCall()
{
if (System.Environment.CommandLine.Contains("-batchmode"))
{
unityRunningInBatchmode = true;
}
if (enableAndroidUniversalSupport)
{
unityVersionSupportsAndroidUniversal = true;
}
if (ShouldAttemptPluginUpdate())
{
AttemptPluginUpdate(true);
}
}
19
Source : MoviePlayerSample.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private bool IsLocalVideo(string movieName)
{
// if the path contains any url scheme, it is not local
return !movieName.Contains("://");
}
19
Source : OVRResources.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public static UnityEngine.Object Load(string path)
{
if (Debug.isDebugBuild)
{
if(resourceBundle == null)
{
Debug.Log("[OVRResources] Resource bundle was not loaded successfully");
return null;
}
var result = replacedetNames.Find(s => s.Contains(path.ToLower()));
return resourceBundle.Loadreplacedet(result);
}
return Resources.Load(path);
}
19
Source : OVRResources.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public static T Load<T>(string path) where T : UnityEngine.Object
{
if (Debug.isDebugBuild)
{
if (resourceBundle == null)
{
Debug.Log("[OVRResources] Resource bundle was not loaded successfully");
return null;
}
var result = replacedetNames.Find(s => s.Contains(path.ToLower()));
return resourceBundle.Loadreplacedet<T>(result);
}
return Resources.Load<T>(path);
}
19
Source : OVRPlatformTool.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
static void LoadRedistPackages(string dataPath)
{
// Check / Download the platform util and call list-redists on it
activeProcess = true;
string platformUtilPath = CheckForPlatformUtil(dataPath);
InitializePlatformUtilProcess(platformUtilPath, "list-redists");
OVRPlatformTool.log += "Loading redistributable packages...\n";
List<RedistPackage> redistPacks = new List<RedistPackage>();
ovrPlatUtilProcess.Exited += new EventHandler(
(s, e) =>
{
activeProcess = false;
}
);
ovrPlatUtilProcess.OutputDataReceived += new DataReceivedEventHandler(
(s, e) =>
{
if (e.Data != null && e.Data.Length != 0 && !e.Data.Contains("\u001b") && !e.Data.Contains("ID"))
{
// Get the name / ID pair from the CLI and create a redist package instance
string[] terms = e.Data.Split('|');
if (terms.Length == 2)
{
RedistPackage redistPack = new RedistPackage(terms[1], terms[0]);
redistPacks.Add(redistPack);
}
}
}
);
try
{
ovrPlatUtilProcess.Start();
ovrPlatUtilProcess.BeginOutputReadLine();
ovrPlatUtilProcess.WaitForExit();
if (redistPacks.Count != OVRPlatformToolSettings.RiftRedistPackages.Count)
{
OVRPlatformTool.log += "Successfully updated redistributable packages.\n";
OVRPlatformToolSettings.RiftRedistPackages = redistPacks;
}
else
{
OVRPlatformTool.log += "Redistributable packages up to date.\n";
}
}
catch
{
if (ThrowPlatformUtilStartupError(platformUtilPath))
{
LoadRedistPackages(dataPath);
}
}
}
19
Source : OVRPlatformTool.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
static void CheckForUpdate(string dataPath)
{
string platformUtilPath = CheckForPlatformUtil(dataPath);
InitializePlatformUtilProcess(platformUtilPath, "self-update");
OVRPlatformTool.log += "Checking for update...\n";
ovrPlatUtilProcess.Exited += new EventHandler(
(s, e) =>
{
if (File.Exists(dataPath + ".ovr-platform-util.exe"))
{
OVRPlatformTool.log += "Cleaning up...\n";
while (File.Exists(dataPath + ".ovr-platform-util.exe")) { }
OVRPlatformTool.log += "Finished updating platform utility.\n";
}
activeProcess = false;
}
);
ovrPlatUtilProcess.OutputDataReceived += new DataReceivedEventHandler(
(s, e) =>
{
if (e.Data != null && e.Data.Length != 0 && !e.Data.Contains("\u001b"))
{
OVRPlatformTool.log += e.Data + "\n";
}
}
);
try
{
ovrPlatUtilProcess.Start();
ovrPlatUtilProcess.BeginOutputReadLine();
}
catch
{
if (ThrowPlatformUtilStartupError(platformUtilPath))
{
CheckForUpdate(dataPath);
}
}
}
19
Source : SciTraderViewModel.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void UpdateSeriesNames(string priceName)
{
if (!AllSeriesNames.First().Contains("SMA"))
AllSeriesNames.RemoveAt(0);
AllSeriesNames.Insert(0, priceName);
SelectedSeriesToSnap = priceName;
}
19
Source : ExampleLoader.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static string LoadSourceFile(string name)
{
replacedembly replacedembly = typeof(ExampleLoader).replacedembly;
var names = replacedembly.GetManifestResourceNames();
var allExampleSourceFiles = names.Where(x => x.Contains("SciChart.Examples.Examples"));
var find = name.Replace('/', '.').Replace(".txt", string.Empty).Replace("Resources.ExampleSourceFiles.", string.Empty);
var file = allExampleSourceFiles.FirstOrDefault(x => x.EndsWith(find));
if (file == null)
throw new Exception(string.Format("Unable to find the source code resource {0}", find));
using (var s = replacedembly.GetManifestResourceStream(file))
using (var sr = new StreamReader(s))
{
return sr.ReadToEnd();
}
}
19
Source : ExampleLoader.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private IDictionary<ExampleKey, string> DiscoverAllExampleDefinitions()
{
var dict = new Dictionary<ExampleKey, string>();
replacedembly replacedembly = typeof (ExampleLoader).replacedembly;
var names = replacedembly.GetManifestResourceNames();
var allXmlManifestResources = names.Where(x => x.Contains("ExampleDefinitions")).ToList();
allXmlManifestResources.Sort();
foreach(var xmlResource in allXmlManifestResources)
{
using (var s = replacedembly.GetManifestResourceStream(xmlResource))
using (var sr = new StreamReader(s))
{
string exampleKeyString = xmlResource.Replace("SciChart.Examples.Resources.ExampleDefinitions.", string.Empty)
.Replace("SciChart.Examples.SL.Resources.ExampleDefinitions.", string.Empty);
string[] chunks = exampleKeyString.Split('.');
var exampleKey = new ExampleKey()
{
ExampleCategory = Trim(chunks[0], true),
ChartGroup = Trim(chunks[1]),
Examplereplacedle = Trim(chunks[2])
};
dict.Add(exampleKey, sr.ReadToEnd());
}
}
return dict;
}
19
Source : ExampleManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static IDictionary<string, string> GetAllExampleDefinitions()
{
var dictionary = new Dictionary<string, string>();
var replacedembly = typeof(ExampleManager).replacedembly;
var exampleNames = replacedembly.GetManifestResourceNames().Where(x => x.Contains("ExampleSourceFiles")).ToList();
exampleNames.Sort();
foreach (var example in exampleNames)
{
using (var s = replacedembly.GetManifestResourceStream(example))
using (var sr = new StreamReader(s))
{
dictionary.Add(example.Replace("SciChart.Example.Resources.ExampleDefinitions.", string.Empty),
sr.ReadToEnd());
}
}
return dictionary;
}
19
Source : ExampleDescriptionFormattingConverter.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (MainWindowViewModel.SearchText.IsNullOrEmpty())
{
return string.Empty;
}
var description = (string)value;
var result = string.Empty;
var terms = MainWindowViewModel.SearchText.Split(' ').Where(word => word != "").Select(x => x.ToLower()).ToArray();
var lines = description.Split(new[] { ". " }, StringSplitOptions.None).ToArray();
var sentences = new HashSet<string>();
foreach (var term in terms)
{
var containsTerm = lines.Where(x => x != "" && x.ToLower().Contains(term));
containsTerm.Take(2).ForEachDo(x => sentences.Add(x));
}
if (sentences.Any())
{
result = HighlightText(sentences.Select(x => x.Trim()).ToArray(), terms);
}
else
{
foreach (string sentence in lines.Take(2).Select(x => x.Trim()))
{
result = result + (sentence + ". ");
}
}
return result;
}
19
Source : ExampleSourceCodeFormattingConverter.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (MainWindowViewModel.SearchText.IsNullOrEmpty())
{
return string.Empty;
}
var terms = MainWindowViewModel.SearchText.Split(' ').Where(word => word != "").Select(x => x.ToLower()).ToArray();
var codeFiles = (Dictionary<string, string>) value;
var uiCodeFiles = codeFiles.Where(x => x.Key.EndsWith(".xaml"));
var lines = new List<string>();
foreach (var file in uiCodeFiles)
{
lines.AddRange(file.Value.Split(new[] {"\r\n"}, StringSplitOptions.None));
}
var toHighlight = new HashSet<string>();
foreach (var term in terms)
{
var containsTerm = lines.Where(x => x != "" && x.ToLower().Contains(term));
containsTerm.Take(2).Select(x => x.Trim()).ForEachDo(x => toHighlight.Add(x));
}
string result;
if (toHighlight.Any())
{
lines = toHighlight.Take(2).Select(x => x.Trim().Replace('<', ' ').Replace('>', ' ') + '.').ToList();
result = HighlightText(lines, terms);
}
else
{
var sentences = lines.Take(2).Select(x => string.Format("... {0} ...", x.Trim().Replace('<', ' ').Replace('>', ' ').ToList()));
result = string.Join("\n", sentences);
}
return result;
}
19
Source : ProjectWriter.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static string WriteProject(Example example, string selectedPath, string replacedembliesPath, bool showMessageBox = true)
{
var files = new Dictionary<string, string>();
var replacedembly = typeof(ProjectWriter).replacedembly;
var names = replacedembly.GetManifestResourceNames();
var templateFiles = names.Where(x => x.Contains("Templates")).ToList();
foreach (var templateFile in templateFiles)
{
var fileName = GetFileNameFromNs(templateFile);
using (var s = replacedembly.GetManifestResourceStream(templateFile))
{
if (s == null) break;
using (var sr = new StreamReader(s))
{
files.Add(fileName, sr.ReadToEnd());
}
}
}
string projectName = "SciChart_" + Regex.Replace(example.replacedle, @"[^A-Za-z0-9]+", string.Empty);
files[ProjectFileName] = GenerateProjectFile(files[ProjectFileName], example, replacedembliesPath);
files[SolutionFileName] = GenerateSolutionFile(files[SolutionFileName], projectName);
files.RenameKey(ProjectFileName, projectName + ".csproj");
files.RenameKey(SolutionFileName, projectName + ".sln");
files[MainWindowFileName] = GenerateShellFile(files[MainWindowFileName], example).Replace("[Examplereplacedle]", example.replacedle);
foreach (var codeFile in example.SourceFiles)
{
files.Add(codeFile.Key, codeFile.Value);
}
WriteProjectFiles(files, Path.Combine(selectedPath, projectName));
if (showMessageBox && Application.Current.MainWindow != null)
{
var message = $"The {example.replacedle} example was successfully exported to {selectedPath + projectName}";
MessageBox.Show(Application.Current.MainWindow, message, "Success!");
}
return projectName;
}
19
Source : AutomationTestBase.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public WriteableBitmap LoadResource(string resourceName)
{
resourceName = resourceName.Replace("/", ".");
WriteableBitmap expectedBitmap = null;
var replacedembly = GetType().replacedembly;
// For testing purposes, to see all the resources available
var resourcePath = replacedembly.GetManifestResourceNames().FirstOrDefault(x => x.ToUpper().Contains(resourceName.ToUpper()));
using (var resourceStream = replacedembly.GetManifestResourceStream(resourcePath))
{
expectedBitmap = Path.GetExtension(resourceName).ToUpper() == ".BMP"
? DecodeBmpStream(resourceStream)
: DecodePngStream(resourceStream);
}
return expectedBitmap;
}
19
Source : HtmlExportHelper.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static void ExportIndexToHtml(IModule module)
{
var replacedembly = typeof(HtmlExportHelper).replacedembly;
string[] names = replacedembly.GetManifestResourceNames();
var templateFile = names.SingleOrDefault(x => x.Contains(IndexTemplateFileName));
using (var s = replacedembly.GetManifestResourceStream(templateFile))
using (var sr = new StreamReader(s))
{
string lines = sr.ReadToEnd();
StringBuilder sb = new StringBuilder();
foreach (var categoryGroup in module.Examples.Values.GroupBy(x => x.TopLevelCategory))
{
sb.Append("<h2>").Append(categoryGroup.Key).Append("</h2>").Append(Environment.NewLine);
foreach (var exampleGroup in categoryGroup.GroupBy(x => x.Group))
{
sb.Append("<h4>").Append(exampleGroup.Key).Append("</h4>").Append(Environment.NewLine);
sb.Append("<ul>").Append(Environment.NewLine);
foreach (var example in exampleGroup)
{
var fileName = string.Format("wpf-{0}chart-example-{1}",
example.TopLevelCategory.ToUpper().Contains("3D") || example.replacedle.ToUpper().Contains("3D") ? "3d-" : string.Empty,
example.replacedle.ToLower().Replace(" ", "-"));
sb.Append("<li>").Append("<a href=\"").Append(fileName).Append("\">").Append(example.replacedle).Append("</a></li>");
}
sb.Append("</ul>").Append(Environment.NewLine);
}
}
lines = lines.Replace("[Index]", sb.ToString());
File.WriteAllText(Path.Combine(ExportPath, "wpf-chart-examples.html"), lines);
}
}
19
Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static string[] GetStopWords(string fileName, char splitter)
{
replacedembly replacedembly = typeof (CreateInvertedIndex).replacedembly;
var names = replacedembly.GetManifestResourceNames();
var allExampleSourceFiles = names.Where(x => x.Contains(fileName));
var file = allExampleSourceFiles.FirstOrDefault();
var result = new string[] {};
if (file != null)
{
using (var s = replacedembly.GetManifestResourceStream(file))
using (var sr = new StreamReader(s))
{
var readToEnd = sr.ReadToEnd();
result = readToEnd.Split(splitter);
result = result.Select(x =>
{
if (x.Contains("\n"))
return x.Replace("\n", "");
return x;
}).ToArray();
}
}
return result;
}
19
Source : CustomChangeThemeModifier.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void Export(string filter, bool useXaml, Size? size = null)
{
var saveFileDialog = new SaveFileDialog
{
Filter = filter,
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
};
if (saveFileDialog.ShowDialog() == true)
{
if (!(ParentSurface is SciChartSurface surface)) return;
var exportType = filter.ToUpper().Contains("XPS") ? ExportType.Xps : ExportType.Png;
if (size.HasValue)
{
surface.ExportToFile(saveFileDialog.FileName, exportType, useXaml, size.Value);
}
else
{
surface.ExportToFile(saveFileDialog.FileName, exportType, useXaml);
}
try
{
Process.Start(saveFileDialog.FileName);
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == 1155)
{
MessageBox.Show("Can't open because no application is replacedociated with the specified file for this operation.", "Exported successfully!");
}
}
}
}
19
Source : DataManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public IEnumerable<TimeFrame> GetAvailableTimeFrames(Instrument forInstrument)
{
if (_availableTimeFrames == null)
{
lock (typeof (DataManager))
{
if (_availableTimeFrames == null)
{
// Initialise the Timeframe dictionary
_availableTimeFrames = new Dictionary<Instrument, IList<TimeFrame>>();
foreach (var instr in AvailableInstruments)
{
_availableTimeFrames[instr] = new List<TimeFrame>();
}
var replacedembly = typeof (DataManager).replacedembly;
foreach (var resourceString in replacedembly.GetManifestResourceNames())
{
if (resourceString.Contains("_"))
{
var instrument = Instrument.Parse(GetSubstring(resourceString, ResourceDirectory + ".", "_"));
var timeframe = TimeFrame.Parse(GetSubstring(resourceString, "_", ".csv.gz"));
_availableTimeFrames[instrument].Add(timeframe);
}
}
}
}
}
return _availableTimeFrames[forInstrument];
}
See More Examples