Here are the examples of the csharp api string.Format(System.IFormatProvider, string, params object[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
31180 Examples
19
View Source File : HealthMonitor.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private bool RecoverBackendAndPreplacedWorkingMemcachedInstance()
{
string preplacedingArg;
if (this.procType != ProcessType.BackendProcess)
{
return false;
}
preplacedingArg = string.Format("-mpid {0}", MemcachedHealthMon.pid);
if (Program.MEMCACHED_PORT > 0)
preplacedingArg += string.Format(" -mport {0}", Program.MEMCACHED_PORT);
return RestartProcessWithExistedInfo(preplacedingArg);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
static void Init()
{
bool watchdog = !System.Diagnostics.Debugger.IsAttached;
Log.Warning("Initializing backend. (watchdog? = {0})",watchdog);
RequestDispatcher.CreateDispatchers(4);
RequestBridge.CreatePipeServers(4);
Edi.StartEdi();
//start health monitor.
System.Diagnostics.Process.Start(
Config.Get().SbmonPath,
string.Format("-backend {0} -memcached {1} -mport {2} -watchdog {3}",
System.Diagnostics.Process.GetCurrentProcess().Id,
DataCacheInstance.ProcessId,Config.Get().MemcachedPort,watchdog));
LogService.Start();
Talk = new InternalTalk(true);
Talk.OnTalk += Talk_OnTalk;
}
19
View Source File : CelesteNetPlayerSession.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void Start<T>(DataHandshakeClient<T> handshake) where T : DataHandshakeClient<T> {
Logger.Log(LogLevel.INF, "playersession", $"Startup #{ID} {Con}");
using (Server.ConLock.W())
Server.Sessions.Add(this);
Server.PlayersByCon[Con] = this;
Server.PlayersByID[ID] = this;
if (Server.UserData.TryLoad(UID, out BanInfo ban) && !ban.Reason.IsNullOrEmpty()) {
Con.Send(new DataDisconnectReason { Text = string.Format(Server.Settings.MessageIPBan, ban.Reason) });
Con.Send(new DataInternalDisconnect());
return;
}
string name = handshake.Name;
if (name.StartsWith("#")) {
string uid = Server.UserData.GetUID(name.Substring(1));
if (uid.IsNullOrEmpty()) {
Con.Send(new DataDisconnectReason { Text = Server.Settings.MessageInvalidUserKey });
Con.Send(new DataInternalDisconnect());
return;
}
UID = uid;
if (!Server.UserData.TryLoad(uid, out BasicUserInfo userinfo)) {
Con.Send(new DataDisconnectReason { Text = Server.Settings.MessageUserInfoMissing });
Con.Send(new DataInternalDisconnect());
return;
}
name = userinfo.Name.Sanitize(IllegalNameChars, true);
if (name.Length > Server.Settings.MaxNameLength)
name = name.Substring(0, Server.Settings.MaxNameLength);
if (name.IsNullOrEmpty())
name = "Ghost";
if (Server.UserData.TryLoad(UID, out ban) && !ban.Reason.IsNullOrEmpty()) {
Con.Send(new DataDisconnectReason { Text = string.Format(Server.Settings.MessageBan, name, ban.Reason) });
Con.Send(new DataInternalDisconnect());
return;
}
} else {
if (Server.Settings.AuthOnly) {
Con.Send(new DataDisconnectReason { Text = Server.Settings.MessageAuthOnly });
Con.Send(new DataInternalDisconnect());
return;
}
name = name.Sanitize(IllegalNameChars);
if (name.Length > Server.Settings.MaxGuestNameLength)
name = name.Substring(0, Server.Settings.MaxGuestNameLength);
if (name.IsNullOrEmpty())
name = "Guest";
}
if (name.Length > Server.Settings.MaxNameLength)
name = name.Substring(0, Server.Settings.MaxNameLength);
string nameSpace = name;
name = name.Replace(" ", "");
string fullNameSpace = nameSpace;
string fullName = name;
using (Server.ConLock.R()) {
int i = 1;
while (true) {
bool conflict = false;
foreach (CelesteNetPlayerSession other in Server.Sessions)
if (conflict = other.PlayerInfo?.FullName == fullName)
break;
if (!conflict)
break;
i++;
fullNameSpace = $"{nameSpace}#{i}";
fullName = $"{name}#{i}";
}
}
string displayName = fullNameSpace;
using (Stream? avatar = Server.UserData.ReadFile(UID, "avatar.png")) {
if (avatar != null) {
AvatarEmoji = new() {
ID = $"celestenet_avatar_{ID}_",
Data = avatar.ToBytes()
};
displayName = $":{AvatarEmoji.ID}: {fullNameSpace}";
}
}
DataPlayerInfo playerInfo = new() {
ID = ID,
Name = name,
FullName = fullName,
DisplayName = displayName
};
playerInfo.Meta = playerInfo.GenerateMeta(Server.Data);
Server.Data.SetRef(playerInfo);
Logger.Log(LogLevel.INF, "playersession", playerInfo.ToString());
Con.Send(new DataHandshakeServer {
PlayerInfo = playerInfo
});
Con.Send(AvatarEmoji);
DataInternalBlob? blobPlayerInfo = DataInternalBlob.For(Server.Data, playerInfo);
DataInternalBlob? blobAvatarEmoji = DataInternalBlob.For(Server.Data, AvatarEmoji);
using (Server.ConLock.R())
foreach (CelesteNetPlayerSession other in Server.Sessions) {
if (other == this)
continue;
DataPlayerInfo? otherInfo = other.PlayerInfo;
if (otherInfo == null)
continue;
other.Con.Send(blobPlayerInfo);
other.Con.Send(blobAvatarEmoji);
Con.Send(otherInfo);
Con.Send(other.AvatarEmoji);
foreach (DataType bound in Server.Data.GetBoundRefs(otherInfo))
if (!bound.Is<MetaPlayerPrivateState>(Server.Data) || other.Channel.ID == 0)
Con.Send(bound);
}
ResendPlayerStates();
Server.InvokeOnSessionStart(this);
}
19
View Source File : CelesteNetTCPUDPConnection.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void WriteTeapot(string[] features, uint token) {
lock (TCPWriter) {
using (StreamWriter writer = new(TCPWriterStream, CelesteNetUtils.UTF8NoBOM, 1024, true))
writer.Write(string.Format(CelesteNetUtils.HTTPTeapot, string.Join(CelesteNetUtils.ConnectionFeatureSeparator, features), token));
TCPWriterStream.Flush();
}
}
19
View Source File : StringInjectExtension.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public static string InjectSingleValue(this string formatString, string key, object replacementValue) {
string result = formatString;
//regex replacement of key with value, where the generic key format is:
//Regex foo = new("{(foo)(?:}|(?::(.[^}]*)}))");
Regex attributeRegex = new("{(" + key + ")(?:}|(?::(.[^}]*)}))"); //for key = foo, matches {foo} and {foo:SomeFormat}
//loop through matches, since each key may be used more than once (and with a different format string)
foreach (Match? m in attributeRegex.Matches(formatString)) {
if (m == null)
continue;
string replacement = m.ToString();
if (m.Groups[2].Length > 0) {
//matched {foo:SomeFormat}
//do a double string.Format - first to build the proper format string, and then to format the replacement value
string attributeFormatString = string.Format(CultureInfo.InvariantCulture, "{{0:{0}}}", m.Groups[2]);
replacement = string.Format(CultureInfo.CurrentCulture, attributeFormatString, replacementValue);
} else {
//matched {foo}
replacement = replacementValue.ToString() ?? string.Empty;
}
//perform replacements, one match at a time
result = result.Replace(m.ToString(), replacement); //attributeRegex.Replace(result, replacement, 1);
}
return result;
}
19
View Source File : ReaderSimpleTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
static async Reader<string> Greet(string name)
=> string.Format(await ExtractTemplate(), name);
19
View Source File : ReaderTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
private static async Reader<string> GetGreeting(int userId)
{
var template = await Reader<string>.Read<Configuration>(cfg => cfg.GreetingTemplate);
var fullName = await GetFullName(userId);
var win = await GetWin(userId);
return string.Format(template, fullName, win);
}
19
View Source File : ReaderTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
private static async Reader<string> GetFullName(int userId)
{
var template = await Reader<string>.Read<Configuration>(cfg => cfg.NameFormat);
var firstName = await GetFirstName(userId);
var lastName = await GetLastName(userId);
return string.Format(template, firstName, lastName);
}
19
View Source File : Validate.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
public static void IsNotEmptyOrWhiteSpace(string param, string paramName)
{
if (param != null && param.IsEmptyOrWhiteSpace())
{
ExceptionUtil.ThrowArgumentException(string.Format(CultureInfo.CurrentCulture,
Resources.ParameterStringIsEmptyOrWhitespaceFormat,
paramName));
}
}
19
View Source File : Validate.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
public static void IsNotNullOrEmptyArray<T>(T[] param, string paramName)
{
if (param is null)
{
ExceptionUtil.ThrowArgumentNullException(paramName);
}
else if (param.Length == 0)
{
ExceptionUtil.ThrowArgumentException(string.Format(CultureInfo.CurrentCulture,
Resources.ParameterIsEmptyArrayFormat,
paramName));
}
}
19
View Source File : Validate.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
public static void IsNotNullOrWhiteSpace(string param, string paramName)
{
if (param is null)
{
ExceptionUtil.ThrowArgumentNullException(paramName);
}
else if (param.IsEmptyOrWhiteSpace())
{
ExceptionUtil.ThrowArgumentException(string.Format(CultureInfo.CurrentCulture,
Resources.ParameterStringIsEmptyOrWhitespaceFormat,
paramName));
}
}
19
View Source File : ImageGridMetadata.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public string SerializeToString()
{
return string.Format(CultureInfo.InvariantCulture,
"<ImageGridMetadata {0}=\"{1}\"{2}=\"{3}\"{4}=\"{5}\"{6}=\"{7}\"{8}=\"{9}\"{10}=\"{11}\" />",
TileColumnCountPropertyName,
this.TileColumnCount,
TileRowCountPropertyName,
this.TileRowCount,
OutputHeightPropertyName,
this.OutputHeight,
OutputWidthPropertyName,
this.OutputWidth,
TileImageHeightPropertyName,
this.TileImageHeight,
TileImageWidthPropertyName,
this.TileImageWidth);
}
19
View Source File : CICPSerializer.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public static string TrySerialize(CICPColorData cicpColor)
{
// The idenreplacedy matrix coefficient is never serialized.
if (cicpColor.matrixCoefficients == CICPMatrixCoefficients.Idenreplacedy)
{
return null;
}
if (cicpColor.colorPrimaries == CICPColorPrimaries.Unspecified ||
cicpColor.transferCharacteristics == CICPTransferCharacteristics.Unspecified ||
cicpColor.matrixCoefficients == CICPMatrixCoefficients.Unspecified)
{
return null;
}
ushort colorPrimaries = (ushort)cicpColor.colorPrimaries;
ushort transferCharacteristics = (ushort)cicpColor.transferCharacteristics;
ushort matrixCoefficients = (ushort)cicpColor.matrixCoefficients;
return string.Format(CultureInfo.InvariantCulture,
"<CICP {0}=\"{1}\" {2}=\"{3}\" {4}=\"{5}\"/>",
ColorPrimariesPropertyName,
colorPrimaries.ToString(CultureInfo.InvariantCulture),
TransferCharacteristicsPropertyName,
transferCharacteristics.ToString(CultureInfo.InvariantCulture),
MatrixCoefficientsPropertyName,
matrixCoefficients.ToString(CultureInfo.InvariantCulture));
}
19
View Source File : HeifEncoder.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
private void SetStringParameter(string name, string value, bool coerceParameterType)
{
Validate.IsNotNull(name, nameof(name));
Validate.IsNotNull(value, nameof(value));
VerifyNotDisposed();
if (coerceParameterType)
{
// Some encoders expect the method that is called to match the parameter type.
// Attempting to set a Boolean or Integer parameter as a string will cause an invalid parameter error.
if (this.encoderParameterTypes.Value.TryGetValue(name, out var type))
{
switch (type)
{
case HeifEncoderParameterType.Boolean:
if (TryConvertStringToBoolean(value, out bool boolValue))
{
SetBooleanParameter(name, boolValue);
}
else
{
throw new HeifException(string.Format(CultureInfo.CurrentCulture,
Resources.CoerceStringValueToBooleanFailedFormat,
nameof(value)));
}
return;
case HeifEncoderParameterType.Integer:
if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int intValue))
{
SetIntegerParameter(name, intValue);
}
else
{
throw new HeifException(string.Format(CultureInfo.CurrentCulture,
Resources.CoerceStringValueToIntegerFailedFormat,
nameof(value)));
}
return;
case HeifEncoderParameterType.String:
// The parameter is the correct type.
break;
default:
throw new HeifException($"Unknown { nameof(HeifEncoderParameterType) }: { type }.");
}
}
}
var error = LibHeifNative.heif_encoder_set_parameter_string(this.encoder, name, value);
error.ThrowIfError();
}
19
View Source File : LibHeifVersion.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
public static void ThrowIfNotSupported()
{
const uint MinimumLibHeifVersion = 0x01090000; // Version 1.9.0
if (LibHeifInfo.VersionNumber < MinimumLibHeifVersion)
{
const int Major = (int)((MinimumLibHeifVersion >> 24) & 0xff);
const int Minor = (int)((MinimumLibHeifVersion >> 16) & 0xff);
const int Maintenance = (int)((MinimumLibHeifVersion >> 8) & 0xff);
throw new HeifException(string.Format(System.Globalization.CultureInfo.CurrentCulture,
Properties.Resources.LibHeifVersionNotSupportedFormat,
Major,
Minor,
Maintenance));
}
}
19
View Source File : ExifParser.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public override string ToString()
{
if (this.OffsetFieldContainsValue)
{
return string.Format("Tag={0}, Type={1}, Count={2}, Value={3}",
this.entry.Tag.ToString(CultureInfo.InvariantCulture),
this.entry.Type.ToString(),
this.entry.Count.ToString(CultureInfo.InvariantCulture),
GetValueStringFromOffset());
}
else
{
return string.Format("Tag={0}, Type={1}, Count={2}, Offset=0x{3}",
this.entry.Tag.ToString(CultureInfo.InvariantCulture),
this.entry.Type.ToString(),
this.entry.Count.ToString(CultureInfo.InvariantCulture),
this.entry.Offset.ToString("X", CultureInfo.InvariantCulture));
}
}
19
View Source File : ExifParser.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public override string ToString()
{
if (OffsetFieldContainsValue)
{
return string.Format("Tag={0}, Type={1}, Count={2}, Value={3}",
entry.Tag.ToString(CultureInfo.InvariantCulture),
entry.Type.ToString(),
entry.Count.ToString(CultureInfo.InvariantCulture),
GetValueStringFromOffset());
}
else
{
return string.Format("Tag={0}, Type={1}, Count={2}, Offset=0x{3}",
entry.Tag.ToString(CultureInfo.InvariantCulture),
entry.Type.ToString(),
entry.Count.ToString(CultureInfo.InvariantCulture),
entry.Offset.ToString("X", CultureInfo.InvariantCulture));
}
}
19
View Source File : GmicConfigDialog.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054
License : GNU General Public License v3.0
Project Creator : 0xC0000054
private void GmicThread()
{
DialogResult result = DialogResult.Cancel;
try
{
List<GmicLayer> layers = new List<GmicLayer>();
Surface clipboardSurface = null;
try
{
// Some G'MIC filters require the image to have more than one layer.
// Because use Paint.NET does not currently support Effect plug-ins accessing
// other layers in the doreplacedent, allowing the user to place the second layer on
// the clipboard is supported as a workaround.
clipboardSurface = Services.GetService<IClipboardService>().TryGetSurface();
if (clipboardSurface != null)
{
layers.Add(new GmicLayer(clipboardSurface, true));
clipboardSurface = null;
}
}
finally
{
if (clipboardSurface != null)
{
clipboardSurface.Dispose();
}
}
layers.Add(new GmicLayer(EnvironmentParameters.SourceSurface, false));
server.AddLayers(layers);
server.Start();
string arguments = string.Format(CultureInfo.InvariantCulture, ".PDN {0}", server.FullPipeName);
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo(GmicPath, arguments);
process.Start();
process.WaitForExit();
if (process.ExitCode == GmicExitCode.Ok)
{
result = DialogResult.OK;
}
else
{
surface?.Dispose();
surface = null;
switch (process.ExitCode)
{
case GmicExitCode.ImageTooLargeForX86:
ShowErrorMessage(Resources.ImageTooLargeForX86);
break;
}
}
}
}
catch (ArgumentException ex)
{
ShowErrorMessage(ex);
}
catch (ExternalException ex)
{
ShowErrorMessage(ex);
}
catch (IOException ex)
{
ShowErrorMessage(ex);
}
catch (UnauthorizedAccessException ex)
{
ShowErrorMessage(ex);
}
BeginInvoke(new Action<DialogResult>(GmicThreadFinished), result);
}
19
View Source File : GmicEffect.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054
License : GNU General Public License v3.0
Project Creator : 0xC0000054
protected override void OnSetRenderInfo(EffectConfigToken parameters, RenderArgs dstArgs, RenderArgs srcArgs)
{
if (repeatEffect)
{
GmicConfigToken token = (GmicConfigToken)parameters;
if (token.Surface != null)
{
token.Surface.Dispose();
token.Surface = null;
}
if (File.Exists(GmicConfigDialog.GmicPath))
{
try
{
using (GmicPipeServer server = new GmicPipeServer())
{
List<GmicLayer> layers = new List<GmicLayer>();
Surface clipboardSurface = null;
try
{
// Some G'MIC filters require the image to have more than one layer.
// Because use Paint.NET does not currently support Effect plug-ins accessing
// other layers in the doreplacedent, allowing the user to place the second layer on
// the clipboard is supported as a workaround.
clipboardSurface = Services.GetService<IClipboardService>().TryGetSurface();
if (clipboardSurface != null)
{
layers.Add(new GmicLayer(clipboardSurface, true));
clipboardSurface = null;
}
}
finally
{
if (clipboardSurface != null)
{
clipboardSurface.Dispose();
}
}
layers.Add(new GmicLayer(EnvironmentParameters.SourceSurface, false));
server.AddLayers(layers);
server.Start();
string arguments = string.Format(CultureInfo.InvariantCulture, ".PDN {0} reapply", server.FullPipeName);
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo(GmicConfigDialog.GmicPath, arguments);
process.Start();
process.WaitForExit();
if (process.ExitCode == GmicExitCode.Ok)
{
OutputImageState state = server.OutputImageState;
if (state.Error != null)
{
ShowErrorMessage(state.Error);
}
else
{
IReadOnlyList<Surface> outputImages = state.OutputImages;
if (outputImages.Count > 1)
{
using (PlatformFolderBrowserDialog folderBrowserDialog = new PlatformFolderBrowserDialog())
{
folderBrowserDialog.ClreplacedicFolderBrowserDescription = Resources.ClreplacedicFolderBrowserDescription;
folderBrowserDialog.VistaFolderBrowserreplacedle = Resources.VistaFolderBrowserreplacedle;
if (!string.IsNullOrWhiteSpace(token.OutputFolder))
{
folderBrowserDialog.SelectedPath = token.OutputFolder;
}
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
string outputFolder = folderBrowserDialog.SelectedPath;
try
{
OutputImageUtil.SaveAllToFolder(outputImages, outputFolder);
}
catch (ArgumentException ex)
{
ShowErrorMessage(ex);
}
catch (ExternalException ex)
{
ShowErrorMessage(ex);
}
catch (IOException ex)
{
ShowErrorMessage(ex);
}
catch (SecurityException ex)
{
ShowErrorMessage(ex);
}
catch (UnauthorizedAccessException ex)
{
ShowErrorMessage(ex);
}
}
}
}
else
{
Surface output = outputImages[0];
if (output.Width == srcArgs.Surface.Width && output.Height == srcArgs.Surface.Height)
{
token.Surface = output.Clone();
}
else
{
// Place the full image on the clipboard when the size does not match the Paint.NET layer
// and prompt the user to save it.
// The resized image will not be copied to the Paint.NET canvas.
Services.GetService<IClipboardService>().SetImage(output);
using (PlatformFileSaveDialog resizedImageSaveDialog = new PlatformFileSaveDialog())
{
resizedImageSaveDialog.Filter = Resources.ResizedImageSaveDialogFilter;
resizedImageSaveDialog.replacedle = Resources.ResizedImageSaveDialogreplacedle;
resizedImageSaveDialog.FileName = DateTime.Now.ToString("yyyyMMdd-THHmmss") + ".png";
if (resizedImageSaveDialog.ShowDialog() == DialogResult.OK)
{
string resizedImagePath = resizedImageSaveDialog.FileName;
try
{
using (Bitmap bitmap = output.CreateAliasedBitmap())
{
bitmap.Save(resizedImagePath, System.Drawing.Imaging.ImageFormat.Png);
}
}
catch (ArgumentException ex)
{
ShowErrorMessage(ex);
}
catch (ExternalException ex)
{
ShowErrorMessage(ex);
}
catch (IOException ex)
{
ShowErrorMessage(ex);
}
catch (SecurityException ex)
{
ShowErrorMessage(ex);
}
catch (UnauthorizedAccessException ex)
{
ShowErrorMessage(ex);
}
}
}
}
}
}
}
else
{
switch (process.ExitCode)
{
case GmicExitCode.ImageTooLargeForX86:
ShowErrorMessage(Resources.ImageTooLargeForX86);
break;
}
}
}
}
}
catch (ArgumentException ex)
{
ShowErrorMessage(ex);
}
catch (ExternalException ex)
{
ShowErrorMessage(ex);
}
catch (IOException ex)
{
ShowErrorMessage(ex);
}
catch (UnauthorizedAccessException ex)
{
ShowErrorMessage(ex);
}
}
else
{
ShowErrorMessage(Resources.GmicNotFound);
}
}
base.OnSetRenderInfo(parameters, dstArgs, srcArgs);
}
19
View Source File : WebPNative.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
internal static unsafe void WebPGetImageInfo(byte[] data, out ImageInfo info)
{
VP8StatusCode status;
fixed (byte* ptr = data)
{
if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
{
status = WebP_x64.WebPGetImageInfo(ptr, new UIntPtr((ulong)data.Length), out info);
}
else if (RuntimeInformation.ProcessArchitecture == Architecture.X86)
{
status = WebP_x86.WebPGetImageInfo(ptr, new UIntPtr((ulong)data.Length), out info);
}
else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
{
status = WebP_ARM64.WebPGetImageInfo(ptr, new UIntPtr((ulong)data.Length), out info);
}
else
{
throw new PlatformNotSupportedException();
}
}
if (status != VP8StatusCode.Ok)
{
switch (status)
{
case VP8StatusCode.OutOfMemory:
throw new OutOfMemoryException();
case VP8StatusCode.InvalidParam:
throw new WebPException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidParameterFormat, nameof(WebPGetImageInfo)));
case VP8StatusCode.UnsupportedFeature:
throw new WebPException(Resources.UnsupportedWebPFeature);
case VP8StatusCode.BitStreamError:
case VP8StatusCode.NotEnoughData:
default:
throw new WebPException(Resources.InvalidWebPImage);
}
}
}
19
View Source File : WebPNative.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
internal static unsafe void WebPLoad(byte[] webpBytes, System.Drawing.Imaging.BitmapData output)
{
VP8StatusCode status;
fixed (byte* ptr = webpBytes)
{
int stride = output.Stride;
ulong outputSize = (ulong)stride * (ulong)output.Height;
if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
{
status = WebP_x64.WebPLoad(ptr, new UIntPtr((ulong)webpBytes.Length), (byte*)output.Scan0, new UIntPtr(outputSize), stride);
}
else if (RuntimeInformation.ProcessArchitecture == Architecture.X86)
{
status = WebP_x86.WebPLoad(ptr, new UIntPtr((ulong)webpBytes.Length), (byte*)output.Scan0, new UIntPtr(outputSize), stride);
}
else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
{
status = WebP_ARM64.WebPLoad(ptr, new UIntPtr((ulong)webpBytes.Length), (byte*)output.Scan0, new UIntPtr(outputSize), stride);
}
else
{
throw new PlatformNotSupportedException();
}
}
if (status != VP8StatusCode.Ok)
{
switch (status)
{
case VP8StatusCode.OutOfMemory:
throw new OutOfMemoryException();
case VP8StatusCode.InvalidParam:
throw new WebPException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidParameterFormat, nameof(WebPLoad)));
case VP8StatusCode.UnsupportedFeature:
throw new WebPException(Resources.UnsupportedWebPFeature);
case VP8StatusCode.BitStreamError:
case VP8StatusCode.NotEnoughData:
default:
throw new WebPException(Resources.InvalidWebPImage);
}
}
}
19
View Source File : MetroColorPicker.xaml.cs
License : MIT License
Project Creator : 1217950746
License : MIT License
Project Creator : 1217950746
private void ApplyColor(HsbaColor hsba)
{
currentColor = hsba;
currentRgbaColor = currentColor.RgbaColor;
if (!rgbaR.IsSelectionActive) { rgbaR.Text = currentRgbaColor.R.ToString(); }
if (!rgbaG.IsSelectionActive) { rgbaG.Text = currentRgbaColor.G.ToString(); }
if (!rgbaB.IsSelectionActive) { rgbaB.Text = currentRgbaColor.B.ToString(); }
if (!rgbaA.IsSelectionActive) { rgbaA.Text = currentRgbaColor.A.ToString(); }
if (!hsbaH.IsSelectionActive) { hsbaH.Text = ((int)(currentColor.H / 3.6)).ToString(); }
if (!hsbaS.IsSelectionActive) { hsbaS.Text = ((int)(currentColor.S * 100)).ToString(); }
if (!hsbaB.IsSelectionActive) { hsbaB.Text = ((int)(currentColor.B * 100)).ToString(); }
if (!hsbaA.IsSelectionActive) { hsbaA.Text = ((int)(currentColor.A * 100)).ToString(); }
if (!hex.IsSelectionActive) { if (canTransparent) { hex.Text = currentColor.HexString; } else { hex.Text = string.Format("#{0:X2}{1:X2}{2:X2}", currentRgbaColor.R, currentRgbaColor.G, currentRgbaColor.B); } }
if (!thumbH.IsDragging) { thumbH.YPercent = currentColor.H / 360.0; }
if (!thumbSB.IsDragging) { thumbSB.XPercent = currentColor.S; thumbSB.YPercent = 1 - currentColor.B; }
if (!thumbA.IsDragging) { thumbA.YPercent = Math.Abs(1 - currentColor.A); }
selectColor.H = currentColor.H;
selectColor.A = currentColor.A;
viewSelectColor.Fill = selectColor.OpaqueSolidColorBrush;
if (canTransparent)
{
viewSelectColor.Opacity = viewSelectColor1.Opacity = viewSelectColor2.Opacity = 1 - thumbA.YPercent;
}
viewAlpha.Color = selectColor.OpaqueColor;
if (canTransparent)
{
Background = currentColor.SolidColorBrush;
}
else
{
Background = currentColor.OpaqueSolidColorBrush;
}
ColorChange?.Invoke(this, null);
}
19
View Source File : Display.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios
License : GNU General Public License v3.0
Project Creator : 1330-Studios
[HarmonyPostfix]
public static void Fix(ref RoundDisplay __instance) {
__instance.text.text = $"{__instance.cachedRoundDisp}\n";
towerdata.Sort((s1, s2) => s1.Item1.CompareTo(s2.Item1));
for (int i = 0; i < towerdata.Count; i++) {
var optionalPercentage = (float)towerdata[i].Item2 / (float)towerdata[i].Item3;
if (i < 5)
__instance.text.text += string.Format(style, towerdata[i].Item1, towerdata[i].Item2, towerdata[i].Item3, optionalPercentage) + "\n";
else if (!Input.GetKey(KeyCode.F1)) { // slower than math so it gets its own exception outside of the main part of if
__instance.text.text += "Press and hold F1 for more...";
break;
} else
__instance.text.text += string.Format(style, towerdata[i].Item1, towerdata[i].Item2, towerdata[i].Item3, optionalPercentage) + "\n";
}
towerdata.Clear();
}
19
View Source File : EntitySqlDescriptor.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private string FormatSql(string sql, string tableName = null)
{
return string.Format(sql, _adapter.AppendQuote(tableName ?? _tableName));
}
19
View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string Generate()
{
try
{
/*
if (Environment.Version.Major != 2)
{
WriteError("This tool should only be run on v2 of the CLR");
Environment.Exit(1);
}
*/
string output_file = null;
string entry_clreplaced_name = DEFAULT_ENTRY_CLreplaced_NAME;
string additional_script = String.Empty;
bool mscorlib_only = false;
bool scriptlet_moniker = false;
bool scriptlet_uninstall = false;
bool enable_debug = false;
RuntimeVersion version = RuntimeVersion.Auto;
ScriptLanguage language = ScriptLanguage.JScript;
Guid clsid = Guid.Empty;
bool show_help = false;
string replacedembly_path = Global_Var.dll_path;
/*
if (!File.Exists(replacedembly_path) || show_help)
{
Console.Error.WriteLine(@"Usage: DotNetToJScript {0} [options] path\to\asm", VERSION);
Console.Error.WriteLine("Copyright (C) James Forshaw 2017. Licensed under GPLv3.");
Console.Error.WriteLine("Source code at https://github.com/tyranid/DotNetToJScript");
Console.Error.WriteLine("Options");
opts.WriteOptionDescriptions(Console.Error);
Environment.Exit(1);
}
*/
IScriptGenerator generator;
switch (language)
{
case ScriptLanguage.JScript:
generator = new JScriptGenerator();
break;
case ScriptLanguage.VBA:
generator = new VBAGenerator();
break;
case ScriptLanguage.VBScript:
generator = new VBScriptGenerator();
break;
default:
throw new ArgumentException("Invalid script language option");
}
byte[] replacedembly = File.ReadAllBytes(replacedembly_path);
try
{
HashSet<string> valid_clreplacedes = GetValidClreplacedes(replacedembly);
if (!valid_clreplacedes.Contains(entry_clreplaced_name))
{
WriteError("Error: Clreplaced '{0}' not found is replacedembly.", entry_clreplaced_name);
if (valid_clreplacedes.Count == 0)
{
WriteError("Error: replacedembly doesn't contain any public, default constructable clreplacedes");
}
else
{
WriteError("Use one of the follow options to specify a valid clreplacedes");
foreach (string name in valid_clreplacedes)
{
WriteError("-c {0}", name);
}
}
Environment.Exit(1);
}
}
catch (Exception)
{
WriteError("Error: loading replacedembly information.");
WriteError("The generated script might not work correctly");
}
BinaryFormatter fmt = new BinaryFormatter();
MemoryStream stm = new MemoryStream();
fmt.Serialize(stm, mscorlib_only ? BuildLoaderDelegateMscorlib(replacedembly) : BuildLoaderDelegate(replacedembly));
string script = generator.GenerateScript(stm.ToArray(), entry_clreplaced_name, additional_script, version, enable_debug);
if (scriptlet_moniker || scriptlet_uninstall)
{
if (!generator.SupportsScriptlet)
{
throw new ArgumentException(String.Format("{0} generator does not support Scriptlet output", generator.ScriptName));
}
script = CreateScriptlet(script, generator.ScriptName, scriptlet_uninstall, clsid);
}
/*
if (!String.IsNullOrEmpty(output_file))
{
File.WriteAllText(output_file, script, new UTF8Encoding(false));
}
else
{
Console.WriteLine(script);
}
*/
return script;
}
catch (Exception ex)
{
ReflectionTypeLoadException tex = ex as ReflectionTypeLoadException;
if (tex != null)
{
WriteError("Couldn't load replacedembly file");
foreach (var e in tex.LoaderExceptions)
{
WriteError(e.Message);
}
}
else
{
WriteError(ex.Message);
}
return null;
}
}
19
View Source File : MonitorItemForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void stb_home_url_Enter(object sender, EventArgs e)
{
string sdir = stb_project_source_dir.Text;
string appname = stb_app_name.Text;
string url = stb_home_url.Text;
if(!string.IsNullOrWhiteSpace(sdir) && !string.IsNullOrWhiteSpace(appname) && url.EndsWith("[port]")){
try
{
if (get_spboot_port_run)
{
return;
}
get_spboot_port_run = true;
if (!sdir.EndsWith("/"))
{
sdir += "/";
}
string serverxml = string.Format("{0}{1}/src/main/resources/config/application-dev.yml", sdir, appname);
string targetxml = MainForm.TEMP_DIR + string.Format("application-dev-{0}.yml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
ThreadPool.QueueUserWorkItem((a) =>
{
Thread.Sleep(500);
string port = "", ctx = "";
string yml = YSTools.YSFile.readFileToString(targetxml);
if(!string.IsNullOrWhiteSpace(yml)){
string[] lines = yml.Split('\n');
bool find = false;
int index = 0, start = 0;
foreach(string line in lines){
if (line.Trim().StartsWith("server:"))
{
find = true;
start = index;
}
else if(find && line.Trim().StartsWith("port:")){
port = line.Substring(line.IndexOf(":") + 1).Trim();
}
else if (find && line.Trim().StartsWith("context-path:"))
{
ctx = line.Substring(line.IndexOf(":") + 1).Trim();
}
if (index - start > 4 && start > 0)
{
break;
}
index++;
}
}
if (port != "")
{
stb_home_url.BeginInvoke((MethodInvoker)delegate()
{
stb_home_url.Text = string.Format("http://{0}:{1}{2}", config.Host, port, ctx);
});
}
get_spboot_port_run = false;
File.Delete(targetxml);
});
}
catch(Exception ex) {
logger.Error("Error", ex);
}
}
}
19
View Source File : NginxMappingItemForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void NginxMappingItemForm_Load(object sender, EventArgs e)
{
if(pro == null){
stb_url.Text = string.Format("http://{0}", this.seConfig.Host);
stb_host.Text = "http://ip:port";
cb_check.Checked = true;
}
}
19
View Source File : NginxMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void customShellListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (customShellListView.SelectedItems.Count > 0)
{
ListViewItem item = customShellListView.SelectedItems[0];
if (null != item)
{
CmdShell cmds = (CmdShell)item.Tag;
StringBuilder sb = new StringBuilder();
foreach (TaskShell task in cmds.ShellList)
{
if (cmds.TaskType == TaskType.Default)
{
sb.AppendLine(task.Shell);
}
else if (cmds.TaskType == TaskType.Timed)
{
sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
}
else if (cmds.TaskType == TaskType.Condition)
{
sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
}
}
shellView.Text = sb.ToString();
if (cmds.TaskType == TaskType.Default)
{
btn_run.Enabled = true;
}
return;
}
}
btn_run.Enabled = false;
shellView.Text = "";
}
19
View Source File : IceMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public override void ReflushMonitorItem()
{
l_appname.Text = itemConfig.ice.AppName;
string srcdir = itemConfig.ice.IceSrvDir;
if (srcdir != null)
{
if (!srcdir.EndsWith("/"))
srcdir += "/";
l_pro_path.Text = srcdir;
}
l_node_port.Text = itemConfig.ice.NodePorts;
l_server_name.Text = itemConfig.ice.ServerName;
if (itemConfig.ice.NodePorts != null)
{
string[] ports = itemConfig.ice.NodePorts.Split(',');
ListViewItem item = null;
foreach(string port in ports){
item = new ListViewItem();
item.Text = string.Format("http://{0}:{1}", seConfig.Host, port);
item.Tag = port;
projects.Items.Add(item);
}
}
}
19
View Source File : IceMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void btn_build_Click(object sender, EventArgs e)
{
btn_update.Enabled = false;
monitorForm.RunShell(l_pro_path.Text + "bin/admin.sh", false, true);
monitorForm.GetShellResult(string.Format("application update config/{0}.xml", itemConfig.ice.AppName), new ShellResultDelegate(UpdateConfigResult), true);
}
19
View Source File : IceMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void customShellListView_SelectedIndexChanged(object sender, EventArgs e)
{
if(customShellListView.SelectedItems.Count > 0){
ListViewItem item = customShellListView.SelectedItems[0];
if(null != item){
CmdShell cmds = (CmdShell) item.Tag;
StringBuilder sb = new StringBuilder();
foreach (TaskShell task in cmds.ShellList)
{
if (cmds.TaskType == TaskType.Default)
{
sb.AppendLine(task.Shell);
}
else if (cmds.TaskType == TaskType.Timed)
{
sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
}
else if (cmds.TaskType == TaskType.Condition)
{
sb.AppendLine(string.Format("{0} - {1}", cmds.Condition, task.Shell));
}
}
shellView.Text = sb.ToString();
if(cmds.TaskType == TaskType.Default){
btn_run.Enabled = true;
}
return;
}
}
btn_run.Enabled = false;
shellView.Text = "";
}
19
View Source File : IceMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
if (get_srvxml_run)
{
return;
}
get_srvxml_run = true;
linkLabel1.Enabled = false;
string targetxml = MainForm.TEMP_DIR + string.Format("srv-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
string serverxml = string.Format("{0}config/{1}.xml", l_pro_path.Text, l_appname.Text);
TextEditorForm editor = new TextEditorForm();
editor.Show(this);
editor.LoadRemoteFile(new ShellForm(monitorForm), serverxml, targetxml);
}
catch { }
get_srvxml_run = false;
linkLabel1.Enabled = true;
}
19
View Source File : MonitorItemForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void MonitorItemForm_Load(object sender, EventArgs e)
{
if (null != monitorConfig)
{
if (monitorConfig.spring != null)
{
stb_app_name.Text = monitorConfig.spring.AppName;
if (string.IsNullOrWhiteSpace(monitorConfig.spring.ShFileDir))
{
stb_sh_dir.Text = string.Format("/home/{0}/bin", config.UserName);
}
else
{
stb_sh_dir.Text = monitorConfig.spring.ShFileDir;
}
stb_build_file.Text = monitorConfig.spring.BuildFileName;
stb_ctl_file.Text = monitorConfig.spring.CrlFileName;
if (string.IsNullOrWhiteSpace(monitorConfig.spring.HomeUrl))
{
stb_home_url.Text = string.Format("http://{0}:[port]", config.Host);
}
else
{
stb_home_url.Text = monitorConfig.spring.HomeUrl;
}
if (string.IsNullOrWhiteSpace(monitorConfig.spring.ProjectSourceDir))
{
stb_project_source_dir.Text = string.Format("/home/{0}/sources", config.UserName);
}
else
{
stb_project_source_dir.Text = monitorConfig.spring.ProjectSourceDir;
}
stb_project_svn.Text = monitorConfig.spring.ProjectSvnUrl;
}
else if (monitorConfig.tomcat != null)
{
stb_tomcat_name.Text = monitorConfig.tomcat.TomcatName;
stb_tomcat_path.Text = monitorConfig.tomcat.TomcatDir;
stb_tomcat_port.Text = monitorConfig.tomcat.TomcatPort;
}
else if (monitorConfig.nginx != null)
{
stb_nginx_name.Text = monitorConfig.nginx.NginxName;
stb_nginx_path.Text = monitorConfig.nginx.NginxPath;
stb_nginx_path.Text = monitorConfig.nginx.NginxConfig;
}
else if (monitorConfig.ice != null)
{
stb_ice_appname.Text = monitorConfig.ice.AppName;
stb_ice_srvpath.Text = monitorConfig.ice.IceSrvDir;
stb_ice_servername.Text = monitorConfig.ice.ServerName;
stb_ice_ports.Text = monitorConfig.ice.NodePorts;
}
TabPage page = tabControl1.TabPages[tabIndex];
for (int i = tabControl1.TabCount - 1; i >= 0; i--)
{
try
{
if (page != tabControl1.TabPages[i])
{
tabControl1.TabPages[i].Parent = null;
}
}
catch { }
}
}
else
{
stb_home_url.Text = string.Format("http://{0}:[port]", config.Host);
stb_sh_dir.Text = string.Format("/home/{0}/bin", config.UserName);
stb_project_source_dir.Text = string.Format("/home/{0}/sources", config.UserName);
tabControl1.SelectedIndex = tabIndex;
}
stb_app_name.SkinTxt.TextChanged += AppName_TextChanged;
stb_build_file.SkinTxt.KeyUp += sh_file_KeyUp;
stb_ctl_file.SkinTxt.KeyUp += sh_file_KeyUp;
stb_tomcat_path.SkinTxt.TextChanged += Tomcat_TextChanged;
stb_tomcat_name.SkinTxt.KeyUp += tomcat_name_KeyUp;
}
19
View Source File : RedisWriter.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public byte[] Prepare(RedisCommand command)
{
var parts = command.Command.Split(' ');
int length = parts.Length + command.Arguments.Length;
StringBuilder sb = new StringBuilder();
sb.Append(MultiBulk).Append(length).Append(EOL);
foreach (var part in parts)
sb.Append(Bulk).Append(_io.Encoding.GetByteCount(part)).Append(EOL).Append(part).Append(EOL);
MemoryStream ms = new MemoryStream();
var data = _io.Encoding.GetBytes(sb.ToString());
ms.Write(data, 0, data.Length);
foreach (var arg in command.Arguments)
{
if (arg != null && arg.GetType() == typeof(byte[]))
{
data = arg as byte[];
var data2 = _io.Encoding.GetBytes($"{Bulk}{data.Length}{EOL}");
ms.Write(data2, 0, data2.Length);
ms.Write(data, 0, data.Length);
ms.Write(new byte[] { 13, 10 }, 0, 2);
}
else
{
string str = String.Format(CultureInfo.InvariantCulture, "{0}", arg);
data = _io.Encoding.GetBytes($"{Bulk}{_io.Encoding.GetByteCount(str)}{EOL}{str}{EOL}");
ms.Write(data, 0, data.Length);
}
//string str = String.Format(CultureInfo.InvariantCulture, "{0}", arg);
//sb.Append(Bulk).Append(_io.Encoding.GetByteCount(str)).Append(EOL).Append(str).Append(EOL);
}
return ms.ToArray();
}
19
View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void customShellListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (customShellListView.SelectedItems.Count > 0)
{
ListViewItem item = customShellListView.SelectedItems[0];
if (null != item)
{
CmdShell cmds = (CmdShell)item.Tag;
StringBuilder sb = new StringBuilder();
foreach (TaskShell task in cmds.ShellList)
{
if (cmds.TaskType == TaskType.Default)
{
sb.AppendLine(task.Shell);
}
else if (cmds.TaskType == TaskType.Timed)
{
sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
}
}
shellView.Text = sb.ToString();
if (cmds.TaskType == TaskType.Default)
{
btn_run.Enabled = true;
}
return;
}
}
btn_run.Enabled = false;
shellView.Text = "";
}
19
View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void 删除文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
ListViewItem item = listView1.SelectedItems[0];
YmlFile file = (YmlFile)item.Tag;
DialogResult dr = MessageBox.Show(this, "您确定要删除此文件吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if(dr == System.Windows.Forms.DialogResult.OK){
monitorForm.RunShell(string.Format("rm -rf {0}", file.remotePath + file.remoteName), false, true);
listView1.Items.Remove(item);
}
}
}
19
View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void LoadProjectList()
{
ThreadPool.QueueUserWorkItem((a) => {
List<JObject> itemList = new List<JObject>();
// 1、获取webapps下的项目
ArrayList files = (ArrayList)monitorForm.RunSftpShell(string.Format("ls {0}webapps/", l_tomcat_path.Text), false, false);
if (files != null)
{
string dirname = "";
JObject json = null;
Object obj = null;
for (int ii = 0; ii < files.Count; ii++)
{
obj = files[ii];
if (obj is ChannelSftp.LsEntry)
{
dirname = ((ChannelSftp.LsEntry)obj).getFilename();
if (dirname.IndexOf(".") == -1 && dirname.IndexOf(":") == -1)
{
json = new JObject();
json.Add("name", dirname);
json.Add("url", l_visit_url.Text + (dirname == "ROOT" ? "" : "/" + dirname));
json.Add("path", l_tomcat_path.Text + "webapps/" + dirname);
itemList.Add(json);
}
}
}
}
// 2、获取server.xml中的映射配置
List<JObject> itemList2 = loadTomcatServerProject();
foreach (JObject p in itemList2)
{
itemList.Add(p);
}
// 渲染列表
this.BeginInvoke((MethodInvoker)delegate()
{
projects.Items.Clear();
ListViewItem item = null;
ListViewItem.ListViewSubItem subItem = null;
foreach (JObject pro in itemList)
{
item = new ListViewItem();
item.Tag = pro;
item.Name = pro["name"].ToString();
item.Text = pro["url"].ToString();
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = pro["path"].ToString();
item.SubItems.Add(subItem);
projects.Items.Add(item);
}
});
});
}
19
View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void WriteLog(string flag, string id, string local, string remote)
{
try
{
string log = "";
if (flag == "L2R")
{
log = string.Format("【{0}】 - [{1}] Transfers File To {2},{3} -> {4} ", user.Host, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "Remote", local, remote);
}
else
{
log = string.Format("[{0} {1}] Transfers File To {2},{3} -> {4} ", user.Host, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "Local", remote, local);
}
WriteLog2(log);
}
catch(Exception e) {
logger.Error("格式化日志报错", e);
}
}
19
View Source File : IceDeployVersionForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void MvnPackage()
{
try
{
string path = stb_local_pdir.Text;
DirectoryInfo dire = new DirectoryInfo(path);
String cmd = string.Format("cd {0} & mvn package --settings {1} -DskipTests", dire.Parent.FullName, stb_maven_xml.Text);
CmdResult result = Command.run(cmd);
if (result.isFailed())
{
errorLabel.Text = "打包失败:" + result.result;
run = false;
MessageBox.Show(this, errorLabel.Text);
}
else if (result.isSuccess())
{
step = 3;
}
}
catch (Exception ex)
{
errorLabel.Text = "mvn package 异常:" + ex.Message;
run = false;
MessageBox.Show(this, errorLabel.Text);
}
}
19
View Source File : IceDeployVersionForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void UpdateConfig()
{
try
{
string localXml = stb_icexml.Text;
string remote_pdir = stb_remote_pdir.Text;
string remoteXml = Utils.PathEndAddSlash(remote_pdir) + "config/" + ice.AppName + ".xml";
monitorForm.getSftp().put(localXml, remoteXml, ChannelSftp.OVERWRITE);
// 更新
monitorForm.RunShell(Utils.PathEndAddSlash(remote_pdir) + "bin/admin.sh", false, true);
monitorForm.GetShellResult(string.Format("application update config/{0}.xml", ice.AppName), (s) => {
monitorForm.RunShell("quit", false);
step = 5;
}, true);
}
catch (Exception ex)
{
errorLabel.Text = string.Format("application update config/{0}.xml 异常:", ice.AppName) + ex.Message;
run = false;
MessageBox.Show(this, errorLabel.Text);
}
}
19
View Source File : IceDeployVersionForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void RestartService()
{
try
{
string remote_pdir = stb_remote_pdir.Text;
monitorForm.RunShell(Utils.PathEndAddSlash(remote_pdir) + "bin/admin.sh", false, true);
monitorForm.RunShell("server stop " + ice.ServerName, false, true);
monitorForm.RunShell("server start " + ice.ServerName, false, true);
monitorForm.RunShell("quit", false, true);
step = 6;
}
catch (Exception ex)
{
errorLabel.Text = string.Format("Restart Service 异常:", ice.AppName) + ex.Message;
run = false;
MessageBox.Show(this, errorLabel.Text);
}
}
19
View Source File : IceDeployVersionForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
void stb_local_pdir_TextChanged(object sender, EventArgs e)
{
string dir = stb_local_pdir.Text;
string path = stb_icexml.Text;
if (!string.IsNullOrWhiteSpace(dir) && string.IsNullOrWhiteSpace(path))
{
if (Directory.Exists(dir))
{
dir = dir.Replace("\\", "/");
if(!dir.EndsWith("/")){
dir += "/";
}
path = string.Format("{0}icedeploy/config/{1}.xml", dir, ice.AppName);
if (File.Exists(path))
{
stb_icexml.Text = path;
}
}
}
}
19
View Source File : MainForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void OpenSshSessionWindow(SessionConfig sessionConfig)
{
FATabStripItem page = new FATabStripItem();
MonitorForm form = new MonitorForm(sessionConfig);
form.FormBorderStyle = FormBorderStyle.None;
form.TopLevel = false;
form.Dock = DockStyle.Fill;
form.Show();
page.Tag = sessionConfig;
page.Name = "page-" + TAB_INDEX;
page.replacedle = string.Format("{0} {1}", faTab.Items.Count + 1, sessionConfig.Name);
page.Controls.Add(form);
TAB_MONITOR.Add(page, form);
faTab.Items.Add(page);
faTab.SelectedItem = page;
page.ContextMenuStrip = contextMenuStrip1;
TAB_INDEX++;
tsl_info1.Text = sessionConfig.Host + "@" + sessionConfig.UserName;
}
19
View Source File : MainForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void RenderSessionList()
{
tool_open.DropDownItems.Clear();
tool_attr.DropDownItems.Clear();
Dictionary<string, SessionConfig> _session_config_dic = AppConfig.Instance.SessionConfigDict;
ToolStripMenuItem sessionItem = null, sessionAttrItem = null;
foreach (KeyValuePair<string, SessionConfig> item in _session_config_dic)
{
sessionItem = new ToolStripMenuItem();
sessionItem.Image = Properties.Resources.monitor;
sessionItem.Text = string.Format("{0} {1}", item.Value.Index, item.Value.Name);
sessionItem.ToolTipText = "";
sessionItem.Tag = item.Value;
tool_open.DropDownItems.Add(sessionItem);
sessionItem.Click += sessionItem_Click;
sessionAttrItem = new ToolStripMenuItem();
sessionAttrItem.Image = Properties.Resources.monitor;
sessionAttrItem.Text = string.Format("{0} {1}", item.Value.Index, item.Value.Name);
sessionAttrItem.ToolTipText = "";
sessionAttrItem.Tag = item.Value;
tool_attr.DropDownItems.Add(sessionAttrItem);
sessionAttrItem.Click += sessionAttrItem_Click;
}
}
19
View Source File : RedisReader.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void ReadCRLF() // TODO: remove hardcoded
{
var r = _io.ReadByte();
var n = _io.ReadByte();
//Console.WriteLine($"ReadCRLF: {r} {n}");
if (r != (byte)13 && n != (byte)10)
throw new RedisProtocolException(String.Format("Expecting CRLF; got bytes: {0}, {1}", r, n));
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private void menuRemoveDuplicateServer_Click(object sender, EventArgs e)
{
Utils.DedupServerList(config.vmess, out List<VmessItem> servers, config.keepOlderDedupl);
int oldCount = config.vmess.Count;
int newCount = servers.Count;
if (servers != null)
{
config.vmess = servers;
}
RefreshServers();
LoadV2ray();
UI.Show(string.Format(UIRes.I18N("RemoveDuplicateServerResult"), oldCount, newCount));
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private void UpdateStatisticsHandler(ulong up, ulong down, List<ServerStareplacedem> statistics)
{
try
{
up /= (ulong)(config.statisticsFreshRate / 1000f);
down /= (ulong)(config.statisticsFreshRate / 1000f);
toolSslServerSpeed.Text = string.Format("{0}/s↑ | {1}/s↓", Utils.HumanFy(up), Utils.HumanFy(down));
List<string[]> datas = new List<string[]>();
for (int i = 0; i < config.vmess.Count; i++)
{
int index = statistics.FindIndex(item_ => item_.itemId == config.vmess[i].gereplacedemId());
if (index != -1)
{
lvServers.Invoke((MethodInvoker)delegate
{
lvServers.BeginUpdate();
lvServers.Items[i].SubItems["todayDown"].Text = Utils.HumanFy(statistics[index].todayDown);
lvServers.Items[i].SubItems["todayUp"].Text = Utils.HumanFy(statistics[index].todayUp);
lvServers.Items[i].SubItems["totalDown"].Text = Utils.HumanFy(statistics[index].totalDown);
lvServers.Items[i].SubItems["totalUp"].Text = Utils.HumanFy(statistics[index].totalUp);
lvServers.EndUpdate();
});
}
}
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
}
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private void tsbTestMe_Click(object sender, EventArgs e)
{
SpeedtestHandler statistics = new SpeedtestHandler(ref config);
string result = statistics.RunAvailabilityCheck() + "ms";
AppendText(false, string.Format(UIRes.I18N("TestMeOutput"), result));
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private void menuMsgBoxFilter_Click(object sender, EventArgs e)
{
var fm = new MsgFilterSetForm();
fm.MsgFilter = MsgFilter;
if (fm.ShowDialog() == DialogResult.OK)
{
MsgFilter = fm.MsgFilter;
gbMsgreplacedle.Text = string.Format(UIRes.I18N("MsgInformationreplacedle"), MsgFilter);
}
}
19
View Source File : RoutingRuleSettingDetailsForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private void btnOK_Click(object sender, EventArgs e)
{
EndBindingData();
var hasRule = false;
if (rulesItem.domain != null && rulesItem.domain.Count > 0)
{
hasRule = true;
}
if (rulesItem.ip != null && rulesItem.ip.Count > 0)
{
hasRule = true;
}
if (rulesItem.protocol != null && rulesItem.protocol.Count > 0)
{
hasRule = true;
}
if (!Utils.IsNullOrEmpty(rulesItem.port))
{
hasRule = true;
}
if (!hasRule)
{
UI.ShowWarning(string.Format(UIRes.I18N("RoutingRuleDetailRequiredTips"), "Port/Protocol/Domain/IP"));
return;
}
this.DialogResult = DialogResult.OK;
}
See More Examples