Here are the examples of the csharp api string.IsNullOrWhiteSpace(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
32732 Examples
19
View Source File : GhostNameTag.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void Render() {
base.Render();
float a = Alpha * (CelesteNetClientModule.Settings.NameOpacity / 4f);
if (a <= 0f || string.IsNullOrWhiteSpace(Name))
return;
Level level = SceneAs<Level>();
if (level == null)
return;
float scale = level.GetScreenScale();
Vector2 pos = Tracking?.Position ?? Position;
pos.Y -= 16f;
pos = level.WorldToScreen(pos);
Vector2 size = CelesteNetClientFont.Measure(Name) * scale;
pos = pos.Clamp(
0f + size.X * 0.25f + 32f, 0f + size.Y * 0.5f + 32f,
1920f - size.X * 0.25f - 32f, 1080f - 32f
);
CelesteNetClientFont.DrawOutline(
Name,
pos,
new(0.5f, 1f),
Vector2.One * 0.5f * scale,
Color.White * a,
2f,
Color.Black * (a * a * a)
);
}
19
View Source File : CelesteNetPlayerListComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void RebuildList() {
if (MDraw.DefaultFont == null || Client == null || Channels == null)
return;
DataPlayerInfo[] all = Client.Data.GetRefs<DataPlayerInfo>();
List<Blob> list = new() {
new Blob {
Text = $"{all.Length} player{(all.Length == 1 ? "" : "s")}",
Color = ColorCountHeader
}
};
StringBuilder builder = new();
switch (Mode) {
case ListMode.Clreplacedic:
foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
if (string.IsNullOrWhiteSpace(player.DisplayName))
continue;
builder.Append(player.DisplayName);
DataChannelList.Channel channel = Channels.List.FirstOrDefault(c => c.Players.Contains(player.ID));
if (channel != null && !string.IsNullOrEmpty(channel.Name)) {
builder
.Append(" #")
.Append(channel.Name);
}
if (Client.Data.TryGetBoundRef(player, out DataPlayerState state))
AppendState(builder, state);
builder.AppendLine();
}
list.Add(new() {
Text = builder.ToString().Trim(),
ScaleFactor = 1f
});
break;
case ListMode.Channels:
HashSet<DataPlayerInfo> listed = new();
DataChannelList.Channel own = Channels.List.FirstOrDefault(c => c.Players.Contains(Client.PlayerInfo.ID));
if (own != null) {
list.Add(new() {
Text = own.Name,
Color = ColorChannelHeaderOwn
});
builder.Clear();
foreach (DataPlayerInfo player in own.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p)))
listed.Add(ListPlayerUnderChannel(builder, player));
list.Add(new() {
Text = builder.ToString().Trim(),
ScaleFactor = 0.5f
});
}
foreach (DataChannelList.Channel channel in Channels.List) {
if (channel == own)
continue;
list.Add(new() {
Text = channel.Name,
Color = ColorChannelHeader
});
builder.Clear();
foreach (DataPlayerInfo player in channel.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p)))
listed.Add(ListPlayerUnderChannel(builder, player));
list.Add(new() {
Text = builder.ToString().Trim(),
ScaleFactor = 1f
});
}
bool wrotePrivate = false;
builder.Clear();
foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
if (listed.Contains(player) || string.IsNullOrWhiteSpace(player.DisplayName))
continue;
if (!wrotePrivate) {
wrotePrivate = true;
list.Add(new() {
Text = "!<private>",
Color = ColorChannelHeaderPrivate
});
}
builder.AppendLine(player.DisplayName);
}
if (wrotePrivate) {
list.Add(new() {
Text = builder.ToString().Trim(),
ScaleFactor = 1f
});
}
break;
}
List = list;
}
19
View Source File : GhostEmote.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void Render() {
base.Render();
if (Scene is not Level level)
return;
float popupScale = PopupScale * level.GetScreenScale();
MTexture icon = null;
string text = null;
if (IsIcon(Value))
icon = GetIcon(Value, Time);
else
text = Value;
float alpha = Alpha * PopupAlpha;
if (alpha <= 0f || (icon == null && string.IsNullOrWhiteSpace(text)))
return;
if (Tracking == null)
return;
Vector2 pos = level.WorldToScreen(Position);
if (Float)
pos.Y -= (float) Math.Sin(Time * 2f) * 4f;
if (icon != null) {
Vector2 size = new(icon.Width, icon.Height);
float scale = (Size / Math.Max(size.X, size.Y)) * 0.5f * popupScale;
size *= scale;
pos = pos.Clamp(
0f + size.X * 0.5f + 64f, 0f + size.Y * 1f + 64f,
1920f - size.X * 0.5f - 64f, 1080f - 64f
);
icon.DrawJustified(
pos,
new(0.5f, 1f),
Color.White * alpha,
Vector2.One * scale
);
} else {
Vector2 size = CelesteNetClientFont.Measure(text);
float scale = (Size / Math.Max(size.X, size.Y)) * 0.5f * popupScale;
size *= scale;
pos = pos.Clamp(
0f + size.X * 0.5f, 0f + size.Y * 1f,
1920f - size.X * 0.5f, 1080f
);
CelesteNetClientFont.DrawOutline(
text,
pos,
new(0.5f, 1f),
Vector2.One * scale,
Color.White * alpha,
2f,
Color.Black * alpha * alpha * alpha
);
}
}
19
View Source File : ChatCMDChannel.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void ParseAndRun(ChatCMDEnv env) {
CelesteNetPlayerSession? session = env.Session;
if (session == null)
return;
Channels channels = env.Server.Channels;
Channel? c;
if (int.TryParse(env.Text, out int page) ||
string.IsNullOrWhiteSpace(env.Text)) {
if (channels.All.Count == 0) {
env.Send($"No channels. See {Chat.Settings.CommandPrefix}{ID} on how to create one.");
return;
}
const int pageSize = 8;
StringBuilder builder = new();
page--;
int pages = (int) Math.Ceiling(channels.All.Count / (float) pageSize);
if (page < 0 || pages <= page)
throw new Exception("Page out of range.");
if (page == 0)
builder
.Append("You're in ")
.Append(session.Channel.Name)
.AppendLine();
for (int i = page * pageSize; i < (page + 1) * pageSize && i < channels.All.Count; i++) {
c = channels.All[i];
builder
.Append(c.PublicName)
.Append(" - ")
.Append(c.Players.Count)
.Append(" players")
.AppendLine();
}
builder
.Append("Page ")
.Append(page + 1)
.Append("/")
.Append(pages);
env.Send(builder.ToString().Trim());
return;
}
Tuple<Channel, Channel> tuple = channels.Move(session, env.Text);
if (tuple.Item1 == tuple.Item2) {
env.Send($"Already in {tuple.Item2.Name}");
} else {
env.Send($"Moved to {tuple.Item2.Name}");
}
}
19
View Source File : ChatCMDEmote.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void ParseAndRun(ChatCMDEnv env) {
if (env.Session == null || string.IsNullOrWhiteSpace(env.Text))
return;
DataEmote emote = new() {
Player = env.Player,
Text = env.Text.Trim()
};
env.Session.Con.Send(emote);
env.Server.Data.Handle(env.Session.Con, emote);
}
19
View Source File : CelesteNetTCPUDPConnection.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void ReadTeapot(out string[] features, out uint token) {
features = Dummy<string>.EmptyArray;
token = 0;
using StreamReader reader = new(TCPReaderStream, Encoding.UTF8, false, 1024, true);
for (string line; !string.IsNullOrWhiteSpace(line = reader?.ReadLine() ?? "");) {
if (line.StartsWith(CelesteNetUtils.HTTPTeapotConFeatures)) {
features = line.Substring(CelesteNetUtils.HTTPTeapotConFeatures.Length).Trim().Split(CelesteNetUtils.ConnectionFeatureSeparators);
}
if (line.StartsWith(CelesteNetUtils.HTTPTeapotConToken)) {
token = uint.Parse(line.Substring(CelesteNetUtils.HTTPTeapotConToken.Length).Trim());
}
}
}
19
View Source File : CelesteNetChatComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void Update(GameTime gameTime) {
base.Update(gameTime);
_Time += Engine.RawDeltaTime;
_TimeSinceCursorMove += Engine.RawDeltaTime;
bool isRebinding = Engine.Scene == null ||
Engine.Scene.Enreplacedies.FindFirst<KeyboardConfigUI>() != null ||
Engine.Scene.Enreplacedies.FindFirst<ButtonConfigUI>() != null;
if (!(Engine.Scene?.Paused ?? true) || isRebinding) {
string typing = Typing;
Active = false;
Typing = typing;
}
if (!Active && !isRebinding && Settings.ButtonChat.Button.Pressed) {
Active = true;
} else if (Active) {
Engine.Commands.Open = false;
_ControlHeld = MInput.Keyboard.Check(Keys.LeftControl) || MInput.Keyboard.Check(Keys.RightControl);
if (!MInput.Keyboard.Check(Keys.Left) && !MInput.Keyboard.Check(Keys.Right)) {
_CursorMoveFast = false;
_TimeSinceCursorMove = 0;
}
// boolean to determine if Left or Right were already held on previous frame
bool _directionHeldLast = MInput.Keyboard.PreviousState[Keys.Left] == KeyState.Down
|| MInput.Keyboard.PreviousState[Keys.Right] == KeyState.Down;
bool _cursorCanMove = true;
// conditions for the cursor to be moving:
// 1. Don't apply delays on first frame Left/Right is pressed
if (_directionHeldLast) {
// 2. Delay time depends on whether this is the initial delay or subsequent "scrolling" left or right
_cursorCanMove = _TimeSinceCursorMove > (_CursorMoveFast ? _CursorMoveDelay : _CursorInitialMoveDelay);
}
if (MInput.Keyboard.Pressed(Keys.Enter)) {
if (!string.IsNullOrWhiteSpace(Typing))
Repeat.Insert(1, Typing);
Send(Typing);
Active = false;
} else if (MInput.Keyboard.Pressed(Keys.Down) && RepeatIndex > 0) {
RepeatIndex--;
} else if (MInput.Keyboard.Pressed(Keys.Up) && RepeatIndex < Repeat.Count - 1) {
RepeatIndex++;
} else if (MInput.Keyboard.Check(Keys.Left) && _cursorCanMove && CursorIndex > 0) {
if (_ControlHeld) {
// skip over space right before the cursor, if there is one
if (Typing[_CursorIndex - 1] == ' ')
CursorIndex--;
if (CursorIndex > 0) {
int prevWord = Typing.LastIndexOf(" ", _CursorIndex - 1);
CursorIndex = (prevWord < 0) ? 0 : prevWord + 1;
}
} else {
CursorIndex--;
}
_TimeSinceCursorMove = 0;
_CursorMoveFast = _directionHeldLast;
_Time = 0;
} else if (MInput.Keyboard.Check(Keys.Right) && _cursorCanMove && CursorIndex < Typing.Length) {
if (_ControlHeld) {
int nextWord = Typing.IndexOf(" ", _CursorIndex);
CursorIndex = (nextWord < 0) ? Typing.Length : nextWord + 1;
} else {
CursorIndex++;
}
_TimeSinceCursorMove = 0;
_CursorMoveFast = _directionHeldLast;
_Time = 0;
} else if (MInput.Keyboard.Pressed(Keys.Home)) {
CursorIndex = 0;
} else if (MInput.Keyboard.Pressed(Keys.End)) {
CursorIndex = Typing.Length;
} else if (Input.ESC.Pressed) {
Active = false;
}
}
// Prevent menus from reacting to player input after exiting chat.
if (_ConsumeInput > 0) {
Input.MenuConfirm.ConsumeBuffer();
Input.MenuConfirm.ConsumePress();
Input.ESC.ConsumeBuffer();
Input.ESC.ConsumePress();
Input.Pause.ConsumeBuffer();
Input.Pause.ConsumePress();
_ConsumeInput--;
}
}
19
View Source File : CelesteNetPlayerListComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
private void AppendState(StringBuilder builder, DataPlayerState state) {
if (!string.IsNullOrWhiteSpace(state.SID))
builder
.Append(" @ ")
.Append(AreaDataExt.Get(state.SID)?.Name?.DialogCleanOrNull(Dialog.Languages["english"]) ?? state.SID)
.Append(" ")
.Append((char) ('A' + (int) state.Mode))
.Append(" ")
.Append(state.Level);
if (state.Idle)
builder.Append(" :celestenet_idle:");
}
19
View Source File : DebugCommands.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
[Command("con", "connect to a celestenet server")]
public static void Con(string server) {
CelesteNetClientModule.Settings.Connected = false;
if (!string.IsNullOrWhiteSpace(server)) {
CelesteNetClientModule.Settings.Server = server;
}
CelesteNetClientModule.Settings.Connected = true;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
static void Repack(string input, string[] extras, string output, string name = null) {
Console.Error.WriteLine($"Repacking: {input} -> {output}");
if (name == null)
name = Path.GetFileName(output);
string outputTmp = Path.Combine(Path.GetDirectoryName(output), name);
if (File.Exists(outputTmp))
File.Delete(outputTmp);
List<string> args = new List<string>();
args.Add($"/out:{outputTmp}");
args.Add(input);
foreach (string dep in extras)
if (!string.IsNullOrWhiteSpace(dep))
args.Add(dep.Trim());
RepackOptions options = new RepackOptions(args);
ILRepack repack = new ILRepack(options);
repack.Repack();
if (output != outputTmp) {
if (File.Exists(output))
File.Delete(output);
File.Move(outputTmp, output);
}
}
19
View Source File : MaybeExTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public static MaybeEx<string> ValidateString(string s)
=> string.IsNullOrWhiteSpace(s) || !s.Contains(',')
? MaybeEx<string>.Nothing()
: s;
19
View Source File : MaybeTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public static Maybe<string> ValidateString(string s)
=> string.IsNullOrWhiteSpace(s) || !s.Contains(',')
? Maybe<string>.Nothing()
: s;
19
View Source File : TSqlBuilder.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
protected override void AppendUnicodePrefix(string str)
{
if (string.IsNullOrWhiteSpace(str))
{
return;
}
bool unicode = false;
for (int i = 0; i < str.Length && !unicode; i++)
{
if (str[i] > 255)
{
unicode = true;
}
}
if (unicode)
{
this.Builder.Append('N');
}
}
19
View Source File : Alias.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public IExprAlias? BuildAliasExpression()
{
if (this._proxy != null)
{
return this._proxy;
}
if (!this._notAuto)
{
return new ExprAliasGuid(Guid.NewGuid());
}
if (this._name == null || string.IsNullOrWhiteSpace(this._name))
{
return null;
}
return new ExprAlias(this._name);
}
19
View Source File : ImageGridMetadata.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public static ImageGridMetadata TryDeserialize(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
if (!value.StartsWith("<ImageGridMetadata", StringComparison.Ordinal))
{
return null;
}
int tileColumnCount = (int)GetPropertyValue(value, TileColumnCountPropertyName);
int tileRowCount = (int)GetPropertyValue(value, TileRowCountPropertyName);
uint outputHeight = GetPropertyValue(value, OutputHeightPropertyName);
uint outputWidth = GetPropertyValue(value, OutputWidthPropertyName);
uint tileImageHeight = GetPropertyValue(value, TileImageHeightPropertyName);
uint tileImageWidth = GetPropertyValue(value, TileImageWidthPropertyName);
return new ImageGridMetadata(tileColumnCount, tileRowCount, outputHeight, outputWidth, tileImageHeight, tileImageWidth);
}
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 static bool TryConvertStringToBoolean(string value, out bool result)
{
if (!string.IsNullOrWhiteSpace(value))
{
if (bool.TryParse(value, out result))
{
return true;
}
else if (value.Equals("1", StringComparison.Ordinal))
{
result = true;
return true;
}
else if (value.Equals("0", StringComparison.Ordinal))
{
result = false;
return true;
}
}
result = false;
return false;
}
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 : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054
License : GNU General Public License v3.0
Project Creator : 0xC0000054
private static bool TryGetValue(string item, string prefix, out string value)
{
if (item != null && item.StartsWith(prefix, StringComparison.Ordinal))
{
value = item.Substring(prefix.Length);
return !string.IsNullOrWhiteSpace(value);
}
value = null;
return false;
}
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 DialogResult ProcessOutputImages()
{
DialogResult result = DialogResult.Cancel;
OutputImageState state = server.OutputImageState;
if (state.Error != null)
{
ShowErrorMessage(state.Error);
}
else
{
IReadOnlyList<Surface> outputImages = state.OutputImages;
if (outputImages.Count > 1)
{
if (!string.IsNullOrWhiteSpace(outputFolder))
{
folderBrowserDialog.SelectedPath = outputFolder;
}
if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK)
{
outputFolder = folderBrowserDialog.SelectedPath;
try
{
OutputImageUtil.SaveAllToFolder(outputImages, outputFolder);
surface?.Dispose();
surface = null;
result = DialogResult.OK;
}
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.Size == EnvironmentParameters.SourceSurface.Size)
{
if (surface == null)
{
surface = new Surface(EnvironmentParameters.SourceSurface.Width, EnvironmentParameters.SourceSurface.Height);
}
surface.CopySurface(output);
result = DialogResult.OK;
}
else
{
if (surface != null)
{
surface.Dispose();
surface = null;
}
// 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);
resizedImageSaveDialog.FileName = DateTime.Now.ToString("yyyyMMdd-THHmmss") + ".png";
if (resizedImageSaveDialog.ShowDialog(this) == DialogResult.OK)
{
string resizedImagePath = resizedImageSaveDialog.FileName;
try
{
using (Bitmap bitmap = output.CreateAliasedBitmap())
{
bitmap.Save(resizedImagePath, System.Drawing.Imaging.ImageFormat.Png);
}
result = DialogResult.OK;
}
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);
}
}
}
}
FinishTokenUpdate();
}
return result;
}
19
View Source File : ResponseExtensions.cs
License : Apache License 2.0
Project Creator : 0xFireball
License : Apache License 2.0
Project Creator : 0xFireball
public static Response FromPartialStream(this IResponseFormatter response, Request request, Stream stream,
string contentType)
{
// Store the len
var len = stream.Length;
// Create the response now
var res = response.FromStream(stream, contentType)
.WithHeader("Connection", "Keep-alive")
.WithHeader("Accept-ranges", "Bytes");
// Use the partial status code
res.StatusCode = HttpStatusCode.PartialContent;
long startPos = 0;
foreach (var s in request.Headers["Range"])
{
var start = s.Split('=')[1];
var m = Regex.Match(start, @"(\d+)-(\d+)?");
start = m.Groups[1].Value;
var end = len - 1;
if (!string.IsNullOrWhiteSpace(m.Groups[2]?.Value))
{
end = Convert.ToInt64(m.Groups[2].Value);
}
startPos = Convert.ToInt64(start);
var length = len - startPos;
res.WithHeader("Content-range", "Bytes " + start + "-" + end + "/" + len);
res.WithHeader("Content-length", length.ToString(CultureInfo.InvariantCulture));
}
stream.Seek(startPos, SeekOrigin.Begin);
return res;
}
19
View Source File : PenguinUploadBootstrapper.cs
License : Apache License 2.0
Project Creator : 0xFireball
License : Apache License 2.0
Project Creator : 0xFireball
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
base.ApplicationStartup(container, pipelines);
StatelessAuthentication.Enable(pipelines, new StatelessAuthenticationConfiguration(ctx =>
{
// Check for the API key
string accessToken = null;
if (ctx.Request.Query.apikey.HasValue)
{
accessToken = ctx.Request.Query.apikey;
}
else if (ctx.Request.Form["apikey"].HasValue)
{
accessToken = ctx.Request.Form["apikey"];
}
else
{
var authHeader = ctx.Request.Headers.Authorization;
if (!string.IsNullOrWhiteSpace(authHeader))
{
accessToken = authHeader;
}
}
// Authenticate the request
var authService = new ApiClientAuthenticationService(ServerContext);
return accessToken == null ? null : authService.ResolveClientIdenreplacedy(accessToken);
}));
}
19
View Source File : VistaFileSaveDialog.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054
License : GNU General Public License v3.0
Project Creator : 0xC0000054
private NativeStructs.COMDLG_FILTERSPEC[] GetFilterItems()
{
List<NativeStructs.COMDLG_FILTERSPEC> filterItems = new List<NativeStructs.COMDLG_FILTERSPEC>();
if (!string.IsNullOrWhiteSpace(filter))
{
string[] splireplacedems = filter.Split('|');
// The split filter string array must contain an even number of items.
if ((splireplacedems.Length & 1) == 0)
{
for (int i = 0; i < splireplacedems.Length; i += 2)
{
NativeStructs.COMDLG_FILTERSPEC filterSpec = new NativeStructs.COMDLG_FILTERSPEC
{
pszName = splireplacedems[i],
pszSpec = splireplacedems[i + 1]
};
filterItems.Add(filterSpec);
}
}
}
return filterItems.ToArray();
}
19
View Source File : DefaultCacheKeyBuilder.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private static string HashCacheKey(string source)
{
if (string.IsNullOrWhiteSpace(source))
return string.Empty;
_md5Hasher ??= MD5.Create();
var bytes = Encoding.UTF8.GetBytes(source);
var hash = _md5Hasher.ComputeHash(bytes);
return ToString(hash);
}
19
View Source File : SQLName.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static SQLName Parse(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
return new SQLName(name);
}
19
View Source File : PartitionRedisCacheProvider.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public CacheValue<TResult> TryGet<TResult>(string key)
{
var val = Cache.GetString(key);
if (string.IsNullOrWhiteSpace(val))
return new CacheValue<TResult>(default, false);
return Serializer.Deserialize<CacheValue<TResult>>(val);
}
19
View Source File : RedisCacheProvider.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public CacheValue<TResult> TryGet<TResult>(string key)
{
var val = Client.Get(key);
if (string.IsNullOrWhiteSpace(val))
return new CacheValue<TResult>(default, false);
return Serializer.Deserialize<CacheValue<TResult>>(val);
}
19
View Source File : ConsulServiceDiscovery.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public async Task<bool> RegisterAsync(CancellationToken cancellationToken = default)
{
if (ConsulRegisterServiceConfiguration == null)
{
ConsulRegisterServiceConfiguration = new ConsulRegisterServiceConfiguration();
}
if (string.IsNullOrWhiteSpace(ConsulRegisterServiceConfiguration.Id))
{
ConsulRegisterServiceConfiguration.Id = ServerSettings.ToString();
}
if (string.IsNullOrWhiteSpace(ConsulRegisterServiceConfiguration.Name))
{
ConsulRegisterServiceConfiguration.Name = ServerSettings.ToString();
}
if (string.IsNullOrWhiteSpace(ConsulRegisterServiceConfiguration.Name))
throw new ArgumentNullException(nameof(ConsulRegisterServiceConfiguration.Name), "Service name value cannot be null.");
Logger.LogTrace("Start registering with consul[{0}]...", ConsulClientConfigure.Address);
try
{
using (var consul = new ConsulClient(conf =>
{
conf.Address = ConsulClientConfigure.Address;
conf.Datacenter = ConsulClientConfigure.Datacenter;
conf.Token = ConsulClientConfigure.Token;
conf.WaitTime = ConsulClientConfigure.WaitTime;
}))
{
ConsulRegisterServiceConfiguration.Meta = new Dictionary<string, string>{
{"X-Tls",(ServerSettings.X509Certificate2!=null).ToString()}
};
if (ServerSettings.Weight.HasValue)
{
ConsulRegisterServiceConfiguration.Meta.Add("X-Weight", ServerSettings.Weight.ToString());
}
//Register service to consul agent
var result = await consul.Agent.ServiceRegister(new AgentServiceRegistration
{
Address = ServerSettings.Address,
Port = ServerSettings.Port,
ID = ConsulRegisterServiceConfiguration.Id,
Name = ConsulRegisterServiceConfiguration.Name,
EnableTagOverride = ConsulRegisterServiceConfiguration.EnableTagOverride,
Meta = ConsulRegisterServiceConfiguration.Meta,
Tags = ConsulRegisterServiceConfiguration.Tags,
Check = new AgentServiceCheck
{
TCP = ServerSettings.ToString(),
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20),
Timeout = TimeSpan.FromSeconds(3),
Interval = ConsulRegisterServiceConfiguration.HealthCheckInterval
}
}, cancellationToken);
if (result.StatusCode != HttpStatusCode.OK)
{
Logger.LogError("Registration service failed:{0}", result.StatusCode);
throw new ConsulRequestException("Registration service failed.", result.StatusCode);
}
Logger.LogTrace("Consul service registration completed");
return result.StatusCode == HttpStatusCode.OK;
}
}
catch (Exception e)
{
Logger.LogError(e, "Registration service failed:{0}", e.Message);
return false;
}
}
19
View Source File : DefaultCacheKeyBuilder.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public string Generate(string sql, object param, string customKey, int? pageIndex = default, int? pageSize = default)
{
if (!string.IsNullOrWhiteSpace(customKey))
return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{customKey}";
if (string.IsNullOrWhiteSpace(sql))
throw new ArgumentNullException(nameof(sql));
var builder = new StringBuilder();
builder.AppendFormat("{0}:", sql);
if (param == null)
return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd(':'))}";
var prop = GetProperties(param);
foreach (var item in prop)
{
builder.AppendFormat("{0}={1}&", item.Name, item.GetValue(param));
}
if (pageIndex.HasValue)
{
builder.AppendFormat("pageindex={0}&", pageIndex.Value);
}
if (pageSize.HasValue)
{
builder.AppendFormat("pagesize={0}&", pageSize.Value);
}
return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd('&'))}";
}
19
View Source File : DefaultConnectionStringProvider.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private ConnectionConfiguration Bind(string connectionName)
{
var section = Configuration.GetSection($"ConnectionStrings:{connectionName}");
if (!section.Exists())
{
Logger.LogError($"Configuration node 'ConnectionStrings:{connectionName}' not found.");
throw new Exception($"Configuration node 'ConnectionStrings:{connectionName}' not found.");
}
var configure = section.Get<ConnectionConfiguration>();
if (configure == null || string.IsNullOrWhiteSpace(configure.Master))
{
Logger.LogError($"The connection named '{connectionName}' master cannot be empty.");
throw new Exception($"The connection named '{connectionName}' master cannot be empty.");
}
if (configure.Slaves == null || !configure.Slaves.Any())
{
Logger.LogError($"The connection named '{connectionName}' slaves cannot be null,and at least one node.");
throw new Exception($"The connection named '{connectionName}' slaves cannot be null,and at least one node.");
}
return configure;
}
19
View Source File : BaseDapper.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public string GetSQL(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
if (SQLManager == null)
throw new InvalidOperationException("Please call the 'AddSQLSeparationForDapper' method first.");
return SQLManager.GetSQL(name);
}
19
View Source File : BaseDapper.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public (string CountSQL, string QuerySQL) GetPagingSQL(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
if (SQLManager == null)
throw new InvalidOperationException("Please call the 'AddSQLSeparationForDapper' method first.");
return SQLManager.GetPagingSQL(name);
}
19
View Source File : DependencyDapperAttribute.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public override object ResolveParameter(ParameterInfo parameter, IComponentContext context)
{
if (parameter == null) throw new ArgumentNullException(nameof(parameter));
if (context == null) throw new ArgumentNullException(nameof(context));
if (string.IsNullOrWhiteSpace(ServiceKey))
return ReadOnly ? context.ResolveKeyed("_slave", parameter.ParameterType, new NamedParameter("readOnly", true)) : context.Resolve(parameter.ParameterType);
return ReadOnly ? context.ResolveKeyed($"{ServiceKey}_slave", parameter.ParameterType, new NamedParameter("readOnly", true)) : context.ResolveKeyed(ServiceKey, parameter.ParameterType);
}
19
View Source File : ICachingKeyGenerator.Default.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public string GenerateKeyPlaceholder(string keyPrefix, int globalExpire, string route, MethodInfo methodInfo, CachingAttribute cachingAttribute = default)
{
var sb = new StringBuilder();
if (!string.IsNullOrWhiteSpace(keyPrefix))
sb.AppendFormat("{0}{1}", keyPrefix, LinkString);
if (cachingAttribute == null || string.IsNullOrWhiteSpace(cachingAttribute.Key))
{
sb.AppendFormat("{0}", route);
if (methodInfo.GetParameters().Length > 0)
sb.Append(LinkString + "{0}");
}
else
sb.Append(cachingAttribute.Key);
return sb.ToString();
}
19
View Source File : ConsulServiceDiscovery.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public async Task<IReadOnlyList<ServiceDiscoveryInfo>> QueryServiceAsync(string serviceName, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(serviceName))
throw new ArgumentNullException(nameof(serviceName));
using (var consul = new ConsulClient(conf =>
{
conf.Address = ConsulClientConfigure.Address;
conf.Datacenter = ConsulClientConfigure.Datacenter;
conf.Token = ConsulClientConfigure.Token;
conf.WaitTime = ConsulClientConfigure.WaitTime;
}))
{
try
{
var result = await consul.Health.Service(serviceName, "", true, cancellationToken);
if (result.StatusCode != HttpStatusCode.OK)
{
Logger.LogError("Query the service {0} failed:{0}", serviceName, result.StatusCode);
return new List<ServiceDiscoveryInfo>();
}
if (!result.Response.Any())
return new List<ServiceDiscoveryInfo>();
return result.Response.Select(p => new ServiceDiscoveryInfo(p.Service.ID, p.Service.Address, p.Service.Port, int.Parse(p.Service.Meta?.FirstOrDefault(m => m.Key == "X-Weight").Value ?? "0"), bool.Parse(p.Service.Meta?.FirstOrDefault(m => m.Key == "X-Tls").Value ?? "false"), p.Service.Meta)).ToList();
}
catch (Exception ex)
{
Logger.LogError("Query the service {2} error:{0}\n{1}", ex.Message, ex.StackTrace, serviceName);
throw;
}
}
}
19
View Source File : ValuesController.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
[HttpGet("search")]
public async Task<IActionResult> Search([FromQuery] string name = "")
{
var result = await MasterReader.QueryAsync("select * from company {where name like '%'||@name||'%'};".Splice(!string.IsNullOrWhiteSpace(name)), new { name });
return Ok(result);
}
19
View Source File : DefaultCacheKeyBuilder.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public string Generate(string sql, object param, string customKey, int? pageIndex = default, int? pageSize = default)
{
if (!string.IsNullOrWhiteSpace(customKey))
return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{customKey}";
if (string.IsNullOrWhiteSpace(sql))
throw new ArgumentNullException(nameof(sql));
var builder = new StringBuilder();
builder.AppendFormat("{0}:", sql);
if (param == null)
return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd(':'))}";
var prop = GetProperties(param);
foreach (var item in prop)
{
builder.AppendFormat("{0}={1}&", item.Name, item.GetValue(param));
}
if (pageIndex.HasValue)
{
builder.AppendFormat("pageindex={0}&", pageIndex.Value);
}
if (pageSize.HasValue)
{
builder.AppendFormat("pagesize={0}&", pageSize.Value);
}
return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd('&'))}";
}
19
View Source File : AutofacExtensions.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static ContainerBuilder AddDapper<TDbProvider>(this ContainerBuilder container, string connectionName = "DefaultConnection", string serviceKey = null, bool enableMasterSlave = false, Action<MonitorBuilder> monitorBuilder = null) where TDbProvider : IDapper
{
container.RegisterType<ResolveContext>().As<IResolveContext>().IfNotRegistered(typeof(IResolveContext)).InstancePerLifetimeScope();
container.RegisterType<ResolveKeyed>().As<IResolveKeyed>().IfNotRegistered(typeof(IResolveKeyed)).InstancePerLifetimeScope();
container.RegisterType<DefaultConnectionStringProvider>().As<IConnectionStringProvider>().SingleInstance();
container.RegisterType<WeightedPolling>().As<ILoadBalancing>().SingleInstance();
if (monitorBuilder != null)
{
var builder = new MonitorBuilder(container);
monitorBuilder.Invoke(builder);
container.RegisterInstance(new MonitorConfiguration
{
SlowCriticalValue = builder.Threshold,
EnableLog = builder.EnableLog,
HasCustomMonitorHandler = builder.HasCustomMonitorHandler
}).SingleInstance();
}
if (string.IsNullOrWhiteSpace(serviceKey))
{
if (enableMasterSlave)
{
if (monitorBuilder != null)
{
container.RegisterType<TDbProvider>().WithParameters(new[]
{
new NamedParameter("connectionName", connectionName),
new NamedParameter("enableMasterSlave", true)
}).InstancePerLifetimeScope();
container.Register<IDapper>((ctx, @params) => new DapperProxy(ctx.Resolve<TDbProvider>(@params), ctx.Resolve<IServiceProvider>())).InstancePerLifetimeScope();
container.RegisterType<TDbProvider>().Keyed<TDbProvider>("_slave").WithParameters(new[]
{
new NamedParameter("connectionName", connectionName),
new NamedParameter("enableMasterSlave", true)
}).InstancePerLifetimeScope();
container.Register<IDapper>((ctx, @params) => new DapperProxy(ctx.ResolveKeyed<TDbProvider>("_slave", @params), ctx.Resolve<IServiceProvider>()))
.InstancePerLifetimeScope();
}
else
{
container.RegisterType<TDbProvider>().As<IDapper>().WithParameters(new[]
{
new NamedParameter("connectionName", connectionName),
new NamedParameter("enableMasterSlave", true)
}).InstancePerLifetimeScope();
container.RegisterType<TDbProvider>().Keyed<IDapper>("_slave").WithParameters(new[]
{
new NamedParameter("connectionName", connectionName),
new NamedParameter("enableMasterSlave", true)
}).InstancePerLifetimeScope();
}
}
else
{
if (monitorBuilder != null)
{
container.RegisterType<TDbProvider>().WithParameter("connectionName", connectionName).InstancePerLifetimeScope();
container.Register<IDapper>((ctx, @params) => new DapperProxy(ctx.Resolve<TDbProvider>(@params), ctx.Resolve<IServiceProvider>())).InstancePerLifetimeScope();
}
else
container.RegisterType<TDbProvider>().As<IDapper>().WithParameter("connectionName", connectionName)
.InstancePerLifetimeScope();
}
}
else
{
if (enableMasterSlave)
{
if (monitorBuilder != null)
{
container.RegisterType<TDbProvider>().Keyed<TDbProvider>(serviceKey).WithParameters(new[]
{
new NamedParameter("connectionName", connectionName),
new NamedParameter("enableMasterSlave", true)
}).InstancePerLifetimeScope();
container.Register<IDapper>((ctx, @params) => new DapperProxy(ctx.ResolveKeyed<TDbProvider>(serviceKey, @params), ctx.Resolve<IServiceProvider>())).Keyed<IDapper>(serviceKey).InstancePerLifetimeScope();
container.RegisterType<TDbProvider>().Keyed<TDbProvider>($"{serviceKey}_slave").WithParameters(new[]
{
new NamedParameter("connectionName", connectionName),
new NamedParameter("enableMasterSlave", true)
}).InstancePerLifetimeScope();
container.Register<IDapper>((ctx, @params) => new DapperProxy(ctx.ResolveKeyed<TDbProvider>($"{serviceKey}_slave", @params), ctx.Resolve<IServiceProvider>())).Keyed<IDapper>($"{serviceKey}_slave").InstancePerLifetimeScope();
}
else
{
container.RegisterType<TDbProvider>().Keyed<IDapper>(serviceKey).WithParameters(new[]
{
new NamedParameter("connectionName", connectionName),
new NamedParameter("enableMasterSlave", true)
}).InstancePerLifetimeScope();
container.RegisterType<TDbProvider>().Keyed<IDapper>($"{serviceKey}_slave").WithParameters(new[]
{
new NamedParameter("connectionName", connectionName),
new NamedParameter("enableMasterSlave", true)
}).InstancePerLifetimeScope();
}
}
else
{
if (monitorBuilder != null)
{
container.RegisterType<TDbProvider>().Keyed<TDbProvider>(serviceKey)
.WithParameter("connectionName", connectionName).InstancePerLifetimeScope();
container.Register<IDapper>((ctx, @params) =>
new DapperProxy(ctx.ResolveKeyed<TDbProvider>(serviceKey, @params), ctx.Resolve<IServiceProvider>())).InstancePerLifetimeScope();
}
else
container.RegisterType<TDbProvider>().Keyed<IDapper>(serviceKey)
.WithParameter("connectionName", connectionName).InstancePerLifetimeScope();
}
}
return container;
}
19
View Source File : EnvironmentVariableReader.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static T Get<T>(string variable, T defaultValue = default)
{
var value = Environment.GetEnvironmentVariable(variable);
if (string.IsNullOrWhiteSpace(value))
return defaultValue;
value = value.ReplaceIpPlaceholder();
var matches = Regex.Matches(value, "[{](.*?)[}]");
if (matches.Count > 0)
{
foreach (var match in matches)
{
value = value.Replace(match.ToString(), Environment.GetEnvironmentVariable(match.ToString().TrimStart('{').TrimEnd('}')));
}
}
return (T)Convert.ChangeType(value, typeof(T));
}
19
View Source File : UraganoBuilder.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public void AddServer(string address, int port = 5730, string certUrl = "", string certPwd = "", int? weight = default)
{
UraganoSettings.ServerSettings = new ServerSettings
{
Address = address.ReplaceIpPlaceholder(),
Port = port,
Weight = weight
};
if (!string.IsNullOrWhiteSpace(certUrl))
{
if (!File.Exists(certUrl))
throw new FileNotFoundException($"Certificate file {certUrl} not found.");
UraganoSettings.ServerSettings.X509Certificate2 =
new X509Certificate2(certUrl, certPwd);
}
RegisterServerServices();
}
19
View Source File : UraganoBuilder.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public void AddServer(IConfigurationSection configurationSection)
{
UraganoSettings.ServerSettings = new ServerSettings();
if (configurationSection.Exists())
{
var addressSection = configurationSection.GetSection("address");
if (addressSection.Exists())
UraganoSettings.ServerSettings.Address = addressSection.Value.ReplaceIpPlaceholder();
var portSection = configurationSection.GetSection("port");
if (portSection.Exists())
UraganoSettings.ServerSettings.Port = int.Parse(portSection.Value);
var weightSection = configurationSection.GetSection("weight");
if (weightSection.Exists())
UraganoSettings.ServerSettings.Weight = int.Parse(weightSection.Value);
var certUrlSection = configurationSection.GetSection("certurl");
if (certUrlSection.Exists() && !string.IsNullOrWhiteSpace(certUrlSection.Value))
{
if (!File.Exists(certUrlSection.Value))
throw new FileNotFoundException($"Certificate file {certUrlSection.Value} not found.");
UraganoSettings.ServerSettings.X509Certificate2 = new X509Certificate2(certUrlSection.Value, configurationSection.GetValue<string>("certpwd"));
}
}
RegisterServerServices();
}
19
View Source File : ZooKeeperServiceDiscovery.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public async Task<bool> RegisterAsync(CancellationToken cancellationToken = default)
{
if (ZooKeeperRegisterServiceConfiguration == null)
{
ZooKeeperRegisterServiceConfiguration = new ZooKeeperRegisterServiceConfiguration();
}
if (string.IsNullOrWhiteSpace(ZooKeeperRegisterServiceConfiguration.Id))
{
ZooKeeperRegisterServiceConfiguration.Id = ServerSettings.ToString();
}
if (string.IsNullOrWhiteSpace(ZooKeeperRegisterServiceConfiguration.Name))
{
ZooKeeperRegisterServiceConfiguration.Name = ServerSettings.ToString();
}
if (string.IsNullOrWhiteSpace(ZooKeeperRegisterServiceConfiguration.Name))
throw new ArgumentNullException(nameof(ZooKeeperRegisterServiceConfiguration.Name), "Service name value cannot be null.");
try
{
var data = Codec.Serialize(new ZooKeeperNodeInfo
{
Weight = ServerSettings.Weight ?? 0,
Address = ServerSettings.Address,
Port = ServerSettings.Port,
EnableTls = ServerSettings.X509Certificate2 != null
});
await CreatePath($"{Root}/{ZooKeeperRegisterServiceConfiguration.Name}/{ZooKeeperRegisterServiceConfiguration.Id}", data);
return true;
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
throw;
}
}
19
View Source File : BaseDapper.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private IDbConnection CreateConnection(string connectionName)
{
var connString = ConnectionStringProvider.GetConnectionString(connectionName, EnableMasterSlave, ReadOnly);
if (string.IsNullOrWhiteSpace(connString))
throw new ArgumentNullException(nameof(connString), "The config of " + connectionName + " cannot be null.");
var conn = new TDbConnection();
if (conn == null)
throw new ArgumentNullException(nameof(IDbConnection), "Failed to create database connection.");
conn.ConnectionString = connString;
conn.Open();
return DbMiniProfiler == null ? conn : DbMiniProfiler.CreateConnection(conn);
}
19
View Source File : ICachingKeyGenerator.Default.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public string GenerateKeyPlaceholder(string keyPrefix, int globalExpire, string route, MethodInfo methodInfo, CachingAttribute cachingAttribute = default)
{
var sb = new StringBuilder();
if (!string.IsNullOrWhiteSpace(keyPrefix))
sb.AppendFormat("{0}{1}", keyPrefix, LinkString);
if (cachingAttribute == null || string.IsNullOrWhiteSpace(cachingAttribute.Key))
{
sb.AppendFormat("{0}", route);
if (methodInfo.GetParameters().Length > 0)
sb.Append(LinkString + "{0}");
}
else
sb.Append(cachingAttribute.Key);
return sb.ToString();
}
19
View Source File : CommonMethods.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
internal static ConsulClientConfigure ReadConsulClientConfigure(IConfigurationSection configurationSection)
{
var client = new ConsulClientConfigure();
if (configurationSection.Exists())
{
var addressSection = configurationSection.GetSection("address");
if (addressSection.Exists())
client.Address = new Uri(addressSection.Value);
var tokenSection = configurationSection.GetSection("token");
if (tokenSection.Exists())
client.Token = tokenSection.Value;
var dcSection = configurationSection.GetSection("datacenter");
if (dcSection.Exists())
client.Datacenter = dcSection.Value;
client.WaitTime = string.IsNullOrWhiteSpace(configurationSection.GetValue<string>("timeout"))
? default
: TimeSpan.FromSeconds(configurationSection.GetValue<int>("timeout"));
}
return client;
}
19
View Source File : ServiceFactory.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public void Create(string route, MethodInfo serverMethodInfo, MethodInfo clientMethodInfo, List<Type> serverInterceptors, List<Type> clientInterceptors)
{
if (ServiceInvokers.ContainsKey(route))
throw new DuplicateRouteException(route);
var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
ServiceCircuitBreakerOptions breaker = null;
CachingConfig cachingConfig = null;
if (enableClient)
{
#region Circuit breaker
var nonCircuitBreakerAttr = clientMethodInfo.GetCustomAttribute<NonCircuitBreakerAttribute>();
if (nonCircuitBreakerAttr == null)
{
var circuitBreakerAttr = clientMethodInfo.GetCustomAttribute<CircuitBreakerAttribute>();
var globalCircuitBreaker = UraganoSettings.CircuitBreakerOptions;
if (globalCircuitBreaker != null || circuitBreakerAttr != null)
{
breaker = new ServiceCircuitBreakerOptions();
if (globalCircuitBreaker != null)
{
breaker.Timeout = globalCircuitBreaker.Timeout;
breaker.Retry = globalCircuitBreaker.Retry;
breaker.ExceptionsAllowedBeforeBreaking =
globalCircuitBreaker.ExceptionsAllowedBeforeBreaking;
breaker.DurationOfBreak = globalCircuitBreaker.DurationOfBreak;
breaker.MaxParallelization = globalCircuitBreaker.MaxParallelization;
breaker.MaxQueuingActions = globalCircuitBreaker.MaxQueuingActions;
}
if (circuitBreakerAttr != null)
{
if (circuitBreakerAttr.TimeoutMilliseconds > -1)
breaker.Timeout = TimeSpan.FromMilliseconds(circuitBreakerAttr.TimeoutMilliseconds);
if (circuitBreakerAttr.Retry > -1)
breaker.Retry = circuitBreakerAttr.Retry;
if (circuitBreakerAttr.ExceptionsAllowedBeforeBreaking > -1)
breaker.ExceptionsAllowedBeforeBreaking =
circuitBreakerAttr.ExceptionsAllowedBeforeBreaking;
if (circuitBreakerAttr.DurationOfBreakSeconds > -1)
breaker.DurationOfBreak = TimeSpan.FromSeconds(circuitBreakerAttr.DurationOfBreakSeconds);
if (!string.IsNullOrWhiteSpace(circuitBreakerAttr.FallbackExecuteScript))
{
breaker.HasInjection = true;
ScriptInjection.AddScript(route, circuitBreakerAttr.FallbackExecuteScript,
circuitBreakerAttr.ScriptUsingNameSpaces);
}
if (circuitBreakerAttr.MaxParallelization > -1)
breaker.MaxParallelization = circuitBreakerAttr.MaxParallelization;
if (circuitBreakerAttr.MaxQueuingActions > -1)
breaker.MaxQueuingActions = circuitBreakerAttr.MaxQueuingActions;
}
}
}
#endregion
#region Caching
//Must have a method of returning a value.
if (UraganoSettings.CachingOptions != null && clientMethodInfo.ReturnType != typeof(Task) && clientMethodInfo.GetCustomAttribute<NonCachingAttribute>() == null && clientMethodInfo.DeclaringType?.GetCustomAttribute<NonCachingAttribute>() == null)
{
var attr = clientMethodInfo.GetCustomAttribute<CachingAttribute>();
var keyGenerator = ServiceProvider.GetRequiredService<ICachingKeyGenerator>();
var key = keyGenerator.GenerateKeyPlaceholder(UraganoSettings.CachingOptions.KeyPrefix, UraganoSettings.CachingOptions.ExpireSeconds, route, clientMethodInfo, attr);
cachingConfig = new CachingConfig(key, attr != null && !string.IsNullOrWhiteSpace(attr.Key), attr != null && attr.ExpireSeconds != -1 ? attr.ExpireSeconds : UraganoSettings.CachingOptions.ExpireSeconds);
}
#endregion
}
var serviceDescriptor = new ServiceDescriptor(route, serverMethodInfo, clientMethodInfo, serverMethodInfo == null ? null : new MethodInvoker(serverMethodInfo), serverInterceptors, clientInterceptors, breaker, cachingConfig);
ServiceInvokers.TryAdd(route, serviceDescriptor);
}
19
View Source File : UraganoBuilderExtensions.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static void AddExceptionlessLogger(this IUraganoBuilder builder, string apiKey, string serverUrl = "")
{
builder.AddLogger(new ExceptionlessLoggerProvider(ExceptionlessClient.Default));
ExceptionlessClient.Default.Configuration.ApiKey = apiKey;
if (!string.IsNullOrWhiteSpace(serverUrl))
ExceptionlessClient.Default.Configuration.ConfigServerUrl = serverUrl;
}
19
View Source File : LoadBalancing.ConsistentHash.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public async Task<ServiceNodeInfo> GetNextNode(string serviceName, string serviceRoute, IReadOnlyList<object> serviceArgs,
IReadOnlyDictionary<string, string> serviceMeta)
{
var nodes = await ServiceDiscovery.GetServiceNodes(serviceName);
if (!nodes.Any())
throw new NotFoundNodeException(serviceName);
if (nodes.Count == 1)
return nodes.First();
lock (LockObject)
{
if (serviceMeta == null || !serviceMeta.TryGetValue("x-consistent-hash-key", out var key) || string.IsNullOrWhiteSpace(key))
{
throw new ArgumentNullException(nameof(serviceMeta), "Service metadata [x-consistent-hash-key] is null,Please call SetMeta method to preplaced in.");
}
var selectedNode= ServicesInfo.GetOrAdd(serviceName, k =>
{
var consistentHash = new ConsistentHash<ServiceNodeInfo>();
foreach (var node in nodes)
{
consistentHash.AddNode(node, node.ServiceId);
}
ServicesInfo.TryAdd(serviceName, consistentHash);
return consistentHash;
}).GetNodeForKey(key);
if(Logger.IsEnabled( LogLevel.Trace))
Logger.LogTrace($"Load to node {selectedNode.ServiceId}.");
return selectedNode;
}
}
19
View Source File : ZooKeeperServiceDiscovery.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private async Task CreatePath(string path, byte[] data)
{
path = path.Trim('/');
if (string.IsNullOrWhiteSpace(path))
return;
var children = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var nodePath = new StringBuilder();
for (var i = 0; i < children.Length; i++)
{
nodePath.Append("/" + children[i]);
if (await ZooKeeper.existsAsync(nodePath.ToString()) == null)
{
await ZooKeeper.createAsync(nodePath.ToString(), i == children.Length - 1 ? data : null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
}
}
19
View Source File : TransformationManager.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios
License : GNU General Public License v3.0
Project Creator : 1330-Studios
internal void Add(Transformation transformation) {
if (string.IsNullOrWhiteSpace(transformation.Name))
throw new ArgumentNullException(nameof(transformation.Name));
TransformationList.Add(transformation);
MelonDebug.Msg($"Added transformation to tower with ID {transformation.TowerID} named {transformation.Name}");
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public static bool IsNull(this string s)
{
return string.IsNullOrWhiteSpace(s);
}
See More Examples