Here are the examples of the csharp api System.Text.StringBuilder.Append(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
30015 Examples
19
View Source File : BitfieldMessage.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
public override string ToString()
{
StringBuilder sb;
sb = new StringBuilder();
for (int i = 0; i < this.BitField.Length; i++)
{
sb.Append(this.BitField[i] ? "1" : "0");
}
return "BitfieldMessage: Bitfield = " + sb.ToString();
}
19
View Source File : CancelMessage.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
public override string ToString()
{
StringBuilder sb;
sb = new System.Text.StringBuilder();
sb.Append("CancelMessage: ");
sb.Append($"PieceIndex = {this.PieceIndex}, ");
sb.Append($"BlockOffset = {this.BlockOffset}, ");
sb.Append($"BlockLength = {this.BlockLength}");
return sb.ToString();
}
19
View Source File : HandshakeMessage.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
public override string ToString()
{
StringBuilder sb;
sb = new System.Text.StringBuilder();
sb.Append("HandshakeMessage: ");
sb.Append($"PeerID = {this.PeerId}, ");
sb.Append($"InfoHash = {this.InfoHash}, ");
sb.Append($"FastPeer = {this.SupportsFastPeer}, ");
sb.Append($"ExtendedMessaging = {this.SupportsExtendedMessaging}");
return sb.ToString();
}
19
View Source File : HaveMessage.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
public override string ToString()
{
StringBuilder sb;
sb = new StringBuilder();
sb.Append("HaveMessage: ");
sb.Append($"Index = {this.pieceIndex}");
return sb.ToString();
}
19
View Source File : AliyunSDKUtils.cs
License : MIT License
Project Creator : aliyunmq
License : MIT License
Project Creator : aliyunmq
public static string DictToString(IDictionary<string, string> dict)
{
if (dict == null || dict.Count == 0)
{
return string.Empty;
}
StringBuilder data = new StringBuilder(64);
foreach(string key in dict.Keys)
{
string value = dict[key];
CheckPropValid(key, value);
data.Append(key).Append(":").Append(value).Append("|");
}
return data.ToString();
}
19
View Source File : RequestMessage.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
public override string ToString()
{
StringBuilder sb;
sb = new System.Text.StringBuilder();
sb.Append("RequestMessage: ");
sb.Append($"PieceIndex = {this.PieceIndex}, ");
sb.Append($"BlockOffset = {this.BlockOffset}, ");
sb.Append($"BlockLength = {this.BlockLength}");
return sb.ToString();
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
public static void FillPropertyDictionary(
this WorkItem workItem,
Dictionary<string, object> dictionary,
String prefix,
Boolean skipHtmlFields)
{
Log.Logger.Debug("Filling dictionary information for work item {id}", workItem.Id);
var tempDictionary = new Dictionary<String, Object>();
tempDictionary["replacedle"] = workItem.replacedle;
tempDictionary["id"] = workItem.Id;
//Some help to avoid forcing the user to use System.replacedignedTo etc for most commonly used fields.
if (skipHtmlFields)
{
tempDictionary["description"] = GetTxtFromHtmlContent(workItem.Description);
}
else
{
tempDictionary["description"] = new HtmlSubsreplacedution(workItem.GenerateHtmlForWordEmbedding(workItem.Description, Registry.Options.NormalizeFontInDescription));
}
tempDictionary["description.txt"] = GetTxtFromHtmlContent(workItem.Description);
tempDictionary["replacedignedto"] = workItem.Fields["System.replacedignedTo"].Value?.ToString() ?? String.Empty;
tempDictionary["createdby"] = workItem.Fields["System.CreatedBy"].Value?.ToString() ?? String.Empty;
HashSet<String> specialFields = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"description",
};
//All the fields will be set in raw format.
foreach (Field field in workItem.Fields)
{
if (specialFields.Contains(field.Name))
continue; //This is a special field, ignore.
tempDictionary[field.Name] = tempDictionary[field.ReferenceName] = GetValue(field);
}
var comments = ConnectionManager.Instance
.WorkItemTrackingHttpClient
.GetCommentsAsync(workItem.Id).Result;
if (comments.Count > 0)
{
StringBuilder htmlComment = new StringBuilder();
foreach (var comment in comments.Comments)
{
htmlComment.Append($"<b>Author:</b>{comment.RevisedBy.Name} in date {comment.RevisedDate.ToString("yyyy/MM/dd hh:mm")}");
htmlComment.Append("<br>");
htmlComment.Append(comment.Text);
}
if (skipHtmlFields)
{
tempDictionary["comments"] = GetTxtFromHtmlContent(htmlComment.ToString());
}
else
{
var commentsInHtml = workItem.GenerateHtmlForWordEmbedding(htmlComment.ToString(), Registry.Options.NormalizeFontInDescription);
tempDictionary["comments"] = new HtmlSubsreplacedution(commentsInHtml);
}
}
else
{
tempDictionary["comments"] = "";
}
//ok some of the historical value could be of interests, as an example the last user timestamp for each state change
//is an information that can be interesting
if (workItem.Revisions.Count > 0)
{
foreach (Revision revision in workItem.Revisions)
{
var fieldsChanged = revision
.Fields
.OfType<Field>()
.Where(f => f.IsChangedInRevision)
.ToList();
var changedBy = revision.Fields["Changed By"].Value;
var changedDate = revision.Fields["Changed Date"].Value;
foreach (var field in fieldsChanged)
{
if (field.ReferenceName.Equals("system.state", StringComparison.OrdinalIgnoreCase))
{
tempDictionary[$"statechange.{field.Value.ToString().ToLower()}.author"] = changedBy;
tempDictionary[$"statechange.{field.Value.ToString().ToLower()}.date"] = ((DateTime)changedDate).ToShortDateString();
}
else if (field.ReferenceName.Equals("system.areapath", StringComparison.OrdinalIgnoreCase))
{
tempDictionary["lastareapathchange.author"] = changedBy;
tempDictionary["lastareapathchange.date"] = ((DateTime)changedDate).ToShortDateString();
}
}
}
}
foreach (var element in tempDictionary)
{
dictionary[$"{prefix}{element.Key}"] = element.Value;
}
}
19
View Source File : MainViewModel.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
private void InnerExecuteExport()
{
var baseFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents);
foreach (var selectedTemplate in Templates.Where(t => t.IsSelected))
{
if (selectedTemplate.IsScriptTemplate)
{
if (ArrayParameters.Any())
{
var arrayParameters = ArrayParameters.Select(p => new
{
Name = p.Name,
Values = p.Value?.Split(',', ';').ToList() ?? new List<string>()
})
.ToList();
Int32 maxParameterCount = arrayParameters.Max(p => p.Values.Count);
for (int i = 0; i < maxParameterCount; i++)
{
StringBuilder fileSuffix = new StringBuilder();
Dictionary<string, object> parameters = PrepareUserParameters();
foreach (var arrayParameter in arrayParameters)
{
var value = arrayParameter.Values.Count > i ? arrayParameter.Values[i] : String.Empty;
parameters[arrayParameter.Name] = value;
fileSuffix.Append(arrayParameter.Name);
fileSuffix.Append("_");
fileSuffix.Append(value);
}
var fileName = Path.Combine(baseFolder, selectedTemplate.TemplateName + "_" + DateTime.Now.ToString("dd_MM_yyyy hh mm")) + "_" + fileSuffix.ToString();
GenerateFileFromScriptTemplate(fileName, selectedTemplate, parameters);
}
}
else
{
var fileName = Path.Combine(baseFolder, selectedTemplate.TemplateName + "_" + DateTime.Now.ToString("dd_MM_yyyy hh mm"));
Dictionary<string, object> parameters = PrepareUserParameters();
GenerateFileFromScriptTemplate(fileName, selectedTemplate, parameters);
}
}
else
{
var fileName = Path.Combine(baseFolder, selectedTemplate.TemplateName + "_" + DateTime.Now.ToString("dd_MM_yyyy hh mm")) + ".docx";
var selected = SelectedQuery?.Results?.Where(q => q.Selected).ToList();
if (selected == null || selected.Count == 0)
{
return;
}
var template = selectedTemplate.WordTemplateFolderManager;
using (WordManipulator manipulator = new WordManipulator(fileName, true))
{
foreach (var workItemResult in selected)
{
var workItem = workItemResult.WorkItem;
manipulator.InsertWorkItem(workItem, template.GetTemplateFor(workItem.Type.Name), true);
}
}
ManageGeneratedWordFile(fileName);
}
}
Status = $"Export Completed";
}
19
View Source File : MessagePackSerializer.Json.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
private static void ToJsonCore(ref MessagePackReader reader, TextWriter writer, MessagePackSerializerOptions options)
{
MessagePackType type = reader.NextMessagePackType;
switch (type)
{
case MessagePackType.Integer:
if (MessagePackCode.IsSignedInteger(reader.NextCode))
{
writer.Write(reader.ReadInt64().ToString(CultureInfo.InvariantCulture));
}
else
{
writer.Write(reader.ReadUInt64().ToString(CultureInfo.InvariantCulture));
}
break;
case MessagePackType.Boolean:
writer.Write(reader.ReadBoolean() ? "true" : "false");
break;
case MessagePackType.Float:
if (reader.NextCode == MessagePackCode.Float32)
{
writer.Write(reader.ReadSingle().ToString(CultureInfo.InvariantCulture));
}
else
{
writer.Write(reader.ReadDouble().ToString(CultureInfo.InvariantCulture));
}
break;
case MessagePackType.String:
WriteJsonString(reader.ReadString(), writer);
break;
case MessagePackType.Binary:
ArraySegment<byte> segment = ByteArraySegmentFormatter.Instance.Deserialize(ref reader, DefaultOptions);
writer.Write("\"" + Convert.ToBase64String(segment.Array, segment.Offset, segment.Count) + "\"");
break;
case MessagePackType.Array:
{
int length = reader.ReadArrayHeader();
options.Security.DepthStep(ref reader);
try
{
writer.Write("[");
for (int i = 0; i < length; i++)
{
ToJsonCore(ref reader, writer, options);
if (i != length - 1)
{
writer.Write(",");
}
}
writer.Write("]");
}
finally
{
reader.Depth--;
}
return;
}
case MessagePackType.Map:
{
int length = reader.ReadMapHeader();
options.Security.DepthStep(ref reader);
try
{
writer.Write("{");
for (int i = 0; i < length; i++)
{
// write key
{
MessagePackType keyType = reader.NextMessagePackType;
if (keyType == MessagePackType.String || keyType == MessagePackType.Binary)
{
ToJsonCore(ref reader, writer, options);
}
else
{
writer.Write("\"");
ToJsonCore(ref reader, writer, options);
writer.Write("\"");
}
}
writer.Write(":");
// write body
{
ToJsonCore(ref reader, writer, options);
}
if (i != length - 1)
{
writer.Write(",");
}
}
writer.Write("}");
}
finally
{
reader.Depth--;
}
return;
}
case MessagePackType.Extension:
ExtensionHeader extHeader = reader.ReadExtensionFormatHeader();
if (extHeader.TypeCode == ReservedMessagePackExtensionTypeCode.DateTime)
{
DateTime dt = reader.ReadDateTime(extHeader);
writer.Write("\"");
writer.Write(dt.ToString("o", CultureInfo.InvariantCulture));
writer.Write("\"");
}
#if !UNITY_2018_3_OR_NEWER
else if (extHeader.TypeCode == ThisLibraryExtensionTypeCodes.TypelessFormatter)
{
// prepare type name token
var privateBuilder = new StringBuilder();
var typeNameTokenBuilder = new StringBuilder();
SequencePosition positionBeforeTypeNameRead = reader.Position;
ToJsonCore(ref reader, new StringWriter(typeNameTokenBuilder), options);
int typeNameReadSize = (int)reader.Sequence.Slice(positionBeforeTypeNameRead, reader.Position).Length;
if (extHeader.Length > typeNameReadSize)
{
// object map or array
MessagePackType typeInside = reader.NextMessagePackType;
if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map)
{
privateBuilder.Append("{");
}
ToJsonCore(ref reader, new StringWriter(privateBuilder), options);
// insert type name token to start of object map or array
if (typeInside != MessagePackType.Array)
{
typeNameTokenBuilder.Insert(0, "\"$type\":");
}
if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map)
{
privateBuilder.Append("}");
}
if (privateBuilder.Length > 2)
{
typeNameTokenBuilder.Append(",");
}
privateBuilder.Insert(1, typeNameTokenBuilder.ToString());
writer.Write(privateBuilder.ToString());
}
else
{
writer.Write("{\"$type\":\"" + typeNameTokenBuilder.ToString() + "}");
}
}
#endif
else
{
var data = reader.ReadRaw((long)extHeader.Length);
writer.Write("[");
writer.Write(extHeader.TypeCode);
writer.Write(",");
writer.Write("\"");
writer.Write(Convert.ToBase64String(data.ToArray()));
writer.Write("\"");
writer.Write("]");
}
break;
case MessagePackType.Nil:
reader.Skip();
writer.Write("null");
break;
default:
throw new MessagePackSerializationException($"code is invalid. code: {reader.NextCode} format: {MessagePackCode.ToFormatName(reader.NextCode)}");
}
}
19
View Source File : AutomataDictionary.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
private static void ToStringCore(IEnumerable<AutomataNode> nexts, StringBuilder sb, int depth)
{
foreach (AutomataNode item in nexts)
{
if (depth != 0)
{
sb.Append(' ', depth * 2);
}
sb.Append("[" + item.Key + "]");
if (item.Value != -1)
{
sb.Append("(" + item.OriginalKey + ")");
sb.Append(" = ");
sb.Append(item.Value);
}
sb.AppendLine();
ToStringCore(item.YieldChildren(), sb, depth + 1);
}
}
19
View Source File : ImageSynthesis.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
public string MD5Hash(string input) {
byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input));
// Create string representation
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < data.Length; ++i) {
sb.Append(data[i].ToString("x2"));
}
return sb.ToString();
}
19
View Source File : JoystickState.cs
License : MIT License
Project Creator : allenwp
License : MIT License
Project Creator : allenwp
public override string ToString()
{
var ret = new StringBuilder(54 - 2 + Axes.Length * 7 + Buttons.Length + Hats.Length * 5);
ret.Append("[JoystickState: IsConnected=" + (IsConnected ? 1 : 0));
if (IsConnected)
{
ret.Append(", Axes=");
foreach (var axis in Axes)
ret.Append((axis > 0 ? "+" : "") + axis.ToString("00000") + " ");
ret.Length--;
ret.Append(", Buttons=");
foreach (var button in Buttons)
ret.Append((int)button);
ret.Append(", Hats=");
foreach (var hat in Hats)
ret.Append(hat + " ");
ret.Length--;
}
ret.Append("]");
return ret.ToString();
}
19
View Source File : EditorUI.cs
License : MIT License
Project Creator : allenwp
License : MIT License
Project Creator : allenwp
private static unsafe void SubmitInvokeWindow()
{
ImGui.Begin("Invoke");
if (ImGui.BeginTabBar("replacedemblies Tab Bar", ImGuiTabBarFlags.None))
{
if (ImGui.BeginTabItem("Selected Object"))
{
ImGui.InputText("Filter", ref invokeFilter, 500);
invokeFilter = invokeFilter.ToLower();
bool doInvoke = ImGui.Button("Invoke");
ImGui.Separator();
ImGui.BeginChild("scrolling", Vector2.Zero, false, ImGuiWindowFlags.HorizontalScrollbar);
// TODO: for selected object, do similar to the other replacedemblies
ImGui.Text("(Selected Ojbect not yet implemented. Implement when needed.)");
ImGui.EndChild();
ImGui.EndTabItem();
}
foreach (var replacedemblyPair in replacedemblies)
{
if (ImGui.BeginTabItem(replacedemblyPair.Key))
{
ImGui.InputText("Filter", ref invokeFilter, 500);
invokeFilter = invokeFilter.ToLower();
bool doInvoke = ImGui.Button("Invoke"); // TODO: allow input of parameters.
ImGui.Separator();
ImGui.BeginChild("scrolling", Vector2.Zero, false, ImGuiWindowFlags.HorizontalScrollbar);
var names = (from type in replacedemblyPair.Value.GetTypes()
from method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
select (Type: type, Method: method, DisplayName: type.FullName + ":" + method.Name)).Where(a => a.Method.GetParameters().Length < 1).ToList();
for (int i = 0; i < names.Count; i++)
{
if (names[i].DisplayName.ToLower().Contains(invokeFilter))
{
if (names[i].Method.IsPrivate)
{
ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.5f, 0.5f, 0.5f, 1f));
}
StringBuilder sb = new StringBuilder();
sb.Append('(');
foreach (var param in names[i].Method.GetParameters())
{
sb.Append(param.ParameterType.Name);
sb.Append(' ');
sb.Append(param.Name);
}
sb.Append(')');
var text = $"{names[i].DisplayName}{sb}";
if (ImGui.Selectable(text, invokeSelectedIndex == i))
{
invokeSelectedIndex = i;
}
if (names[i].Method.IsPrivate)
{
ImGui.PopStyleColor();
}
}
}
if (doInvoke && names.Count > invokeSelectedIndex)
{
try
{
names[invokeSelectedIndex].Method.Invoke(null, null);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
ImGui.EndChild();
ImGui.EndTabItem();
}
}
ImGui.EndTabBar();
}
ImGui.End();
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
public static string JoinTo(this string value, params string[] others)
{
var builder = new StringBuilder(value);
foreach (var v in others)
{
builder.Append(v);
}
return builder.ToString();
}
19
View Source File : MemoryEditor.cs
License : MIT License
Project Creator : allenwp
License : MIT License
Project Creator : allenwp
public unsafe void Draw(string replacedle, byte[] mem_data, int mem_size, int base_display_addr = 0)
{
ImGui.SetNextWindowSize(new Vector2(500, 350), ImGuiCond.FirstUseEver);
if (!ImGui.Begin(replacedle))
{
ImGui.End();
return;
}
float line_height = ImGuiNative.igGetTextLineHeight();
int line_total_count = (mem_size + Rows - 1) / Rows;
ImGuiNative.igSetNextWindowContentSize(new Vector2(0.0f, line_total_count * line_height));
ImGui.BeginChild("##scrolling", new Vector2(0, -ImGuiNative.igGetFrameHeightWithSpacing()), false, 0);
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(0, 0));
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
int addr_digits_count = 0;
for (int n = base_display_addr + mem_size - 1; n > 0; n >>= 4)
addr_digits_count++;
float glyph_width = ImGui.CalcTextSize("F").X;
float cell_width = glyph_width * 3; // "FF " we include trailing space in the width to easily catch clicks everywhere
var clipper = new ImGuiListClipper2(line_total_count, line_height);
int visible_start_addr = clipper.DisplayStart * Rows;
int visible_end_addr = clipper.DisplayEnd * Rows;
bool data_next = false;
if (!AllowEdits || DataEditingAddr >= mem_size)
DataEditingAddr = -1;
int data_editing_addr_backup = DataEditingAddr;
if (DataEditingAddr != -1)
{
if (ImGui.IsKeyPressed(ImGui.GetKeyIndex(ImGuiKey.UpArrow)) && DataEditingAddr >= Rows) { DataEditingAddr -= Rows; DataEditingTakeFocus = true; }
else if (ImGui.IsKeyPressed(ImGui.GetKeyIndex(ImGuiKey.DownArrow)) && DataEditingAddr < mem_size - Rows) { DataEditingAddr += Rows; DataEditingTakeFocus = true; }
else if (ImGui.IsKeyPressed(ImGui.GetKeyIndex(ImGuiKey.LeftArrow)) && DataEditingAddr > 0) { DataEditingAddr -= 1; DataEditingTakeFocus = true; }
else if (ImGui.IsKeyPressed(ImGui.GetKeyIndex(ImGuiKey.RightArrow)) && DataEditingAddr < mem_size - 1) { DataEditingAddr += 1; DataEditingTakeFocus = true; }
}
if ((DataEditingAddr / Rows) != (data_editing_addr_backup / Rows))
{
// Track cursor movements
float scroll_offset = ((DataEditingAddr / Rows) - (data_editing_addr_backup / Rows)) * line_height;
bool scroll_desired = (scroll_offset < 0.0f && DataEditingAddr < visible_start_addr + Rows * 2) || (scroll_offset > 0.0f && DataEditingAddr > visible_end_addr - Rows * 2);
if (scroll_desired)
ImGuiNative.igSetScrollY(ImGuiNative.igGetScrollY() + scroll_offset);
}
for (int line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible items
{
int addr = line_i * Rows;
ImGui.Text(FixedHex(base_display_addr + addr, addr_digits_count) + ": ");
ImGui.SameLine();
// Draw Hexadecimal
float line_start_x = ImGuiNative.igGetCursorPosX();
for (int n = 0; n < Rows && addr < mem_size; n++, addr++)
{
ImGui.SameLine(line_start_x + cell_width * n);
if (DataEditingAddr == addr)
{
// Display text input on current byte
ImGui.PushID(addr);
// FIXME: We should have a way to retrieve the text edit cursor position more easily in the API, this is rather tedious.
ImGuiInputTextCallback callback = (data) =>
{
int* p_cursor_pos = (int*)data->UserData;
if (ImGuiNative.ImGuiInputTextCallbackData_Hreplacedelection(data) == 0)
*p_cursor_pos = data->CursorPos;
return 0;
};
int cursor_pos = -1;
bool data_write = false;
if (DataEditingTakeFocus)
{
ImGui.SetKeyboardFocusHere();
ReplaceChars(DataInput, FixedHex(mem_data[addr], 2));
ReplaceChars(AddrInput, FixedHex(base_display_addr + addr, addr_digits_count));
}
ImGui.PureplacedemWidth(ImGui.CalcTextSize("FF").X);
var flags = ImGuiInputTextFlags.CharsHexadecimal | ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.NoHorizontalScroll | ImGuiInputTextFlags.AlwaysInsertMode | ImGuiInputTextFlags.CallbackAlways;
if (ImGui.InputText("##data", DataInput, 32, flags, callback, (IntPtr)(&cursor_pos)))
data_write = data_next = true;
else if (!DataEditingTakeFocus && !ImGui.IsItemActive())
DataEditingAddr = -1;
DataEditingTakeFocus = false;
ImGui.PopItemWidth();
if (cursor_pos >= 2)
data_write = data_next = true;
if (data_write)
{
int data;
if (TryHexParse(DataInput, out data))
mem_data[addr] = (byte)data;
}
ImGui.PopID();
}
else
{
ImGui.Text(FixedHex(mem_data[addr], 2));
if (AllowEdits && ImGui.IsItemHovered() && ImGui.IsMouseClicked(0))
{
DataEditingTakeFocus = true;
DataEditingAddr = addr;
}
}
}
ImGui.SameLine(line_start_x + cell_width * Rows + glyph_width * 2);
//separator line drawing replaced by printing a pipe char
// Draw ASCII values
addr = line_i * Rows;
var asciiVal = new System.Text.StringBuilder(2 + Rows);
asciiVal.Append("| ");
for (int n = 0; n < Rows && addr < mem_size; n++, addr++)
{
int c = mem_data[addr];
asciiVal.Append((c >= 32 && c < 128) ? Convert.ToChar(c) : '.');
}
ImGui.TextUnformatted(asciiVal.ToString()); //use unformatted, so string can contain the '%' character
}
//clipper.End(); //not implemented
ImGui.PopStyleVar(2);
ImGui.EndChild();
if (data_next && DataEditingAddr < mem_size)
{
DataEditingAddr = DataEditingAddr + 1;
DataEditingTakeFocus = true;
}
ImGui.Separator();
ImGuiNative.igAlignTextToFramePadding();
ImGui.PureplacedemWidth(50);
ImGui.PushAllowKeyboardFocus(true);
int rows_backup = Rows;
if (ImGui.DragInt("##rows", ref Rows, 0.2f, 4, 32, "%.0f rows"))
{
if (Rows <= 0) Rows = 4;
Vector2 new_window_size = ImGui.GetWindowSize();
new_window_size.X += (Rows - rows_backup) * (cell_width + glyph_width);
ImGui.SetWindowSize(new_window_size);
}
ImGui.PopAllowKeyboardFocus();
ImGui.PopItemWidth();
ImGui.SameLine();
ImGui.Text(string.Format(" Range {0}..{1} ", FixedHex(base_display_addr, addr_digits_count),
FixedHex(base_display_addr + mem_size - 1, addr_digits_count)));
ImGui.SameLine();
ImGui.PureplacedemWidth(70);
if (ImGui.InputText("##addr", AddrInput, 32, ImGuiInputTextFlags.CharsHexadecimal | ImGuiInputTextFlags.EnterReturnsTrue, null))
{
int goto_addr;
if (TryHexParse(AddrInput, out goto_addr))
{
goto_addr -= base_display_addr;
if (goto_addr >= 0 && goto_addr < mem_size)
{
ImGui.BeginChild("##scrolling");
ImGui.SetScrollFromPosY(ImGui.GetCursorStartPos().Y + (goto_addr / Rows) * ImGuiNative.igGetTextLineHeight());
ImGui.EndChild();
DataEditingAddr = goto_addr;
DataEditingTakeFocus = true;
}
}
}
ImGui.PopItemWidth();
ImGui.End();
}
19
View Source File : SceneGraph2.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
private string OnRender()
{
// Spinning ticker that shows activity, lets us know if application hangs or freezes.
var tui = new StringBuilder();
//tui.Append($"[ {SimUnit.TickPhase} ] - ");
// Keeps track of active Windows name and active Windows current state name for debugging purposes.
tui.Append(_simUnit.WindowManager.FocusedWindow?.CurrentForm != null
? $"Window[{_simUnit.WindowManager.Count}]: {_simUnit.WindowManager.FocusedWindow}[{_simUnit.WindowManager.FocusedWindow.CurrentForm}] : "
: $"Window[{_simUnit.WindowManager.Count}]: {_simUnit.WindowManager.FocusedWindow}() : ");
// Allows the implementing simulation to control text before window is rendered out.
tui.Append(SimUnit.OnPreRender());
// Prints game Windows specific text and options. This typically is menus from commands, or states showing some information.
tui.Append($"{RenderWindow()}{Environment.NewLine}");
// Determines if the user is allowed to see their input from buffer as they type it, or is it stored until they press enter.
if (SimUnit.WindowManager.AcceptingInput)
tui.Append(SimUnit.WindowManager.FocusedWindow != null
? $"{SimUnit.WindowManager.FocusedWindow.PromptText} {SimUnit.InputManager.InputBuffer}"
: $"{PROMPT_TEXT_DEFAULT} {SimUnit.InputManager.InputBuffer}");
// Outputs the result of the string builder to TUI builder above.
return tui.ToString();
}
19
View Source File : DdbExpressionVisitor.cs
License : MIT License
Project Creator : AllocZero
License : MIT License
Project Creator : AllocZero
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression is ConstantExpression constantExpression && node.Member is FieldInfo fieldInfo)
{
var value = fieldInfo.GetValue(constantExpression.Value);
_builder.Append(value);
return node;
}
if (node.Expression!.NodeType != ExpressionType.Parameter)
Visit(node.Expression);
if (_builder.Length > 0)
_builder.Append('.');
_builder.Append("#f");
_builder.Append(_cachedAttributeNames!.Count);
if (!ClreplacedInfo.PropertiesMap.TryGetValue(node.Member.Name, out var ddbPropertyInfo))
throw new DdbException(
$"Property {node.Member.Name} does not exist in enreplacedy {ClreplacedInfo.Type.Name} or it's not marked by {nameof(DynamoDbPropertyAttribute)} attribute");
_cachedAttributeNames.Add(ddbPropertyInfo.AttributeName);
ClreplacedInfo = ddbPropertyInfo.RuntimeClreplacedInfo;
return node;
}
19
View Source File : ByteArrayFormattingExtensions.cs
License : MIT License
Project Creator : AllocZero
License : MIT License
Project Creator : AllocZero
public static string ToHex(this byte[] array, bool lowercase)
{
var stringBuilder = new StringBuilder(array.Length * 2);
foreach (var item in array)
stringBuilder.Append(item.ToString(lowercase ? "x2" : "X2", CultureInfo.InvariantCulture));
return stringBuilder.ToString();
}
19
View Source File : DumpCreator.cs
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx
private string GetProcDumpArgs(string[] procdumpArgs)
{
StringBuilder sb = new StringBuilder();
foreach(var arg in procdumpArgs)
{
if( arg.Contains(' '))
{
sb.Append($"\"{arg}\" ");
}
else
{
sb.Append(arg);
sb.Append(' ');
}
}
return sb.ToString();
}
19
View Source File : RowPrinter.cs
License : GNU General Public License v3.0
Project Creator : Alois-xx
License : GNU General Public License v3.0
Project Creator : Alois-xx
public static string Print(params string[] strings)
{
StringBuilder sb = new StringBuilder();
for(int i=0;i<strings.Length;i++)
{
// prevent multiline rows and replace any column separators with #
sb.Append(strings[i]?.Trim(myTrimChars).Replace('|','#'));
if( i != strings.Length-1)
{
sb.Append("|");
}
}
string msg = sb.ToString();
Console.WriteLine(msg);
return msg;
}
19
View Source File : UrlEncoder.cs
License : MIT License
Project Creator : AllocZero
License : MIT License
Project Creator : AllocZero
public static string Encode(int rfcNumber, string data, bool path)
{
var stringBuilder = new StringBuilder(data.Length * 2);
if (!RfcEncodingSchemes.TryGetValue(rfcNumber, out var str1))
str1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
string str2 = str1 + (path ? ValidPathCharacters : "");
foreach (var b in Encoding.UTF8.GetBytes(data))
{
var ch = (char) b;
if (str2.IndexOf(ch) != -1)
stringBuilder.Append(ch);
else
// ReSharper disable once UseFormatSpecifierInInterpolation to avoid boxing
stringBuilder.Append($"%{((int) ch).ToString("X2", CultureInfo.InvariantCulture)}");
}
return stringBuilder.ToString();
}
19
View Source File : Row.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public string ToString(string format, int rowIndex)
{
var sb = new StringBuilder();
StringFormat sf = GetStringFormat(format);
if (sf == StringFormat.Csv && rowIndex == 0)
{
//print headers
int i = 0;
foreach (Field f in Schema)
{
if (i++ > 0) sb.Append(",");
sb.Append(f.Name);
}
sb.AppendLine();
}
ToString(sb, sf, 1, Schema);
return sb.ToString();
}
19
View Source File : Schema.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public string GetNotEqualsMessage(Schema other, string thisName, string otherName)
{
if(_fields.Count != other._fields.Count)
{
return $"different number of elements ({_fields.Count} != {other._fields.Count})";
}
var sb = new StringBuilder();
for (int i = 0; i < _fields.Count; i++)
{
if (!_fields[i].Equals(other._fields[i]))
{
if(sb.Length != 0)
{
sb.Append(", ");
}
sb.Append("[");
sb.Append(thisName);
sb.Append(": ");
sb.Append(_fields[i]);
sb.Append("] != [");
sb.Append(otherName);
sb.Append(": ");
sb.Append(other._fields[i]);
sb.Append("]");
}
}
if (sb.Length > 0) return sb.ToString();
return "not sure!";
}
19
View Source File : StringBuilderExtensions.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public static void DivideObjects(this StringBuilder sb, StringFormat sf, int level)
{
if (level > 0)
{
switch (sf)
{
case StringFormat.Csv:
sb.Append(",");
break;
case StringFormat.Json:
sb.Append(",");
break;
default:
sb.Append(", ");
break;
}
}
else
{
sb.AppendLine();
}
}
19
View Source File : DataPageHeader.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("DataPageHeader(");
__sb.Append(", Num_values: ");
__sb.Append(Num_values);
__sb.Append(", Encoding: ");
__sb.Append(Encoding);
__sb.Append(", Definition_level_encoding: ");
__sb.Append(Definition_level_encoding);
__sb.Append(", Repereplacedion_level_encoding: ");
__sb.Append(Repereplacedion_level_encoding);
if (Statistics != null && __isset.statistics) {
__sb.Append(", Statistics: ");
__sb.Append(Statistics== null ? "<null>" : Statistics.ToString());
}
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : IntType.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("IntType(");
__sb.Append(", BitWidth: ");
__sb.Append(BitWidth);
__sb.Append(", IsSigned: ");
__sb.Append(IsSigned);
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : LogicalType.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("LogicalType(");
bool __first = true;
if (STRING != null && __isset.@STRING) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("STRING: ");
__sb.Append(STRING== null ? "<null>" : STRING.ToString());
}
if (MAP != null && __isset.MAP) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("MAP: ");
__sb.Append(MAP== null ? "<null>" : MAP.ToString());
}
if (LIST != null && __isset.LIST) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("LIST: ");
__sb.Append(LIST== null ? "<null>" : LIST.ToString());
}
if (ENUM != null && __isset.@ENUM) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("ENUM: ");
__sb.Append(ENUM== null ? "<null>" : ENUM.ToString());
}
if (DECIMAL != null && __isset.@DECIMAL) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("DECIMAL: ");
__sb.Append(DECIMAL== null ? "<null>" : DECIMAL.ToString());
}
if (DATE != null && __isset.DATE) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("DATE: ");
__sb.Append(DATE== null ? "<null>" : DATE.ToString());
}
if (TIME != null && __isset.TIME) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("TIME: ");
__sb.Append(TIME== null ? "<null>" : TIME.ToString());
}
if (TIMESTAMP != null && __isset.TIMESTAMP) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("TIMESTAMP: ");
__sb.Append(TIMESTAMP== null ? "<null>" : TIMESTAMP.ToString());
}
if (INTEGER != null && __isset.INTEGER) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("INTEGER: ");
__sb.Append(INTEGER== null ? "<null>" : INTEGER.ToString());
}
if (UNKNOWN != null && __isset.UNKNOWN) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("UNKNOWN: ");
__sb.Append(UNKNOWN== null ? "<null>" : UNKNOWN.ToString());
}
if (JSON != null && __isset.JSON) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("JSON: ");
__sb.Append(JSON== null ? "<null>" : JSON.ToString());
}
if (BSON != null && __isset.BSON) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("BSON: ");
__sb.Append(BSON== null ? "<null>" : BSON.ToString());
}
if (UUID != null && __isset.UUID) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("UUID: ");
__sb.Append(UUID== null ? "<null>" : UUID.ToString());
}
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : MapType.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("MapType(");
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : MilliSeconds.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("MilliSeconds(");
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : NanoSeconds.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("NanoSeconds(");
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : NullType.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("NullType(");
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : OffsetIndex.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("OffsetIndex(");
__sb.Append(", Page_locations: ");
__sb.Append(Page_locations);
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : PageEncodingStats.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("PageEncodingStats(");
__sb.Append(", Page_type: ");
__sb.Append(Page_type);
__sb.Append(", Encoding: ");
__sb.Append(Encoding);
__sb.Append(", Count: ");
__sb.Append(Count);
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : PageHeader.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("PageHeader(");
__sb.Append(", Type: ");
__sb.Append(Type);
__sb.Append(", Uncompressed_page_size: ");
__sb.Append(Uncompressed_page_size);
__sb.Append(", Compressed_page_size: ");
__sb.Append(Compressed_page_size);
if (__isset.crc) {
__sb.Append(", Crc: ");
__sb.Append(Crc);
}
if (Data_page_header != null && __isset.data_page_header) {
__sb.Append(", Data_page_header: ");
__sb.Append(Data_page_header== null ? "<null>" : Data_page_header.ToString());
}
if (Index_page_header != null && __isset.index_page_header) {
__sb.Append(", Index_page_header: ");
__sb.Append(Index_page_header== null ? "<null>" : Index_page_header.ToString());
}
if (Dictionary_page_header != null && __isset.dictionary_page_header) {
__sb.Append(", Dictionary_page_header: ");
__sb.Append(Dictionary_page_header== null ? "<null>" : Dictionary_page_header.ToString());
}
if (Data_page_header_v2 != null && __isset.data_page_header_v2) {
__sb.Append(", Data_page_header_v2: ");
__sb.Append(Data_page_header_v2== null ? "<null>" : Data_page_header_v2.ToString());
}
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : PageLocation.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("PageLocation(");
__sb.Append(", Offset: ");
__sb.Append(Offset);
__sb.Append(", Compressed_page_size: ");
__sb.Append(Compressed_page_size);
__sb.Append(", First_row_index: ");
__sb.Append(First_row_index);
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : SchemaElement.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("SchemaElement(");
bool __first = true;
if (__isset.type) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Type: ");
__sb.Append(Type);
}
if (__isset.type_length) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Type_length: ");
__sb.Append(Type_length);
}
if (__isset.repereplacedion_type) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Repereplacedion_type: ");
__sb.Append(Repereplacedion_type);
}
if(!__first) { __sb.Append(", "); }
__sb.Append("Name: ");
__sb.Append(Name);
if (__isset.num_children) {
__sb.Append(", Num_children: ");
__sb.Append(Num_children);
}
if (__isset.converted_type) {
__sb.Append(", Converted_type: ");
__sb.Append(Converted_type);
}
if (__isset.scale) {
__sb.Append(", Scale: ");
__sb.Append(Scale);
}
if (__isset.precision) {
__sb.Append(", Precision: ");
__sb.Append(Precision);
}
if (__isset.field_id) {
__sb.Append(", Field_id: ");
__sb.Append(Field_id);
}
if (LogicalType != null && __isset.logicalType) {
__sb.Append(", LogicalType: ");
__sb.Append(LogicalType== null ? "<null>" : LogicalType.ToString());
}
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : SortingColumn.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("SortingColumn(");
__sb.Append(", Column_idx: ");
__sb.Append(Column_idx);
__sb.Append(", Descending: ");
__sb.Append(Descending);
__sb.Append(", Nulls_first: ");
__sb.Append(Nulls_first);
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : SplitBlockAlgorithm.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString() {
StringBuilder __sb = new StringBuilder("SplitBlockAlgorithm(");
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : Statistics.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public override string ToString()
{
StringBuilder __sb = new StringBuilder("Statistics(");
bool __first = true;
if (Max != null && __isset.max)
{
if (!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Max: ");
__sb.Append(Max);
}
if (Min != null && __isset.min)
{
if (!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Min: ");
__sb.Append(Min);
}
if (__isset.null_count)
{
if (!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Null_count: ");
__sb.Append(Null_count);
}
if (__isset.distinct_count)
{
if (!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Distinct_count: ");
__sb.Append(Distinct_count);
}
if (Max_value != null && __isset.max_value)
{
if (!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Max_value: ");
__sb.Append(Max_value);
}
if (Min_value != null && __isset.min_value)
{
if (!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Min_value: ");
__sb.Append(Min_value);
}
__sb.Append(")");
return __sb.ToString();
}
19
View Source File : AwsS3FileStorage.cs
License : Apache License 2.0
Project Creator : aloneguid
License : Apache License 2.0
Project Creator : aloneguid
private HttpRequestMessage CreateCompleteMultipartUploadRequest(string key, string uploadId, IEnumerable<string> partTags)
{
var request = new HttpRequestMessage(HttpMethod.Post, $"/{key}?uploadId={uploadId}");
var sb = new StringBuilder(@"<?xml version=""1.0"" encoding=""UTF-8""?><CompleteMultipartUpload xmlns=""http://s3.amazonaws.com/doc/2006-03-01/"">");
int partId = 1;
foreach(string eTag in partTags)
{
sb
.Append("<Part><ETag>")
.Append(eTag)
.Append("</ETag><PartNumber>")
.Append(partId++)
.Append("</PartNumber></Part>");
}
sb.Append("</CompleteMultipartUpload>");
request.Content = new StringContent(sb.ToString());
return request;
}
19
View Source File : S3AuthHandler.cs
License : Apache License 2.0
Project Creator : aloneguid
License : Apache License 2.0
Project Creator : aloneguid
private string GetCanonicalHeaders(HttpRequestMessage request, out string signedHeaders)
{
// List of request headers with their values.
// Individual header name and value pairs are separated by the newline character ("\n").
// Header names must be in lowercase. You must sort the header names alphabetically to construct the string.
// Note that I add some headers manually, but preserve sorting order in the actual code.
var headers = from kvp in request.Headers
where kvp.Key.StartsWith("x-amz-", StringComparison.OrdinalIgnoreCase)
orderby kvp.Key
select new { Key = kvp.Key.ToLowerInvariant(), kvp.Value };
var sb = new StringBuilder();
var signedHeadersList = new List<string>();
// The CanonicalHeaders list must include the following:
// - HTTP host header.
// - If the Content-Type header is present in the request, you must add it to the CanonicalHeaders list.
// - Any x-amz-* headers that you plan to include in your request must also be added. For example, if you are using temporary security credentials, you need to include x-amz-security-token in your request. You must add this header in the list of CanonicalHeaders.
string contentType = request.Content?.Headers.ContentType?.ToString();
if(contentType != null)
{
sb.Append("content-type:").Append(contentType).Append("\n");
signedHeadersList.Add("content-type");
}
if(request.Headers.Contains("date"))
{
sb.Append("date:").Append(request.Headers.GetValues("date").First()).Append("\n");
signedHeadersList.Add("date");
}
sb.Append("host:").Append(request.RequestUri.Host).Append("\n");
signedHeadersList.Add("host");
if(request.Headers.Contains("range"))
{
sb.Append("range:").Append(request.Headers.GetValues("range").First()).Append("\n");
signedHeadersList.Add("range");
}
// Create the string in the right format; this is what makes the headers "canonicalized" --
// it means put in a standard format. http://en.wikipedia.org/wiki/Canonicalization
foreach(var kvp in headers)
{
sb.Append(kvp.Key).Append(":");
signedHeadersList.Add(kvp.Key);
foreach(string hv in kvp.Value)
{
sb.Append(hv);
}
sb.Append("\n");
}
signedHeaders = string.Join(";", signedHeadersList);
return sb.ToString();
}
19
View Source File : SharedKeyAuthHandler.cs
License : Apache License 2.0
Project Creator : aloneguid
License : Apache License 2.0
Project Creator : aloneguid
private static string GetCanonicalizedResource(Uri address, string storageAccountName)
{
// The absolute path is "/" because for we're getting a list of containers.
StringBuilder sb = new StringBuilder("/").Append(storageAccountName).Append(address.AbsolutePath);
// Address.Query is the resource, such as "?comp=list".
// This ends up with a NameValueCollection with 1 entry having key=comp, value=list.
// It will have more entries if you have more query parameters.
NameValueCollection values = HttpUtility.ParseQueryString(address.Query);
foreach(string item in values.AllKeys.OrderBy(k => k))
{
string v = values[item];
// v = HttpUtility.UrlEncode(v);
sb.Append('\n').Append(item.ToLower()).Append(':').Append(v);
}
return sb.ToString();
}
19
View Source File : CreateDeviceClientMethod.cs
License : MIT License
Project Creator : alonf
License : MIT License
Project Creator : alonf
private void CreateDeviceClientMethod(string methodName, AttributeSyntax attributeSyntax)
{
AppendLine($"private Microsoft.Azure.Devices.Client.DeviceClient {methodName}()");
using (Block())
{
var parameterNameList = new List<string>();
if (attributeSyntax?.ArgumentList != null)
{
AppendLine();
AppendLine("#pragma warning disable CS4014");
AppendLine();
foreach (var argument in attributeSyntax.ArgumentList.Arguments)
{
var attreplacedignment = $"the{argument.NameEquals}";
parameterNameList.Add(argument.NameEquals?.ToString().TrimEnd('=', ' ', '\t').Trim());
var attExpression = argument.Expression.ToString();
CreateVariablereplacedignmentLineFromAttributeParameter(attreplacedignment, attExpression);
}
AppendLine();
AppendLine("#pragma warning restore CS4014");
AppendLine();
}
else
{
parameterNameList.Add(nameof(DeviceAttribute.ConnectionString));
AppendLine("var theConnectionString=System.Environment.GetEnvironmentVariable(\"ConnectionString\");");
}
var createDeviceError = new StringBuilder();
string clientOptionsPropertyName = GetClientOptionsPropertyName();
var hasTransportSettingsAttributes = HandleTransportSettingsAttributes();
string authenticationMethodPropertyName = GetAuthenticationMethodPropertyName();
var creationFunctionEntry = new StringBuilder();
if (parameterNameList.Contains(nameof(DeviceAttribute.ConnectionString)))
{
createDeviceError.Append("ConnectionString ");
creationFunctionEntry.Append("cs_");
}
if (parameterNameList.Contains(nameof(DeviceAttribute.Hostname)))
{
createDeviceError.Append("Hostname ");
creationFunctionEntry.Append("hn_");
}
if (parameterNameList.Contains(nameof(DeviceAttribute.GatewayHostname)))
{
createDeviceError.Append("GatewayHostname ");
creationFunctionEntry.Append("gw_");
}
if (parameterNameList.Contains(nameof(DeviceAttribute.TransportType)))
{
createDeviceError.Append("TransportType ");
creationFunctionEntry.Append("tt_");
}
if (parameterNameList.Contains(nameof(DeviceAttribute.DeviceId)))
{
createDeviceError.Append("DeviceId ");
creationFunctionEntry.Append("did_");
}
if (hasTransportSettingsAttributes)
{
createDeviceError.Append("ITransportSettings[] ");
creationFunctionEntry.Append("ts_");
}
if (authenticationMethodPropertyName is not null)
{
createDeviceError.Append("AuthenticationMethod ");
creationFunctionEntry.Append("am_");
}
if (clientOptionsPropertyName is not null)
{
createDeviceError.Append("ClientOptions ");
creationFunctionEntry.Append("co_");
}
if (creationFunctionEntry.Length == 0) //no parameters
{
Location location = null;
if (attributeSyntax != null)
{
location = Location.Create(attributeSyntax.SyntaxTree, attributeSyntax.Span);
}
_diagnosticsManager.Report(DiagnosticId.DeviceParametersError, location);
return;
}
Append("var deviceClient = ");
creationFunctionEntry.Remove(creationFunctionEntry.Length - 1, 1); //remove the last _
//for debug:
//AppendLine($"//{creationFunctionEntry}");
switch (creationFunctionEntry.ToString())
{
case "cs":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)});");
break;
case "cs_co":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, {clientOptionsPropertyName});");
break;
case "cs_ts":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, transportSettings);");
break;
case "cs_ts_co":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, transportSettings, {clientOptionsPropertyName});");
break;
case "cs_tt":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.TransportType)});");
break;
case "cs_tt_co":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.TransportType)}, {clientOptionsPropertyName});");
break;
case "cs_did":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.DeviceId)});");
break;
case "cs_did_co":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.DeviceId)}, {clientOptionsPropertyName});");
break;
case "cs_tt_did":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.DeviceId)}, the{nameof(DeviceAttribute.TransportType)});");
break;
case "cs_did_ts":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.DeviceId)}, transportSettings);");
break;
case "cs_did_ts_co":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.DeviceId)}, transportSettings, {clientOptionsPropertyName});");
break;
case "hn_gw_tt_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName}, the{nameof(DeviceAttribute.TransportType)});");
break;
case "hn_gw_tt_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName}, the{nameof(DeviceAttribute.TransportType)}, {clientOptionsPropertyName});");
break;
case "hn_gw_ts_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName}, transportSettings);");
break;
case "hn_gw_ts_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName}, transportSettings, {clientOptionsPropertyName});");
break;
case "hn_gw_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName});");
break;
case "hn_gw_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName}, {clientOptionsPropertyName});");
break;
case "hn_tt_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName}, the{nameof(DeviceAttribute.TransportType)});");
break;
case "hn_tt_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName}, the{nameof(DeviceAttribute.TransportType)}, {clientOptionsPropertyName});");
break;
case "hn_ts_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName}, transportSettings);");
break;
case "hn_ts_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName}, transportSettings, {clientOptionsPropertyName});");
break;
case "hn_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName});");
break;
case "hn_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName}, {clientOptionsPropertyName});");
break;
default:
Location location = null;
if (attributeSyntax != null)
{
location = Location.Create(attributeSyntax.SyntaxTree, attributeSyntax.Span);
}
_diagnosticsManager.Report(DiagnosticId.ParametersMismatch, location, createDeviceError.ToString());
AppendLine(" null;");
break;
}
AppendLine("return deviceClient;");
}
}
19
View Source File : SnowflakeId.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
public static string replacedyzeId(long Id)
{
StringBuilder sb = new StringBuilder();
var timestamp = (Id >> timestampLeftShift);
var time = Jan1st1970.AddMilliseconds(timestamp + twepoch);
sb.Append(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss:fff"));
var datacenterId = (Id ^ (timestamp << timestampLeftShift)) >> datacenterIdShift;
sb.Append("_" + datacenterId);
var workerId = (Id ^ ((timestamp << timestampLeftShift) | (datacenterId << datacenterIdShift))) >> workerIdShift;
sb.Append("_" + workerId);
var sequence = Id & sequenceMask;
sb.Append("_" + sequence);
return sb.ToString();
}
19
View Source File : ToolController.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
[HttpPost]
public async Task<IResponseEnreplacedy> InitDb(DbConnecreplacedem req)
{
StringBuilder sb = new StringBuilder();
sb.Append("<ul>");
sb.Append("<li>创建数据连接对象 开始</li>");
var dbType = (FreeSql.DataType)Enum.Parse(typeof(FreeSql.DataType), req.DbType);
var connStr = req.ConnectionString;
IFreeSql fsql = new FreeSqlBuilder()
.UseConnectionString(dbType, connStr)
.UseAutoSyncStructure(true) //自动同步实体结构【开发环境必备】
.Build();
DbConnection dbConnection = fsql.Ado.MasterPool.Get().Value; // 这儿验证 连接是否成功,这句代码可以不要,如果连接字符不变正确,为了提早发现(报异常)
fsql.Aop.AuditValue += SyncDataAuditValue;
sb.Append("<li>创建数据连接对象 结束</li>");
sb.Append("<li>创建数据库结构及初始化数据 开始</li>");
using (var uow = fsql.CreateUnitOfWork())
using (var tran = uow.GetOrBeginTransaction())
{
SeedDataEnreplacedy data = (new SeedData()).GetSeedData();
sb.Append("<ul>");
await InitDtData(fsql, data.SysApiEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysConditionEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysDictionaryEntryEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysDictionaryHeaderEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysConfigEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysGroupEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysPermissionEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysResourceEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysRoleEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysRPermissionConditionEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysRPermissionRoleEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysRResourceApiEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysRRoleResourceEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysSettingEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysUserEnreplacedies.ToArray(), tran, sb);
await InitDtData(fsql, data.SysLoginLogEnreplacedies?.ToArray(), tran, sb);
await InitDtData(fsql, data.SysOperationLogEnreplacedies?.ToArray(), tran, sb);
sb.Append("</ul>");
uow.Commit();
}
sb.Append("<li>创建数据库结构及初始化数据 结束</li>");
sb.Append("</ul>");
fsql.Dispose();
return ResponseEnreplacedy.Ok("初始化成功", msg: sb.ToString());
}
19
View Source File : ToolController.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
private async Task<StringBuilder> InitDtData<T>(
IFreeSql db,
T[] data,
DbTransaction tran,
StringBuilder sb
) where T : clreplaced
{
var table = typeof(T).GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault() as TableAttribute;
var tableName = table.Name;
try
{
if (!await db.Queryable<T>().AnyAsync())
{
if (data?.Length > 0)
{
var insert = db.Insert<T>();
if (tran != null)
{
insert = insert.WithTransaction(tran);
}
if (db.Ado.DataType == DataType.SqlServer)
{
//var insrtSql = insert.AppendData(data).InsertIdenreplacedy().ToSql();
//var sql = $"SET IDENreplacedY_INSERT {tableName} ON\n {insrtSql} \nSET IDENreplacedY_INSERT {tableName} OFF";
//await db.Ado.ExecuteNonQueryAsync(sql);
await insert.AppendData(data).InsertIdenreplacedy().ExecuteAffrowsAsync();
}
else
{
await insert.AppendData(data).InsertIdenreplacedy().ExecuteAffrowsAsync();
}
sb.Append($"<li>table: {tableName} 生成种子数据 成功</li>");
Console.WriteLine($"table: {tableName} 生成种子数据 succeed");
}
else
{
sb.Append($"<li>table: {tableName} 无种子数据</li>");
Console.WriteLine($"table: {tableName} 无种子数据");
}
}
else
{
sb.Append($"<li>table: {tableName} 数据已存在 如果需重新初始化,先清空表</li>");
Console.WriteLine($"table: {tableName} 数据已存在 如果需重新初始化,先清空表");
}
return sb;
}
catch (Exception ex)
{
sb.Append($"<li>table: {tableName} 同步数据失败 \n{ex.Message}</li>");
Console.WriteLine($"table: {tableName} 同步数据失败 \n{ex.Message}");
return sb;
}
}
19
View Source File : StringBuilderExtensions.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
private static void EncodeCsv(StringBuilder sb, StringFormat sf, object value)
{
if (value == null) return;
sb.Append(value.ToString());
}
19
View Source File : StringBuilderExtensions.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
private static void EncodeJson(StringBuilder sb, StringFormat sf, object value)
{
if (value == null)
{
AppendNull(sb, sf);
return;
}
Type t = value.GetType();
string quote = sf == StringFormat.Json ? JsonQuote : JsonSingleQuote;
if (t == typeof(string))
{
sb.Append(quote);
sb.Append(HttpEncoder.JavaScriptStringEncode((string)value));
sb.Append(quote);
}
else if(t == typeof(DateTimeOffset))
{
sb.Append(quote);
sb.Append(value.ToString());
sb.Append(quote);
}
else if(t == typeof(bool))
{
sb.Append((bool)value ? "true" : "false");
}
else
{
sb.Append(value.ToString());
}
}
19
View Source File : HttpEncoder.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public static string JavaScriptStringEncode(string value)
{
if (string.IsNullOrEmpty(value))
return string.Empty;
StringBuilder builder = (StringBuilder)null;
int startIndex = 0;
int count = 0;
for (int index = 0; index < value.Length; ++index)
{
char c = value[index];
if (CharRequiresJavaScriptEncoding(c))
{
if (builder == null)
builder = new StringBuilder(value.Length + 5);
if (count > 0)
builder.Append(value, startIndex, count);
startIndex = index + 1;
count = 0;
}
switch (c)
{
case '\b':
builder.Append("\\b");
break;
case '\t':
builder.Append("\\t");
break;
case '\n':
builder.Append("\\n");
break;
case '\f':
builder.Append("\\f");
break;
case '\r':
builder.Append("\\r");
break;
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
default:
if (CharRequiresJavaScriptEncoding(c))
{
AppendCharAsUnicodeJavaScript(builder, c);
break;
}
++count;
break;
}
}
if (builder == null)
return value;
if (count > 0)
builder.Append(value, startIndex, count);
return builder.ToString();
}
19
View Source File : HttpEncoder.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
private static void AppendCharAsUnicodeJavaScript(StringBuilder builder, char c)
{
builder.Append("\\u");
builder.Append(((int)c).ToString("x4", (IFormatProvider)CultureInfo.InvariantCulture));
}
See More Examples