Here are the examples of the csharp api object.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
22368 Examples
19
Source : SimNetwork.cs
with MIT License
from abdullin
with MIT License
from abdullin
public string BodyString() {
var body = Payload == null ? "" : Payload.ToString();
if (Flag != SimFlag.None) {
body += $" {Flag.ToString().ToUpperInvariant()}";
}
return body.Trim();
}
19
Source : Converters.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return double.TryParse(value?.ToString(), out double result) ? result : 1d;
}
19
Source : OVRNetwork.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public void StartListening(int listeningPort)
{
if (tcpListener != null)
{
Debug.LogWarning("[OVRNetworkTcpServer] tcpListener is not null");
return;
}
IPAddress localAddr = IPAddress.Any;
tcpListener = new TcpListener(localAddr, listeningPort);
try
{
tcpListener.Start();
Debug.LogFormat("TcpListener started. Local endpoint: {0}", tcpListener.LocalEndpoint.ToString());
}
catch (SocketException e)
{
Debug.LogWarningFormat("[OVRNetworkTcpServer] Unsable to start TcpListener. Socket exception: {0}", e.Message);
Debug.LogWarning("It could be caused by multiple instances listening at the same port, or the port is forwarded to the Android device through ADB");
Debug.LogWarning("If the port is forwarded through ADB, use the Android Tools in Tools/Oculus/System Metrics Profiler to kill the server");
tcpListener = null;
}
if (tcpListener != null)
{
Debug.LogFormat("[OVRNetworkTcpServer] Start Listening on port {0}", listeningPort);
try
{
tcpListener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), tcpListener);
}
catch (Exception e)
{
Debug.LogWarningFormat("[OVRNetworkTcpServer] can't accept new client: {0}", e.Message);
}
}
}
19
Source : OVRNetwork.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
void ConnectCallback(IAsyncResult ar)
{
try
{
TcpClient client = ar.AsyncState as TcpClient;
client.EndConnect(ar);
Debug.LogFormat("[OVRNetworkTcpClient] connected to {0}", client.ToString());
}
catch (Exception e)
{
Debug.LogWarningFormat("[OVRNetworkTcpClient] connect error {0}", e.Message);
}
if (connectionStateChangedCallback != null)
{
connectionStateChangedCallback();
}
}
19
Source : CreateACustomFreeSurface3DChart.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void PaletteModeComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (customFreeSurfaceRenderableSeries == null)
return;
switch (((ContentControl)e.AddedItems[0]).Content.ToString())
{
case "Radial":
customFreeSurfaceRenderableSeries.PaletteMinMaxMode = FreeSurfacePaletteMinMaxMode.Relative;
customFreeSurfaceRenderableSeries.PaletteMinimum = new Vector3(0.0f, 5.0f, 0.0f);
customFreeSurfaceRenderableSeries.PaletteMaximum = new Vector3(0.0f, 7.0f, 0.0f);
customFreeSurfaceRenderableSeries.PaletteRadialFactor = 1.0;
customFreeSurfaceRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
customFreeSurfaceRenderableSeries.PaletteAzimuthalFactor = 0.0;
customFreeSurfaceRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Axial":
customFreeSurfaceRenderableSeries.PaletteMinMaxMode = FreeSurfacePaletteMinMaxMode.Absolute;
customFreeSurfaceRenderableSeries.PaletteMinimum = new Vector3(0.0f, -2.0f, 0.0f);
customFreeSurfaceRenderableSeries.PaletteMaximum = new Vector3(0.0f, 2.0f, 0.0f);
customFreeSurfaceRenderableSeries.PaletteRadialFactor = 0.0;
customFreeSurfaceRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 1.0f, 0.0f);
customFreeSurfaceRenderableSeries.PaletteAzimuthalFactor = 0.0;
customFreeSurfaceRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Azimuthal":
customFreeSurfaceRenderableSeries.PaletteRadialFactor = 0.0;
customFreeSurfaceRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
customFreeSurfaceRenderableSeries.PaletteAzimuthalFactor = 1.0;
customFreeSurfaceRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Polar":
customFreeSurfaceRenderableSeries.PaletteRadialFactor = 0.0;
customFreeSurfaceRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
customFreeSurfaceRenderableSeries.PaletteAzimuthalFactor = 0.0;
customFreeSurfaceRenderableSeries.PalettePolarFactor = 1.0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
19
Source : CreateACylinderMesh3DChart.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void PaletteModeComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (cylinderMeshRenderableSeries == null)
return;
switch (((ContentControl)e.AddedItems[0]).Content.ToString())
{
case "Radial":
cylinderMeshRenderableSeries.PaletteMinMaxMode = FreeSurfacePaletteMinMaxMode.Relative;
cylinderMeshRenderableSeries.PaletteMinimum = new Vector3(0.0f, 5.0f, 0.0f);
cylinderMeshRenderableSeries.PaletteMaximum = new Vector3(0.0f, 7.0f, 0.0f);
cylinderMeshRenderableSeries.PaletteRadialFactor = 1.0;
cylinderMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
cylinderMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
cylinderMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Axial":
cylinderMeshRenderableSeries.PaletteMinMaxMode = FreeSurfacePaletteMinMaxMode.Absolute;
cylinderMeshRenderableSeries.PaletteMinimum = new Vector3(0.0f, -4.0f, 0.0f);
cylinderMeshRenderableSeries.PaletteMaximum = new Vector3(0.0f, 4.0f, 0.0f);
cylinderMeshRenderableSeries.PaletteRadialFactor = 0.0;
cylinderMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 1.0f, 0.0f);
cylinderMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
cylinderMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Azimuthal":
cylinderMeshRenderableSeries.PaletteRadialFactor = 0.0;
cylinderMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
cylinderMeshRenderableSeries.PaletteAzimuthalFactor = 1.0;
cylinderMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Polar":
cylinderMeshRenderableSeries.PaletteRadialFactor = 0.0;
cylinderMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
cylinderMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
cylinderMeshRenderableSeries.PalettePolarFactor = 1.0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
19
Source : CreateACylindroidMesh3DChart.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void PaletteModeComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (cylindroidMeshRenderableSeries == null)
return;
switch (((ContentControl)e.AddedItems[0]).Content.ToString())
{
case "Radial":
cylindroidMeshRenderableSeries.PaletteMinMaxMode = FreeSurfacePaletteMinMaxMode.Relative;
cylindroidMeshRenderableSeries.PaletteMinimum = new Vector3(3.0f, 0.0f, 0.0f);
cylindroidMeshRenderableSeries.PaletteMaximum = new Vector3(4.0f, 0.0f, 0.0f);
cylindroidMeshRenderableSeries.PaletteRadialFactor = 1.0;
cylindroidMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
cylindroidMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
cylindroidMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Axial":
cylindroidMeshRenderableSeries.PaletteMinMaxMode = FreeSurfacePaletteMinMaxMode.Absolute;
cylindroidMeshRenderableSeries.PaletteMinimum = new Vector3(0.0f, -4.0f, 0.0f);
cylindroidMeshRenderableSeries.PaletteMaximum = new Vector3(0.0f, 4.0f, 0.0f);
cylindroidMeshRenderableSeries.PaletteRadialFactor = 0.0;
cylindroidMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 1.0f, 0.0f);
cylindroidMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
cylindroidMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Azimuthal":
cylindroidMeshRenderableSeries.PaletteRadialFactor = 0.0;
cylindroidMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
cylindroidMeshRenderableSeries.PaletteAzimuthalFactor = 1.0;
cylindroidMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Polar":
cylindroidMeshRenderableSeries.PaletteRadialFactor = 0.0;
cylindroidMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
cylindroidMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
cylindroidMeshRenderableSeries.PalettePolarFactor = 1.0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
19
Source : CreateAnEllipsoidMesh3DChart.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void PaletteModeComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ellipsoidMeshRenderableSeries == null)
return;
switch (((ContentControl)e.AddedItems[0]).Content.ToString())
{
case "Radial":
ellipsoidMeshRenderableSeries.PaletteMinMaxMode = FreeSurfacePaletteMinMaxMode.Relative;
ellipsoidMeshRenderableSeries.PaletteMinimum = new Vector3(0.0f, 6.0f, 0.0f);
ellipsoidMeshRenderableSeries.PaletteMaximum = new Vector3(0.0f, 7.0f, 0.0f);
ellipsoidMeshRenderableSeries.PaletteRadialFactor = 1.0;
ellipsoidMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
ellipsoidMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
ellipsoidMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Axial":
ellipsoidMeshRenderableSeries.PaletteMinMaxMode = FreeSurfacePaletteMinMaxMode.Absolute;
ellipsoidMeshRenderableSeries.PaletteMinimum = new Vector3(0.0f, -4.0f, 0.0f);
ellipsoidMeshRenderableSeries.PaletteMaximum = new Vector3(0.0f, 4.0f, 0.0f);
ellipsoidMeshRenderableSeries.PaletteRadialFactor = 0.0;
ellipsoidMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 1.0f, 0.0f);
ellipsoidMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
ellipsoidMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Azimuthal":
ellipsoidMeshRenderableSeries.PaletteRadialFactor = 0.0;
ellipsoidMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
ellipsoidMeshRenderableSeries.PaletteAzimuthalFactor = 1.0;
ellipsoidMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Polar":
ellipsoidMeshRenderableSeries.PaletteRadialFactor = 0.0;
ellipsoidMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
ellipsoidMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
ellipsoidMeshRenderableSeries.PalettePolarFactor = 1.0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
19
Source : CreateAPolarMesh3DChart.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void PaletteModeComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (polarMeshRenderableSeries == null)
return;
switch (((ContentControl)e.AddedItems[0]).Content.ToString())
{
case "Radial":
polarMeshRenderableSeries.PaletteMinMaxMode = FreeSurfacePaletteMinMaxMode.Relative;
polarMeshRenderableSeries.PaletteMinimum = new Vector3(0.0f, 0.0f, 0.0f);
polarMeshRenderableSeries.PaletteMaximum = new Vector3(0.0f, 0.5f, 0.0f);
polarMeshRenderableSeries.PaletteRadialFactor = 1.0;
polarMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
polarMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
polarMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Axial":
polarMeshRenderableSeries.PaletteMinMaxMode = FreeSurfacePaletteMinMaxMode.Absolute;
polarMeshRenderableSeries.PaletteMinimum = new Vector3(-5.0f, 0.0f, -5.0f);
polarMeshRenderableSeries.PaletteMaximum = new Vector3(5.0f, 0.0f, 5.0f);
polarMeshRenderableSeries.PaletteRadialFactor = 0.0;
polarMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.5f, 0.0f, 0.5f);
polarMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
polarMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Azimuthal":
polarMeshRenderableSeries.PaletteRadialFactor = 0.0;
polarMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
polarMeshRenderableSeries.PaletteAzimuthalFactor = 1.0;
polarMeshRenderableSeries.PalettePolarFactor = 0.0;
break;
case "Polar":
polarMeshRenderableSeries.PaletteRadialFactor = 0.0;
polarMeshRenderableSeries.PaletteAxialFactor = new Vector3(0.0f, 0.0f, 0.0f);
polarMeshRenderableSeries.PaletteAzimuthalFactor = 0.0;
polarMeshRenderableSeries.PalettePolarFactor = 1.0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
19
Source : ToValidDateTimeConverter.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private object ValidateDate(object value, object parameter)
{
var newDate = (DateTime) value;
switch (parameter.ToString())
{
case "Max":
if (XVisibleRange.Min >= newDate)
{
newDate = XVisibleRange.Max;
}
break;
case "Min":
if (XVisibleRange.Max <= newDate)
{
newDate = XVisibleRange.Min;
}
break;
}
return newDate;
}
19
Source : StrongTyped.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public override string ToString()
{
return Value.ToString();
}
19
Source : TextToBooleanConverter.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var valueString = value.ToString();
return !valueString.IsEmpty();
}
19
Source : Host.cs
with MIT License
from acandylevey
with MIT License
from acandylevey
public void SendMessage(JObject data)
{
Log.LogMessage("Sending Message:" + JsonConvert.SerializeObject(data));
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data.ToString(Formatting.None));
Stream stdout = Console.OpenStandardOutput();
stdout.WriteByte((byte)((bytes.Length >> 0) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 8) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 16) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 24) & 0xFF));
stdout.Write(bytes, 0, bytes.Length);
stdout.Flush();
}
19
Source : FileCacheTest.cs
with Apache License 2.0
from acarteas
with Apache License 2.0
from acarteas
[TestMethod]
public void DefaultRegionTest()
{
FileCache cacheWithDefaultRegion = new FileCache();
cacheWithDefaultRegion.DefaultRegion = "foo";
FileCache defaultCache = new FileCache();
cacheWithDefaultRegion["foo"] = "bar";
object pull = defaultCache.Get("foo", "foo");
pull.ToString().Should().Be("bar");
cacheWithDefaultRegion.Flush();
defaultCache.Flush();
}
19
Source : FileCacheTest.cs
with Apache License 2.0
from acarteas
with Apache License 2.0
from acarteas
[TestMethod]
public void ClearCache()
{
_cache = new FileCache();
_cache["MyFirstKey"] = "MyFirstValue";
_cache.Add("MySecondKey", "MySecondValue", _cache.DefaultPolicy, "MyFirstRegion");
object pull = _cache.Get("MyFirstKey");
pull.ToString().Should().Be("MyFirstValue");
object pull2 = _cache.Get("MySecondKey", "MyFirstRegion");
pull2.ToString().Should().Be("MySecondValue");
_cache.Clear();
object result = _cache.Get("MyFirstKey");
result.Should().BeNull();
object result2 = _cache.Get("MySecondKey", "MyFirstRegion");
result2.Should().BeNull();
}
19
Source : RecordFSReaderBase.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
protected virtual string GetPath(TId id) => Paths.GetDataFile(RootPath, id?.ToString() ?? throw new Exception("Id is empty."));
19
Source : ChromiumBrowser.cs
with MIT License
from acandylevey
with MIT License
from acandylevey
public bool IsRegistered(string Hostname, string ManifestPath)
{
string targetKeyPath = regHostnameKeyLocation + Hostname;
RegistryKey regKey = Registry.CurrentUser.OpenSubKey(targetKeyPath, true);
if (regKey != null && regKey.GetValue("").ToString() == ManifestPath)
return true;
return false;
}
19
Source : LazyTreeNode.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public override string ToString() => Content.ToString();
19
Source : CompareConverters.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var left = double.Parse(value.ToString());
var right = double.Parse(parameter.ToString());
return left < right;
}
19
Source : CompareConverters.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var left = double.Parse(value.ToString());
var right = double.Parse(parameter.ToString());
return left > right;
}
19
Source : MinusConverter.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var left = double.Parse(values[0].ToString());
var right = double.Parse(values[1].ToString());
return left - right;
}
19
Source : PlusConverter.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
double? result = values.Select(value => double.Parse(value.ToString())).Aggregate((sum, value) => sum + value);
return result <= 0 ? null : result;
}
19
Source : StringToImageConverter.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var firstLetter = value.ToString().First().ToString();
var temp = new DrawingVisual();
var c = temp.RenderOpen();
var typeface = new Typeface(new FontFamily("Microsoft YaHei"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
c.DrawRectangle(Brushes.BlueViolet, null, new Rect(new Size(32, 32)));
c.DrawText(new FormattedText(firstLetter, culture, FlowDirection.LeftToRight, typeface, 16, Brushes.White), new Point(8, 5));
c.Close();
var image = new DrawingImage(temp.Drawing);
return image;
}
19
Source : ConnectionListener.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private void OnDataReceive(IAsyncResult result)
{
EndPoint clientEndPoint = null;
try
{
clientEndPoint = new IPEndPoint(listeningHost, 0);
int dataSize = Socket.EndReceiveFrom(result, ref clientEndPoint);
IPEndPoint ipEndpoint = (IPEndPoint)clientEndPoint;
// TO-DO: generate ban entries here based on packet rates of endPoint, IP Address, and IP Address Range
if (packetLog.IsDebugEnabled)
{
byte[] data = new byte[dataSize];
Buffer.BlockCopy(buffer, 0, data, 0, dataSize);
StringBuilder sb = new StringBuilder();
sb.AppendLine($"Received Packet (Len: {data.Length}) [{ipEndpoint.Address}:{ipEndpoint.Port}=>{ListenerEndpoint.Address}:{ListenerEndpoint.Port}]");
sb.AppendLine(data.BuildPacketString());
packetLog.Debug(sb.ToString());
}
var packet = new ClientPacket();
if (packet.Unpack(buffer, dataSize))
NetworkManager.ProcessPacket(this, packet, ipEndpoint);
packet.ReleaseBuffer();
}
catch (SocketException socketException)
{
// If we get "Connection has been forcibly closed..." error, just eat the exception and continue on
// This gets sent when the remote host terminates the connection (on UDP? interesting...)
// TODO: There might be more, should keep an eye out. Logged message will help here.
if (socketException.SocketErrorCode == SocketError.MessageSize ||
socketException.SocketErrorCode == SocketError.NetworkReset ||
socketException.SocketErrorCode == SocketError.ConnectionReset)
{
log.DebugFormat("ConnectionListener.OnDataReceieve() has thrown {0}: {1} from client {2}", socketException.SocketErrorCode, socketException.Message, clientEndPoint != null ? clientEndPoint.ToString() : "Unknown");
}
else
{
log.FatalFormat("ConnectionListener.OnDataReceieve() has thrown {0}: {1} from client {2}", socketException.SocketErrorCode, socketException.Message, clientEndPoint != null ? clientEndPoint.ToString() : "Unknown");
return;
}
}
Listen();
}
19
Source : Extensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static string BuildPacketString(this byte[] bytes, int startPosition = 0, int bytesToOutput = 9999)
{
TextWriter tw = new StringWriter();
byte[] buffer = bytes;
int column = 0;
int row = 0;
int columns = 16;
tw.Write(" x ");
for (int i = 0; i < columns; i++)
{
tw.Write(i.ToString().PadLeft(3));
}
tw.WriteLine(" |Text");
tw.Write(" 0 ");
string asciiLine = "";
for (int i = startPosition; i < startPosition+bytesToOutput; i++)
{
if (i >= buffer.Length) {
break;
}
if (column >= columns)
{
row++;
column = 0;
tw.WriteLine(" |" + asciiLine);
asciiLine = "";
tw.Write((row * columns).ToString().PadLeft(4));
tw.Write(" ");
}
tw.Write(buffer[i].ToString("X2").PadLeft(3));
if (Char.IsControl((char)buffer[i]))
asciiLine += " ";
else
asciiLine += (char)buffer[i];
column++;
}
tw.Write("".PadLeft((columns - column) * 3));
tw.WriteLine(" |" + asciiLine);
return tw.ToString();
}
19
Source : CommandParameterHelpers.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool ResolveACEParameters(Session session, IEnumerable<string> aceParsedParameters, IEnumerable<ACECommandParameter> parameters, bool rawIncluded = false)
{
string parameterBlob = "";
if (rawIncluded)
{
parameterBlob = aceParsedParameters.First();
}
else
{
parameterBlob = aceParsedParameters.Count() > 0 ? aceParsedParameters.Aggregate((a, b) => a + " " + b).Trim(new char[] { ' ', ',' }) : string.Empty;
}
int commaCount = parameterBlob.Count(x => x == ',');
List<ACECommandParameter> acps = parameters.ToList();
for (int i = acps.Count - 1; i > -1; i--)
{
ACECommandParameter acp = acps[i];
acp.ParameterNo = i + 1;
if (parameterBlob.Length > 0)
{
try
{
switch (acp.Type)
{
case ACECommandParameterType.PositiveLong:
Match match4 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match4.Success)
{
if (!long.TryParse(match4.Groups[1].Value, out long val))
{
return false;
}
if (val <= 0)
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match4.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match4.Groups[1].Index).Trim(new char[] { ' ' });
}
break;
case ACECommandParameterType.Long:
Match match3 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match3.Success)
{
if (!long.TryParse(match3.Groups[1].Value, out long val))
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match3.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match3.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
break;
case ACECommandParameterType.ULong:
Match match2 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match2.Success)
{
if (!ulong.TryParse(match2.Groups[1].Value, out ulong val))
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match2.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match2.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
break;
case ACECommandParameterType.Location:
Position position = null;
Match match = Regex.Match(parameterBlob, @"([\d\.]+[ns])[^\d\.]*([\d\.]+[ew])$", RegexOptions.IgnoreCase);
if (match.Success)
{
string ns = match.Groups[1].Value;
string ew = match.Groups[2].Value;
if (!TryParsePosition(new string[] { ns, ew }, out string errorMessage, out position))
{
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMessage, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMessage);
}
return false;
}
else
{
acp.Value = position;
acp.Defaulted = false;
int coordsStartPos = Math.Min(match.Groups[1].Index, match.Groups[2].Index);
parameterBlob = (coordsStartPos == 0) ? string.Empty : parameterBlob.Substring(0, coordsStartPos).Trim(new char[] { ' ', ',' });
}
}
break;
case ACECommandParameterType.OnlinePlayerName:
if (i != 0)
{
throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
}
parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
Player targetPlayer = PlayerManager.GetOnlinePlayer(parameterBlob);
if (targetPlayer == null)
{
string errorMsg = $"Unable to find player {parameterBlob}";
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMsg);
}
return false;
}
else
{
acp.Value = targetPlayer;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.OnlinePlayerNameOrIid:
if (i != 0)
{
throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
}
if (!parameterBlob.Contains(' '))
{
if (uint.TryParse(parameterBlob, out uint iid))
{
Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
if (targetPlayer2 == null)
{
string logMsg = $"Unable to find player with iid {iid}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer2;
acp.Defaulted = false;
break;
}
}
}
Player targetPlayer3 = PlayerManager.GetOnlinePlayer(parameterBlob);
if (targetPlayer3 == null)
{
string logMsg = $"Unable to find player {parameterBlob}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer3;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.OnlinePlayerIid:
Match matcha5 = Regex.Match(parameterBlob, /*((i == 0) ? "" : @"\s+") +*/ @"(\d{10})$|(0x[0-9a-f]{8})$", RegexOptions.IgnoreCase);
if (matcha5.Success)
{
string strIid = "";
if (matcha5.Groups[2].Success)
{
strIid = matcha5.Groups[2].Value;
}
else if (matcha5.Groups[1].Success)
{
strIid = matcha5.Groups[1].Value;
}
try
{
uint iid = 0;
if (strIid.StartsWith("0x"))
{
iid = Convert.ToUInt32(strIid, 16);
}
else
{
iid = uint.Parse(strIid);
}
Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
if (targetPlayer2 == null)
{
string logMsg = $"Unable to find player with iid {strIid}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer2;
acp.Defaulted = false;
parameterBlob = (matcha5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, matcha5.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
}
catch (Exception)
{
string errorMsg = $"Unable to parse {strIid} into a player iid";
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMsg);
}
return false;
}
}
break;
case ACECommandParameterType.PlayerName:
if (i != 0)
{
throw new Exception("Player name parameter must be the first parameter, since it can contain spaces.");
}
parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
if (string.IsNullOrWhiteSpace(parameterBlob))
{
break;
}
else
{
acp.Value = parameterBlob;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.Uri:
Match match5 = Regex.Match(parameterBlob, @"(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))$", RegexOptions.IgnoreCase);
if (match5.Success)
{
string strUri = match5.Groups[1].Value;
try
{
Uri url = new Uri(strUri);
acp.Value = url;
acp.Defaulted = false;
parameterBlob = (match5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match5.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.DoubleQuoteEnclosedText:
Match match6 = Regex.Match(parameterBlob.TrimEnd(), @"(\"".*\"")$", RegexOptions.IgnoreCase);
if (match6.Success)
{
string txt = match6.Groups[1].Value;
try
{
acp.Value = txt.Trim('"');
acp.Defaulted = false;
parameterBlob = (match6.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match6.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.CommaPrefixedText:
if (i == 0)
{
throw new Exception("this parameter type is not appropriate as the first parameter");
}
if (i == acps.Count - 1 && !acp.Required && commaCount < acps.Count - 1)
{
break;
}
Match match7 = Regex.Match(parameterBlob.TrimEnd(), @"\,\s*([^,]*)$", RegexOptions.IgnoreCase);
if (match7.Success)
{
string txt = match7.Groups[1].Value;
try
{
acp.Value = txt.TrimStart(new char[] { ' ', ',' });
acp.Defaulted = false;
parameterBlob = (match7.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match7.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.SimpleWord:
Match match8 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
if (match8.Success)
{
string txt = match8.Groups[1].Value;
try
{
acp.Value = txt.TrimStart(' ');
acp.Defaulted = false;
parameterBlob = (match8.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match8.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.Enum:
if (acp.PossibleValues == null)
{
throw new Exception("The enum parameter type must be accompanied by the PossibleValues");
}
if (!acp.PossibleValues.IsEnum)
{
throw new Exception("PossibleValues must be an enum type");
}
Match match9 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
if (match9.Success)
{
string txt = match9.Groups[1].Value;
try
{
txt = txt.Trim(new char[] { ' ', ',' });
Array etvs = Enum.GetValues(acp.PossibleValues);
foreach (object etv in etvs)
{
if (etv.ToString().ToLower() == txt.ToLower())
{
acp.Value = etv;
acp.Defaulted = false;
parameterBlob = (match9.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match9.Groups[1].Index).Trim(new char[] { ' ' });
break;
}
}
}
catch (Exception)
{
return false;
}
}
break;
}
}
catch
{
return false;
}
}
if (acp.Defaulted)
{
acp.Value = acp.DefaultValue;
}
if (acp.Required && acp.Defaulted)
{
if (!string.IsNullOrWhiteSpace(acp.ErrorMessage))
{
if (session != null)
{
ChatPacket.SendServerMessage(session, acp.ErrorMessage, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(acp.ErrorMessage);
}
}
return false;
}
}
return true;
}
19
Source : NegatableBooleanToVisibilityConverter.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool bVal;
bool result = bool.TryParse(value.ToString(), out bVal);
if (!result) return value;
if (bVal && !Negate) return Visibility.Visible;
if (bVal && Negate) return FalseVisibility;
if (!bVal && Negate) return Visibility.Visible;
if (!bVal && !Negate) return FalseVisibility;
else return Visibility.Visible;
}
19
Source : TippingManager.cs
with MIT License
from acid-chicken
with MIT License
from acid-chicken
public static async Task<string> InvokeMethodAsync(params object[] args)
{
using (var process = Process.Start(new ProcessStartInfo("bitzeny-cli", string.Join(' ', args.Select(x => x == null || x is bool || x is sbyte || x is byte || x is short || x is ushort || x is int || x is uint || x is long || x is ulong || x is float || x is double || x is decimal ? x.ToString() : $"\"{x}\"")))
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}))
using (var reader = process.StandardOutput)
{
var output = await reader.ReadToEndAsync().ConfigureAwait(false);
process.WaitForExit();
process.Close();
return output.Trim();
}
}
19
Source : SheetFilter.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
public Predicate<object> GetFilter()
{
string properyName = FilterPropertyName;
switch (FilterPropertyName)
{
case "Export Name":
var m = FirstDigitOfLastNumberInString(FilterValue);
if (m == null)
{
return null;
}
return item => m == FirstDigitOfLastNumberInString((item as ExportSheet).FullExportName);
case "Number":
var n = FirstDigitOfLastNumberInString(FilterValue);
if (n == null)
{
return null;
}
return item => n == FirstDigitOfLastNumberInString((item as ExportSheet).SheetNumber);
case "Name":
properyName = "SheetDescription";
var noNumbers = Regex.Replace(FilterValue, "[0-9-]", @" ");
string[] parts = noNumbers.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
return item => parts.Any(item.GetType().GetProperty(properyName).GetValue(item, null).ToString().Contains);
case "Revision":
properyName = "SheetRevision";
break;
case "Revision Description":
properyName = "SheetRevisionDescription";
break;
case "Revision Date":
properyName = "SheetRevisionDate";
break;
case "Scale":
properyName = "Scale";
break;
case "North Point":
properyName = "NorthPointVisibilityString";
break;
default:
return null;
}
return item => item.GetType().GetProperty(properyName).GetValue(item, null).ToString().Equals(FilterValue, StringComparison.InvariantCulture);
}
19
Source : CheckUtil.cs
with MIT License
from actions
with MIT License
from actions
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
base.OnEventWritten(eventData);
lock (_lock)
{
if (_ignoredEvent.TryGetValue(eventData.EventSource.Name, out var ignored) &&
ignored.Contains(eventData.EventName))
{
return;
}
_logs.Add($"{DateTime.UtcNow.ToString("O")} [START {eventData.EventSource.Name} - {eventData.EventName}]");
_logs.AddRange(eventData.Payload.Select(x => string.Join(Environment.NewLine, x.ToString().Split(Environment.NewLine).Select(y => $"{DateTime.UtcNow.ToString("O")} {y}"))));
_logs.Add($"{DateTime.UtcNow.ToString("O")} [END {eventData.EventSource.Name} - {eventData.EventName}]");
}
}
19
Source : JsonExtensions.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
public static JObject InsertToken<T>(this JObject parent, string property, T token) where T : JToken
{
if (token != null)
parent[property] = token.ToString(formatting: Newtonsoft.Json.Formatting.None);
return parent;
}
19
Source : HostContext.cs
with MIT License
from actions
with MIT License
from actions
void IObserver<KeyValuePair<string, object>>.OnNext(KeyValuePair<string, object> value)
{
_netcoreHttpTrace.Info($"Trace {value.Key} event:{Environment.NewLine}{value.Value.ToString()}");
}
19
Source : UriExtensions.cs
with MIT License
from actions
with MIT License
from actions
public static void AddMultiple<T>(this NameValueCollection collection, String name, IEnumerable<T> values, Func<T, String> convert)
{
ArgumentUtility.CheckForNull(collection, "collection");
ArgumentUtility.CheckStringForNullOrEmpty(name, "name");
if (convert == null) convert = (val) => val.ToString();
if (values != null)
{
foreach (var value in values)
{
collection.Add(name, convert(value));
}
}
}
19
Source : ExpressionValue.cs
with MIT License
from actions
with MIT License
from actions
public override String ToString()
{
if (!String.IsNullOrEmpty(m_expression))
{
return String.Concat("$[ ", m_expression, " ]");
}
else
{
return m_literalValue?.ToString();
}
}
19
Source : PropertyValidation.cs
with MIT License
from actions
with MIT License
from actions
public static void ValidatePropertyValue(String propertyName, Object value)
{
// Keep this consistent with XmlPropertyWriter.Write.
if (null != value)
{
Type type = value.GetType();
TypeCode typeCode = Type.GetTypeCode(type);
if (type.IsEnum)
{
ValidateStringValue(propertyName, ((Enum)value).ToString("D"));
}
else if (typeCode == TypeCode.Object && value is byte[])
{
ValidateByteArray(propertyName, (byte[])value);
}
else if (typeCode == TypeCode.Object && value is Guid)
{
//treat Guid like the other valid primitive types that
//don't have explicit columns, e.g. it gets stored as a string
ValidateStringValue(propertyName, ((Guid)value).ToString("N"));
}
else if (typeCode == TypeCode.Object)
{
throw new PropertyTypeNotSupportedException(propertyName, type);
}
else if (typeCode == TypeCode.DBNull)
{
throw new PropertyTypeNotSupportedException(propertyName, type);
}
else if (typeCode == TypeCode.Empty)
{
// should be impossible with null check above, but just in case.
throw new PropertyTypeNotSupportedException(propertyName, type);
}
else if (typeCode == TypeCode.Int32)
{
ValidateInt32(propertyName, (int)value);
}
else if (typeCode == TypeCode.Double)
{
ValidateDouble(propertyName, (double)value);
}
else if (typeCode == TypeCode.DateTime)
{
ValidateDateTime(propertyName, (DateTime)value);
}
else if (typeCode == TypeCode.String)
{
ValidateStringValue(propertyName, (String)value);
}
else
{
// Here are the remaining types. All are supported over in DbArtifactPropertyValueColumns.
// With a property definition they'll be strongly-typed when they're read back.
// Otherwise they read back as strings.
// Boolean
// Char
// SByte
// Byte
// Int16
// UInt16
// UInt32
// Int64
// UInt64
// Single
// Decimal
ValidateStringValue(propertyName, value.ToString());
}
}
}
19
Source : TemplateUnraveler.cs
with MIT License
from actions
with MIT License
from actions
private String DumpState()
{
var result = new StringBuilder();
if (m_current == null)
{
result.AppendLine("State: (null)");
}
else
{
result.AppendLine("State:");
result.AppendLine();
// Push state hierarchy
var stack = new Stack<ReaderState>();
var curr = m_current;
while (curr != null)
{
result.AppendLine(curr.ToString());
curr = curr.Parent;
}
}
return result.ToString();
}
19
Source : JsonWebTokenUtilities.cs
with MIT License
from actions
with MIT License
from actions
internal static IEnumerable<Claim> TranslateFromJwtClaims(IDictionary<string, object> claims)
{
ArgumentUtility.CheckForNull(claims, nameof(claims));
List<Claim> ret = new List<Claim>();
//there are two claim names that get special treatment
foreach (var claim in claims)
{
string claimName = claim.Key;
if (string.Compare(claimName, JsonWebTokenClaims.NameId, StringComparison.Ordinal) == 0)
{
claimName = JsonWebTokenClaims.NameIdLongName;
}
else if (string.Compare(claimName, JsonWebTokenClaims.IdenreplacedyProvider, StringComparison.Ordinal) == 0)
{
claimName = JsonWebTokenClaims.IdenreplacedyProviderLongName;
}
ret.Add(new Claim(claimName, claim.Value.ToString()));
}
return ret;
}
19
Source : UriExtensions.cs
with MIT License
from actions
with MIT License
from actions
public static void AddMultiple<T>(this IList<KeyValuePair<String, String>> collection, String key, IEnumerable<T> values, Func<T, String> convert)
{
ArgumentUtility.CheckForNull(collection, "collection");
ArgumentUtility.CheckStringForNullOrEmpty(key, "name");
if (convert == null) convert = (val) => val.ToString();
if (values != null && values.Any())
{
StringBuilder newValue = new StringBuilder();
KeyValuePair<String, String> matchingKvp = collection.FirstOrDefault(kvp => kvp.Key.Equals(key));
if (matchingKvp.Key == key)
{
collection.Remove(matchingKvp);
newValue.Append(matchingKvp.Value);
}
foreach (var value in values)
{
if (newValue.Length > 0)
{
newValue.Append(",");
}
newValue.Append(convert(value));
}
collection.Add(new KeyValuePair<String, String>(key, newValue.ToString()));
}
}
19
Source : ScalarToken.cs
with MIT License
from actions
with MIT License
from actions
public virtual String ToDisplayString()
{
return TrimDisplayString(ToString());
}
19
Source : FlagsEnum.cs
with MIT License
from actions
with MIT License
from actions
public static object ParseKnownFlags(Type enumType, string stringValue)
{
ArgumentUtility.CheckForNull(enumType, nameof(enumType));
if (!enumType.IsEnum)
{
throw new ArgumentException(PipelinesWebApiResources.FlagEnumTypeRequired());
}
// Check for the flags attribute in debug. Skip this reflection in release.
Debug.replacedert(enumType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false).Any(), "FlagsEnum only intended for enums with the Flags attribute.");
// The exception types below are based on Enum.TryParseEnum (http://index/?query=TryParseEnum&rightProject=mscorlib&file=system%5Cenum.cs&rightSymbol=bhaeh2vnegwo)
if (stringValue == null)
{
throw new ArgumentNullException(stringValue);
}
if (String.IsNullOrWhiteSpace(stringValue))
{
throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
}
if (UInt64.TryParse(stringValue, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out ulong ulongValue))
{
return Enum.Parse(enumType, stringValue);
}
var enumNames = Enum.GetNames(enumType).ToHashSet(name => name, StringComparer.OrdinalIgnoreCase);
var enumMemberMappings = new Lazy<IDictionary<string, string>>(() =>
{
IDictionary<string, string> mappings = null;
foreach (var field in enumType.GetFields())
{
if (field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() is EnumMemberAttribute enumMemberAttribute)
{
if (mappings == null)
{
mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
mappings.Add(enumMemberAttribute.Value, field.GetValue(null).ToString());
}
}
return mappings;
});
var values = stringValue.Split(s_enumSeparatorCharArray);
var matches = new List<string>();
for (int i = 0; i < values.Length; i++)
{
string value = values[i].Trim();
if (String.IsNullOrEmpty(value))
{
throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
}
if (enumNames.Contains(value))
{
matches.Add(value);
}
else if (enumMemberMappings.Value != null && enumMemberMappings.Value.TryGetValue(value, out string matchingValue))
{
matches.Add(matchingValue);
}
}
if (!matches.Any())
{
return Enum.Parse(enumType, "0");
}
string matchesString = String.Join(", ", matches);
return Enum.Parse(enumType, matchesString, ignoreCase: true);
}
19
Source : LocationXmlOperator.cs
with MIT License
from actions
with MIT License
from actions
public void WriteServices(XmlNode doreplacedentNode, IEnumerable<ServiceDefinition> serviceDefinitions)
{
XmlDoreplacedent doreplacedent = doreplacedentNode.OwnerDoreplacedent;
XmlNode servicesNode = doreplacedent.CreateNode(XmlNodeType.Element, s_services, null);
doreplacedentNode.AppendChild(servicesNode);
foreach (ServiceDefinition definition in serviceDefinitions)
{
XmlNode serviceDefinitionNode = doreplacedent.CreateNode(XmlNodeType.Element, s_serviceDefinition, null);
servicesNode.AppendChild(serviceDefinitionNode);
XmlNode serviceTypeNode = doreplacedent.CreateNode(XmlNodeType.Element, s_serviceType, null);
serviceDefinitionNode.AppendChild(serviceTypeNode);
serviceTypeNode.InnerText = definition.ServiceType;
XmlNode identifierNode = doreplacedent.CreateNode(XmlNodeType.Element, s_identifier, null);
serviceDefinitionNode.AppendChild(identifierNode);
identifierNode.InnerText = XmlConvert.ToString(definition.Identifier);
if (definition.DisplayName != null)
{
XmlNode displayNameNode = doreplacedent.CreateNode(XmlNodeType.Element, s_displayName, null);
serviceDefinitionNode.AppendChild(displayNameNode);
displayNameNode.InnerText = definition.DisplayName;
}
if (definition.Description != null)
{
XmlNode descriptionNode = doreplacedent.CreateNode(XmlNodeType.Element, s_description, null);
serviceDefinitionNode.AppendChild(descriptionNode);
descriptionNode.InnerText = definition.Description;
}
XmlNode relativePathNode = doreplacedent.CreateNode(XmlNodeType.Element, s_relativePath, null);
serviceDefinitionNode.AppendChild(relativePathNode);
relativePathNode.InnerText = definition.RelativePath;
XmlUtility.AddXmlAttribute(relativePathNode, s_relativeTo, definition.RelativeToSetting.ToString());
XmlNode parentServiceTypeNode = doreplacedent.CreateNode(XmlNodeType.Element, s_parentServiceType, null);
serviceDefinitionNode.AppendChild(parentServiceTypeNode);
parentServiceTypeNode.InnerText = definition.ParentServiceType;
XmlNode parentIdentifierNode = doreplacedent.CreateNode(XmlNodeType.Element, s_parentIdentifier, null);
serviceDefinitionNode.AppendChild(parentIdentifierNode);
parentIdentifierNode.InnerText = XmlConvert.ToString(definition.ParentIdentifier);
if (definition.RelativeToSetting == RelativeToSetting.FullyQualified)
{
XmlNode locationMappingsNode = doreplacedent.CreateNode(XmlNodeType.Element, s_locationMappings, null);
serviceDefinitionNode.AppendChild(locationMappingsNode);
foreach (LocationMapping mapping in definition.LocationMappings)
{
XmlNode locationMappingNode = doreplacedent.CreateNode(XmlNodeType.Element, s_locationMapping, null);
locationMappingsNode.AppendChild(locationMappingNode);
XmlNode accessMappingNode = doreplacedent.CreateNode(XmlNodeType.Element, s_accessMapping, null);
locationMappingNode.AppendChild(accessMappingNode);
accessMappingNode.InnerText = mapping.AccessMappingMoniker;
XmlNode locationNode = doreplacedent.CreateNode(XmlNodeType.Element, s_location, null);
locationMappingNode.AppendChild(locationNode);
locationNode.InnerText = mapping.Location;
}
}
if (definition.ResourceVersion > 0)
{
XmlNode resourceVersionNode = doreplacedent.CreateNode(XmlNodeType.Element, s_resourceVersion, null);
serviceDefinitionNode.AppendChild(resourceVersionNode);
resourceVersionNode.InnerText = XmlConvert.ToString(definition.ResourceVersion);
}
if (definition.MinVersionString != null)
{
XmlNode minVersionNode = doreplacedent.CreateNode(XmlNodeType.Element, s_minVersion, null);
serviceDefinitionNode.AppendChild(minVersionNode);
minVersionNode.InnerText = definition.MinVersionString;
}
if (definition.MaxVersionString != null)
{
XmlNode maxVersionNode = doreplacedent.CreateNode(XmlNodeType.Element, s_maxVersion, null);
serviceDefinitionNode.AppendChild(maxVersionNode);
maxVersionNode.InnerText = definition.MaxVersionString;
}
if (definition.ReleasedVersionString != null)
{
XmlNode releasedVersionNode = doreplacedent.CreateNode(XmlNodeType.Element, s_releasedVersion, null);
serviceDefinitionNode.AppendChild(releasedVersionNode);
releasedVersionNode.InnerText = definition.ReleasedVersionString;
}
}
}
19
Source : VssHttpUriUtility.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public static String ReplaceRouteValues(
String routeTemplate,
Dictionary<String, Object> routeValues,
RouteReplacementOptions routeReplacementOptions)
{
StringBuilder sbResult = new StringBuilder();
StringBuilder sbCurrentPathPart = new StringBuilder();
int paramStart = -1, paramLength = 0;
bool insideParam = false;
HashSet<string> unusedValues = new HashSet<string>(routeValues.Keys, StringComparer.OrdinalIgnoreCase);
Dictionary<string, object> caseIncensitiveRouteValues = new Dictionary<string, object>(routeValues, StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < routeTemplate.Length; i++)
{
char c = routeTemplate[i];
if (insideParam)
{
if (c == '}')
{
insideParam = false;
String paramName = routeTemplate.Substring(paramStart, paramLength);
paramLength = 0;
if (paramName.StartsWith("*"))
{
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.WildcardAsQueryParams))
{
continue;
}
// wildcard route
paramName = paramName.Substring(1);
}
Object paramValue;
if (caseIncensitiveRouteValues.TryGetValue(paramName, out paramValue))
{
if (paramValue != null)
{
sbCurrentPathPart.Append(paramValue.ToString());
unusedValues.Remove(paramName);
}
}
else if (routeReplacementOptions.HasFlag(RouteReplacementOptions.RequireExplicitRouteParams))
{
throw new ArgumentException("Missing route param " + paramName);
}
}
else
{
paramLength++;
}
}
else
{
if (c == '/')
{
if (sbCurrentPathPart.Length > 0)
{
sbResult.Append('/');
sbResult.Append(sbCurrentPathPart.ToString());
sbCurrentPathPart.Clear();
}
}
else if (c == '{')
{
if ((i + 1) < routeTemplate.Length && routeTemplate[i + 1] == '{')
{
// Escaped '{'
sbCurrentPathPart.Append(c);
i++;
}
else
{
insideParam = true;
paramStart = i + 1;
}
}
else if (c == '}')
{
sbCurrentPathPart.Append(c);
if ((i + 1) < routeTemplate.Length && routeTemplate[i + 1] == '}')
{
// Escaped '}'
i++;
}
}
else
{
sbCurrentPathPart.Append(c);
}
}
}
if (sbCurrentPathPart.Length > 0)
{
sbResult.Append('/');
sbResult.Append(sbCurrentPathPart.ToString());
}
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.EscapeUri))
{
sbResult = new StringBuilder(Uri.EscapeUriString(sbResult.ToString()));
}
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.AppendUnusedAsQueryParams) && unusedValues.Count > 0)
{
bool isFirst = true;
foreach (String paramName in unusedValues)
{
Object paramValue;
if (caseIncensitiveRouteValues.TryGetValue(paramName, out paramValue) && paramValue != null)
{
sbResult.Append(isFirst ? '?' : '&');
isFirst = false;
sbResult.Append(Uri.EscapeDataString(paramName));
sbResult.Append('=');
sbResult.Append(Uri.EscapeDataString(paramValue.ToString()));
}
}
}
return sbResult.ToString();
}
19
Source : EnumDescriptionTypeConverter.cs
with MIT License
from Actipro
with MIT License
from Actipro
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == null)
throw new ArgumentNullException("destinationType");
if (null != value && destinationType == typeof(string))
return GetDescription(this.type, value.ToString());
return base.ConvertTo(context, culture, value, destinationType);
}
19
Source : MainWindow.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void toggleContextualTabGroupCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
e.Handled = true;
ICheckableCommandParameter parameter = e.Parameter as ICheckableCommandParameter;
if (parameter != null) {
RibbonControls.ContextualTabGroup contextualTabGroup = ribbon.ContextualTabGroups[Convert.ToString(parameter.Tag)];
parameter.Handled = true;
parameter.IsChecked = contextualTabGroup.IsVisible;
}
}
19
Source : MainWindow.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void toggleContextualTabGroupCommand_Execute(object sender, ExecutedRoutedEventArgs e) {
RibbonControls.ContextualTabGroup contextualTabGroup = null;
ICheckableCommandParameter parameter = e.Parameter as ICheckableCommandParameter;
if (parameter != null)
contextualTabGroup = ribbon.ContextualTabGroups[Convert.ToString(parameter.Tag)];
else if (e.Parameter is string)
contextualTabGroup = ribbon.ContextualTabGroups[Convert.ToString(e.Parameter)];
if (contextualTabGroup != null) {
contextualTabGroup.IsActive = !contextualTabGroup.IsActive;
// If making active, select the first tab in it
// if ((contextualTabGroup.IsActive) && (contextualTabGroup.Items.Count > 0))
// ribbon.SelectedTab = (RibbonControls.Tab)contextualTabGroup.Items[0];
}
}
19
Source : MainControl.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void OnLanguageMenuItemClick(object sender, RoutedEventArgs e) {
MenuItem item = (MenuItem)sender;
this.LoadLanguage(item.Header.ToString());
}
19
Source : MainControl.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void OnCalculateStatisticsButtonClick(object sender, RoutedEventArgs e) {
// Validate path
string folderPath = folderTextBox.Text.Trim();
if ((string.IsNullOrEmpty(folderPath)) || (!Directory.Exists(folderPath))) {
MessageBox.Show("Please enter a valid folder path.", "Invalid Folder", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
// Initialize the background worker
processingBackgroundWorker = new BackgroundWorker();
processingBackgroundWorker.WorkerReportsProgress = true;
processingBackgroundWorker.DoWork += delegate(object sndr, DoWorkEventArgs eventArgs) {
StatData data = (StatData)eventArgs.Argument;
// Recurse and queue files
List<string> queuedFiles = new List<string>();
this.QueueFolder(queuedFiles, data.FolderPath);
// Add stats for files
for (int index = 0; index < queuedFiles.Count; index++) {
processingBackgroundWorker.ReportProgress(
(int)((index + 1) * 100.0 / queuedFiles.Count),
String.Format("Examining {0}...", queuedFiles[index])
);
this.AddStatsForFile(data, queuedFiles[index]);
}
};
processingBackgroundWorker.ProgressChanged += delegate(object sndr, ProgressChangedEventArgs eventArgs) {
messageTextBox.Text = eventArgs.UserState.ToString();
progressBar.Value = eventArgs.ProgressPercentage;
};
processingBackgroundWorker.RunWorkerCompleted += delegate(object sndr, RunWorkerCompletedEventArgs eventArgs) {
// Show results
List<ActiproSoftware.Text.ITextStatistic> statistics = new List<ActiproSoftware.Text.ITextStatistic>();
statistics.Add(ActiproSoftware.Text.Implementation.TextStatistics.CreateStatistic("RootPath", "Root Path", currentData.FolderPath));
statistics.Add(ActiproSoftware.Text.Implementation.TextStatistics.CreateStatistic("TotalFiles", "Total Files", currentData.CSharpFileCount + currentData.VBFileCount + currentData.XamlFileCount));
statistics.Add(ActiproSoftware.Text.Implementation.TextStatistics.CreateStatistic("C#Files", "C# Files", currentData.CSharpFileCount));
statistics.Add(ActiproSoftware.Text.Implementation.TextStatistics.CreateStatistic("VBFiles", "VB Files", currentData.VBFileCount));
statistics.Add(ActiproSoftware.Text.Implementation.TextStatistics.CreateStatistic("XAMLFiles", "XAML Files", currentData.XamlFileCount));
statistics.Add(ActiproSoftware.Text.Implementation.TextStatistics.CreateStatistic("TotalLines", "Total Lines", currentData.NonWhitespaceLineCount + currentData.WhitespaceLineCount));
statistics.Add(ActiproSoftware.Text.Implementation.TextStatistics.CreateStatistic("NonWhitespaceLines", "Non-Whitespace Lines", currentData.NonWhitespaceLineCount));
statistics.Add(ActiproSoftware.Text.Implementation.TextStatistics.CreateStatistic("WhitespaceLines", "Whitespace Lines", currentData.WhitespaceLineCount));
statistics.Add(ActiproSoftware.Text.Implementation.TextStatistics.CreateStatistic("WhitespaceLinePercent", "Whitespace Line %", currentData.WhitespaceLineCount * 100.0 / Math.Max(1, currentData.NonWhitespaceLineCount + currentData.WhitespaceLineCount)));
resultsListView.ItemsSource = statistics;
// Processing is complete
messageTextBox.Text = "Ready";
progressBar.Value = 0;
calculateStatisticsButton.IsEnabled = true;
};
// Initialize UI
calculateStatisticsButton.IsEnabled = false;
messageTextBox.Text = "Discovering files...";
progressBar.Value = 0;
// Start the background work
currentData = new StatData();
currentData.FolderPath = folderPath;
processingBackgroundWorker.RunWorkerAsync(currentData);
}
19
Source : CardContentControl.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void OnSetLabelColorMenuItemClick(object sender, RoutedEventArgs e) {
var menuItem = (MenuItem)sender;
var task = this.DataContext as TaskModel;
if (task != null)
task.SetLabelColorCommand.Execute(menuItem.CommandParameter.ToString());
}
19
Source : NeuralLearner.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
private static void SetPropertyValues<U>(string propertyName,
object objectInconcern, U valueToSet)
{
var prop = objectInconcern.GetType().GetProperty(propertyName
, BindingFlags.Public | BindingFlags.Instance);
var types = prop != null && prop.ToString() != "" ? prop.ToString().Split(' ')[0] : "";
var typeToParse = types.Replace("System.", "");
if (null == prop || !prop.CanWrite || types == "") return;
prop.SetValue(objectInconcern, valueToSet, null);
}
19
Source : ITypeSymbolExtensions.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
public static string GetSimplifiedName(this ITypeSymbol type)
{
type.ThrowOnNull(nameof(type));
switch (type.SpecialType)
{
case SpecialType.None when type.TypeKind == TypeKind.Array:
case SpecialType.System_Object:
case SpecialType.System_Void:
case SpecialType.System_Boolean:
case SpecialType.System_Char:
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_String:
case SpecialType.System_Array:
case SpecialType.System_Nullable_T:
return type.ToString();
default:
return type.Name;
}
}
See More Examples