content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace Aurora.EffectsEngine.Animations
{
public class AnimationFilledCircle : AnimationCircle
{
public AnimationFilledCircle() : base()
{
}
public AnimationFilledCircle(Rectangle dimension, Color color, float duration = 0.0f) : base(dimension, color, 1, duration)
{
}
public AnimationFilledCircle(RectangleF dimension, Color color, float duration = 0.0f) : base(dimension, color, 1, duration)
{
}
public AnimationFilledCircle(PointF center, float radius, Color color, int width = 1, float duration = 0.0f) : base(center, radius, color, width, duration)
{
}
public AnimationFilledCircle(float x, float y, float radius, Color color, int width = 1, float duration = 0.0f) : base(x, y, radius, color, width, duration)
{
}
public override void Draw(Graphics g, float scale = 1.0f)
{
if (_brush == null || _invalidated)
{
_brush = new SolidBrush(_color);
_invalidated = false;
}
RectangleF _scaledDimension = new RectangleF(_dimension.X * scale, _dimension.Y * scale, _dimension.Width * scale, _dimension.Height * scale);
Matrix rotationMatrix = new Matrix();
rotationMatrix.RotateAt(-_angle, new PointF(_center.X * scale, _center.Y * scale), MatrixOrder.Append);
Matrix originalMatrix = g.Transform;
g.Transform = rotationMatrix;
g.FillEllipse(_brush, _scaledDimension);
g.Transform = originalMatrix;
}
public override AnimationFrame BlendWith(AnimationFrame otherAnim, double amount)
{
if (!(otherAnim is AnimationFilledCircle))
{
throw new FormatException("Cannot blend with another type");
}
amount = GetTransitionValue(amount);
RectangleF newrect = new RectangleF((float)CalculateNewValue(_dimension.X, otherAnim._dimension.X, amount),
(float)CalculateNewValue(_dimension.Y, otherAnim._dimension.Y, amount),
(float)CalculateNewValue(_dimension.Width, otherAnim._dimension.Width, amount),
(float)CalculateNewValue(_dimension.Height, otherAnim._dimension.Height, amount)
);
float newAngle = (float)CalculateNewValue(_angle, otherAnim._angle, amount);
return new AnimationFilledCircle(newrect, Utils.ColorUtils.BlendColors(_color, otherAnim._color, amount)).SetAngle(newAngle);
}
public override AnimationFrame GetCopy()
{
RectangleF newrect = new RectangleF(_dimension.X,
_dimension.Y,
_dimension.Width,
_dimension.Height
);
return new AnimationFilledCircle(newrect, Color.FromArgb(_color.A, _color.R, _color.G, _color.B), _duration).SetAngle(_angle).SetTransitionType(_transitionType);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((AnimationFilledCircle)obj);
}
public bool Equals(AnimationFilledCircle p)
{
return _color.Equals(p._color) &&
_dimension.Equals(p._dimension) &&
_width.Equals(p._width) &&
_duration.Equals(p._duration) &&
_angle.Equals(p._angle);
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 23 + _color.GetHashCode();
hash = hash * 23 + _dimension.GetHashCode();
hash = hash * 23 + _width.GetHashCode();
hash = hash * 23 + _duration.GetHashCode();
hash = hash * 23 + _angle.GetHashCode();
return hash;
}
}
public override string ToString()
{
return $"AnimationFilledCircle [ Color: {_color.ToString()} Dimensions: {_dimension.ToString()} Duration: {_duration} Angle: {_angle} ]";
}
}
}
| 38.34188 | 174 | 0.576683 | [
"MIT"
] | boristomas/Aurora | Project-Aurora/Project-Aurora/EffectsEngine/Animations/AnimationFilledCircle.cs | 4,372 | C# |
/*
Copyright (c) 2018, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.IO;
using System.Linq;
using MatterHackers.Agg;
using MatterHackers.Agg.Platform;
using MatterHackers.Agg.UI;
using MatterHackers.ImageProcessing;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.CustomWidgets;
using MatterHackers.MatterControl.PrinterControls.PrinterConnections;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.MatterControl.SlicerConfiguration;
namespace MatterHackers.MatterControl.PrintLibrary
{
public class HardwareTreeView : TreeView
{
private TreeNode printersNode;
private FlowLayoutWidget rootColumn;
private EventHandler unregisterEvents;
public HardwareTreeView(ThemeConfig theme)
: base(theme)
{
rootColumn = new FlowLayoutWidget(FlowDirection.TopToBottom)
{
HAnchor = HAnchor.Stretch,
VAnchor = VAnchor.Fit
};
this.AddChild(rootColumn);
// Printers
printersNode = new TreeNode(theme)
{
Text = "Printers".Localize(),
HAnchor = HAnchor.Stretch,
AlwaysExpandable = true,
Image = StaticData.Instance.LoadIcon("printer.png", 16, 16).SetToColor(theme.TextColor)
};
printersNode.TreeView = this;
var forcedHeight = 20 * GuiWidget.DeviceScale;
var mainRow = printersNode.Children.FirstOrDefault();
mainRow.HAnchor = HAnchor.Stretch;
mainRow.AddChild(new HorizontalSpacer());
// add in the create printer button
var createPrinter = new IconButton(StaticData.Instance.LoadIcon("md-add-circle_18.png", 18, 18).SetToColor(theme.TextColor), theme)
{
Name = "Create Printer",
VAnchor = VAnchor.Center,
Margin = theme.ButtonSpacing.Clone(left: theme.ButtonSpacing.Right),
ToolTipText = "Create Printer".Localize(),
Height = forcedHeight,
Width = forcedHeight
};
createPrinter.Click += (s, e) => UiThread.RunOnIdle(() =>
{
DialogWindow.Show(PrinterSetup.GetBestStartPage(PrinterSetup.StartPageOptions.ShowMakeModel));
});
mainRow.AddChild(createPrinter);
// add in the import printer button
var importPrinter = new IconButton(StaticData.Instance.LoadIcon("md-import_18.png", 18, 18).SetToColor(theme.TextColor), theme)
{
VAnchor = VAnchor.Center,
Margin = theme.ButtonSpacing,
ToolTipText = "Import Printer".Localize(),
Height = forcedHeight,
Width = forcedHeight,
Name = "Import Printer Button"
};
importPrinter.Click += (s, e) => UiThread.RunOnIdle(() =>
{
DialogWindow.Show(new CloneSettingsPage());
});
mainRow.AddChild(importPrinter);
rootColumn.AddChild(printersNode);
HardwareTreeView.CreatePrinterProfilesTree(printersNode, theme);
this.Invalidate();
// Filament
var materialsNode = new TreeNode(theme)
{
Text = "Materials".Localize(),
AlwaysExpandable = true,
Image = StaticData.Instance.LoadIcon("filament.png", 16, 16).SetToColor(theme.TextColor)
};
materialsNode.TreeView = this;
rootColumn.AddChild(materialsNode);
// Register listeners
PrinterSettings.AnyPrinterSettingChanged += Printer_SettingChanged;
// Rebuild the treeview anytime the Profiles list changes
ProfileManager.ProfilesListChanged.RegisterEvent((s, e) =>
{
HardwareTreeView.CreatePrinterProfilesTree(printersNode, theme);
this.Invalidate();
}, ref unregisterEvents);
}
public static void CreatePrinterProfilesTree(TreeNode printersNode, ThemeConfig theme)
{
if (printersNode == null)
{
return;
}
printersNode.Nodes.Clear();
// Add the menu items to the menu itself
foreach (var printer in ProfileManager.Instance.ActiveProfiles.OrderBy(p => p.Name))
{
var printerNode = new TreeNode(theme)
{
Text = printer.Name,
Name = $"{printer.Name} Node",
Tag = printer
};
printerNode.Load += (s, e) =>
{
printerNode.Image = OemSettings.Instance.GetIcon(printer.Make);
};
printersNode.Nodes.Add(printerNode);
}
printersNode.Expanded = true;
}
public static void CreateOpenPrintersTree(TreeNode printersNode, ThemeConfig theme)
{
if (printersNode == null)
{
return;
}
printersNode.Nodes.Clear();
// Add the menu items to the menu itself
foreach (var printer in ApplicationController.Instance.ActivePrinters)
{
string printerName = printer.Settings.GetValue(SettingsKey.printer_name);
var printerNode = new TreeNode(theme)
{
Text = printerName,
Name = $"{printerName} Node",
Tag = printer
};
printerNode.Load += (s, e) =>
{
printerNode.Image = OemSettings.Instance.GetIcon(printer.Settings.GetValue(SettingsKey.make));
};
printersNode.Nodes.Add(printerNode);
}
printersNode.Expanded = true;
}
public override void OnClosed(EventArgs e)
{
// Unregister listeners
PrinterSettings.AnyPrinterSettingChanged -= Printer_SettingChanged;
base.OnClosed(e);
}
private void Printer_SettingChanged(object s, StringEventArgs e)
{
string settingsName = e?.Data;
if (settingsName != null && settingsName == SettingsKey.printer_name)
{
// Allow enough time for ProfileManager to respond and refresh its data
UiThread.RunOnIdle(() =>
{
HardwareTreeView.CreatePrinterProfilesTree(printersNode, theme);
}, .2);
this.Invalidate();
}
}
}
}
| 30.644144 | 134 | 0.733647 | [
"BSD-2-Clause"
] | Bhalddin/MatterControl | MatterControlLib/Library/Widgets/HardwareTreeView.cs | 6,805 | C# |
/*******************************************************
*
* 作者:胡庆访
* 创建时间:20120220
* 说明:此文件只包含一个类,具体内容见类型注释。
* 运行环境:.NET 4.0
* 版本号:1.0.0
*
* 历史记录:
* 创建文件 胡庆访 20120220
*
*******************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rafy.Domain;
using Rafy.ManagedProperty;
using Newtonsoft.Json.Linq;
using Rafy.MetaModel;
using Rafy.Utils;
using Rafy.MetaModel.View;
using Rafy.Web.Json;
using System.Diagnostics;
using Rafy.Web.ClientMetaModel;
using Rafy.Reflection;
namespace Rafy.Web.EntityDataPortal
{
/// <summary>
/// Entity 与 Json 相互转换的类
/// </summary>
internal class EntityJsonConverter
{
/// <summary>
/// 把实体列表对应的 json 转换为 EntityList 对象。
/// </summary>
/// <param name="jEntityList"></param>
/// <param name="repository">如果没有显式指定 Repository,则会根据 json 中的 _model 属性来查找对应的实体仓库。</param>
/// <returns></returns>
[DebuggerStepThrough]
internal static EntityList JsonToEntityList(JObject jEntityList, EntityRepository repository = null)
{
return ListReader.JsonToEntity(jEntityList, repository);
}
internal static void EntityToJson(EntityViewMeta evm, IEnumerable<Entity> entities, IList<EntityJson> list)
{
foreach (var entity in entities)
{
var entityJson = new EntityJson();
EntityToJson(evm, entity, entityJson);
list.Add(entityJson);
}
}
internal static void EntityToJson(EntityViewMeta evm, Entity entity, EntityJson entityJson)
{
var isTree = evm.EntityMeta.IsTreeEntity;
foreach (var propertyVM in evm.EntityProperties)
{
var property = propertyVM.PropertyMeta;
var mp = property.ManagedProperty;
if (mp != null)
{
//如果非树型实体,则需要排除树型实体的两个属性。
if (!isTree && (mp == Entity.TreeIndexProperty || mp == Entity.TreePIdProperty)) { continue; }
//引用属性
if (mp is IRefEntityProperty)
{
var refMp = mp as IRefProperty;
var id = entity.GetRefNullableId(refMp.RefIdProperty);
if (id != null)
{
entityJson.SetProperty(refMp.RefIdProperty.Name, id);
//同时写入引用属性的视图属性,如 BookCategoryId_Display
var titleProperty = propertyVM.SelectionViewMeta?.RefTypeDefaultView?.TitleProperty;
if (titleProperty != null)
{
var lazyRefEntity = entity.GetRefEntity(refMp.RefEntityProperty);
var titleMp = titleProperty.PropertyMeta.ManagedProperty;
object value;
if (titleMp != null)
{
value = lazyRefEntity.GetProperty(titleMp);
}
else
{
value = ObjectHelper.GetPropertyValue(lazyRefEntity, titleProperty.Name);
}
var name = EntityModelGenerator.DisplayRefProperty(refMp);
entityJson.SetProperty(name, value);
}
}
}
else if (mp is IRefProperty)
{
//ignore
}
//一般托管属性
else
{
var pRuntimeType = property.PropertyType;
var serverType = ServerTypeHelper.GetServerType(pRuntimeType);
if (serverType.Name != SupportedServerType.Unknown)
{
var value = entity.GetProperty(mp);
value = ToClientValue(pRuntimeType, value);
entityJson.SetProperty(mp.Name, value);
}
}
}
//一般 CLR 属性
else
{
var pRuntimeType = property.PropertyType;
var serverType = ServerTypeHelper.GetServerType(pRuntimeType);
if (serverType.Name != SupportedServerType.Unknown)
{
var value = ObjectHelper.GetPropertyValue(entity, property.Name);
value = ToClientValue(pRuntimeType, value);
entityJson.SetProperty(property.Name, value);
}
}
}
}
internal static object ToClientValue(Type serverType, object value)
{
if (serverType.IsEnum) { value = EnumViewModel.EnumToLabel(value as Enum); }
else if (serverType == typeof(Nullable<int>))
{
if (value == null) value = 0;
}
else if (serverType == typeof(Nullable<Guid>))
{
if (value == null) value = Guid.Empty;
value = value.ToString();
}
else if (serverType == typeof(Guid))
{
value = value.ToString();
}
return value;
}
internal static object ToServerValue(Type serverType, object value)
{
if (serverType.IsEnum) { value = EnumViewModel.Parse(value as string, serverType); }
else if (serverType == typeof(Nullable<int>))
{
var intValue = Convert.ToInt32(value);
if (intValue == 0) value = null;
else if (!(value is int)) value = intValue;
}
else if (serverType == typeof(Nullable<Guid>))
{
if (value != null)
{
var guidValue = Guid.Parse(value.ToString());
if (guidValue == Guid.Empty) value = null;
}
}
else if (serverType == typeof(Guid))
{
if (value != null)
{
value = Guid.Parse(value.ToString());
}
else
{
value = Guid.Empty;
}
}
return value;
}
}
} | 36.712766 | 116 | 0.448855 | [
"MIT"
] | zgynhqf/trunk | Rafy/Web/Rafy.Web/EntityDataPortal/EntityJsonConverter.cs | 7,216 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Hotfix")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Hotfix")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0728467B-73C1-46DE-90EB-5C506A28818D")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 38.428571 | 84 | 0.739777 | [
"MIT"
] | futouyiba/ClubET | ThirdParty/Hotfix/Properties/AssemblyInfo.cs | 1,348 | C# |
using Neo.IO;
using System;
using System.IO;
using System.Numerics;
using static Neo.Helper;
namespace Neo.Cryptography.ECC
{
public class ECPoint : IComparable<ECPoint>, IEquatable<ECPoint>, ISerializable
{
internal ECFieldElement X, Y;
internal readonly ECCurve Curve;
private byte[] _compressedPoint, _uncompressedPoint;
public bool IsInfinity
{
get { return X == null && Y == null; }
}
public int Size => IsInfinity ? 1 : 33;
public ECPoint() : this(null, null, ECCurve.Secp256r1) { }
internal ECPoint(ECFieldElement x, ECFieldElement y, ECCurve curve)
{
if ((x is null ^ y is null) || (curve is null))
throw new ArgumentException("Exactly one of the field elements is null");
this.X = x;
this.Y = y;
this.Curve = curve;
}
public int CompareTo(ECPoint other)
{
if (!Curve.Equals(other.Curve)) throw new InvalidOperationException("Invalid comparision for points with different curves");
if (ReferenceEquals(this, other)) return 0;
int result = X.CompareTo(other.X);
if (result != 0) return result;
return Y.CompareTo(other.Y);
}
public static ECPoint DecodePoint(ReadOnlySpan<byte> encoded, ECCurve curve)
{
ECPoint p = null;
switch (encoded[0])
{
case 0x02: // compressed
case 0x03: // compressed
{
if (encoded.Length != (curve.ExpectedECPointLength + 1))
throw new FormatException("Incorrect length for compressed encoding");
int yTilde = encoded[0] & 1;
BigInteger X1 = new BigInteger(encoded[1..], isUnsigned: true, isBigEndian: true);
p = DecompressPoint(yTilde, X1, curve);
p._compressedPoint = encoded.ToArray();
break;
}
case 0x04: // uncompressed
{
if (encoded.Length != (2 * curve.ExpectedECPointLength + 1))
throw new FormatException("Incorrect length for uncompressed/hybrid encoding");
BigInteger X1 = new BigInteger(encoded[1..(1 + curve.ExpectedECPointLength)], isUnsigned: true, isBigEndian: true);
BigInteger Y1 = new BigInteger(encoded[(1 + curve.ExpectedECPointLength)..], isUnsigned: true, isBigEndian: true);
p = new ECPoint(new ECFieldElement(X1, curve), new ECFieldElement(Y1, curve), curve)
{
_uncompressedPoint = encoded.ToArray()
};
break;
}
default:
throw new FormatException("Invalid point encoding " + encoded[0]);
}
return p;
}
private static ECPoint DecompressPoint(int yTilde, BigInteger X1, ECCurve curve)
{
ECFieldElement x = new ECFieldElement(X1, curve);
ECFieldElement alpha = x * (x.Square() + curve.A) + curve.B;
ECFieldElement beta = alpha.Sqrt();
//
// if we can't find a sqrt we haven't got a point on the
// curve - run!
//
if (beta == null)
throw new ArithmeticException("Invalid point compression");
BigInteger betaValue = beta.Value;
int bit0 = betaValue.IsEven ? 0 : 1;
if (bit0 != yTilde)
{
// Use the other root
beta = new ECFieldElement(curve.Q - betaValue, curve);
}
return new ECPoint(x, beta, curve);
}
void ISerializable.Deserialize(BinaryReader reader)
{
ECPoint p = DeserializeFrom(reader, Curve);
X = p.X;
Y = p.Y;
}
public static ECPoint DeserializeFrom(BinaryReader reader, ECCurve curve)
{
Span<byte> buffer = stackalloc byte[1 + curve.ExpectedECPointLength * 2];
buffer[0] = reader.ReadByte();
switch (buffer[0])
{
case 0x02:
case 0x03:
{
if (reader.Read(buffer[1..(1 + curve.ExpectedECPointLength)]) != curve.ExpectedECPointLength)
{
throw new FormatException();
}
return DecodePoint(buffer[..(1 + curve.ExpectedECPointLength)], curve);
}
case 0x04:
{
if (reader.Read(buffer[1..(1 + curve.ExpectedECPointLength * 2)]) != curve.ExpectedECPointLength * 2)
{
throw new FormatException();
}
return DecodePoint(buffer, curve);
}
default:
throw new FormatException("Invalid point encoding " + buffer[0]);
}
}
/// <summary>
/// Encode ECPoint to byte array
/// Note: The return should't be modified because it could be cached
/// </summary>
/// <param name="commpressed">Compressed</param>
/// <returns>Encoded point</returns>
public byte[] EncodePoint(bool commpressed)
{
if (IsInfinity) return new byte[1];
byte[] data;
if (commpressed)
{
if (_compressedPoint != null) return _compressedPoint;
data = new byte[33];
}
else
{
if (_uncompressedPoint != null) return _uncompressedPoint;
data = new byte[65];
byte[] yBytes = Y.Value.ToByteArray(isUnsigned: true, isBigEndian: true);
Buffer.BlockCopy(yBytes, 0, data, 65 - yBytes.Length, yBytes.Length);
}
byte[] xBytes = X.Value.ToByteArray(isUnsigned: true, isBigEndian: true);
Buffer.BlockCopy(xBytes, 0, data, 33 - xBytes.Length, xBytes.Length);
data[0] = commpressed ? Y.Value.IsEven ? (byte)0x02 : (byte)0x03 : (byte)0x04;
if (commpressed) _compressedPoint = data;
else _uncompressedPoint = data;
return data;
}
public bool Equals(ECPoint other)
{
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(null, other)) return false;
if (IsInfinity && other.IsInfinity) return true;
if (IsInfinity || other.IsInfinity) return false;
return X.Equals(other.X) && Y.Equals(other.Y);
}
public override bool Equals(object obj)
{
return Equals(obj as ECPoint);
}
public static ECPoint FromBytes(byte[] pubkey, ECCurve curve)
{
switch (pubkey.Length)
{
case 33:
case 65:
return DecodePoint(pubkey, curve);
case 64:
case 72:
return DecodePoint(Concat(new byte[] { 0x04 }, pubkey[^64..]), curve);
case 96:
case 104:
return DecodePoint(Concat(new byte[] { 0x04 }, pubkey[^96..^32]), curve);
default:
throw new FormatException();
}
}
public override int GetHashCode()
{
return X.GetHashCode() + Y.GetHashCode();
}
internal static ECPoint Multiply(ECPoint p, BigInteger k)
{
// floor(log2(k))
int m = (int)k.GetBitLength();
// width of the Window NAF
sbyte width;
// Required length of precomputation array
int reqPreCompLen;
// Determine optimal width and corresponding length of precomputation
// array based on literature values
if (m < 13)
{
width = 2;
reqPreCompLen = 1;
}
else if (m < 41)
{
width = 3;
reqPreCompLen = 2;
}
else if (m < 121)
{
width = 4;
reqPreCompLen = 4;
}
else if (m < 337)
{
width = 5;
reqPreCompLen = 8;
}
else if (m < 897)
{
width = 6;
reqPreCompLen = 16;
}
else if (m < 2305)
{
width = 7;
reqPreCompLen = 32;
}
else
{
width = 8;
reqPreCompLen = 127;
}
// The length of the precomputation array
int preCompLen = 1;
ECPoint[] preComp = new ECPoint[] { p };
ECPoint twiceP = p.Twice();
if (preCompLen < reqPreCompLen)
{
// Precomputation array must be made bigger, copy existing preComp
// array into the larger new preComp array
ECPoint[] oldPreComp = preComp;
preComp = new ECPoint[reqPreCompLen];
Array.Copy(oldPreComp, 0, preComp, 0, preCompLen);
for (int i = preCompLen; i < reqPreCompLen; i++)
{
// Compute the new ECPoints for the precomputation array.
// The values 1, 3, 5, ..., 2^(width-1)-1 times p are
// computed
preComp[i] = twiceP + preComp[i - 1];
}
}
// Compute the Window NAF of the desired width
sbyte[] wnaf = WindowNaf(width, k);
int l = wnaf.Length;
// Apply the Window NAF to p using the precomputed ECPoint values.
ECPoint q = p.Curve.Infinity;
for (int i = l - 1; i >= 0; i--)
{
q = q.Twice();
if (wnaf[i] != 0)
{
if (wnaf[i] > 0)
{
q += preComp[(wnaf[i] - 1) / 2];
}
else
{
// wnaf[i] < 0
q -= preComp[(-wnaf[i] - 1) / 2];
}
}
}
return q;
}
public static ECPoint Parse(string value, ECCurve curve)
{
return DecodePoint(value.HexToBytes(), curve);
}
void ISerializable.Serialize(BinaryWriter writer)
{
writer.Write(EncodePoint(true));
}
public override string ToString()
{
return EncodePoint(true).ToHexString();
}
public static bool TryParse(string value, ECCurve curve, out ECPoint point)
{
try
{
point = Parse(value, curve);
return true;
}
catch (FormatException)
{
point = null;
return false;
}
}
internal ECPoint Twice()
{
if (this.IsInfinity)
return this;
if (this.Y.Value.Sign == 0)
return Curve.Infinity;
ECFieldElement TWO = new ECFieldElement(2, Curve);
ECFieldElement THREE = new ECFieldElement(3, Curve);
ECFieldElement gamma = (this.X.Square() * THREE + Curve.A) / (Y * TWO);
ECFieldElement x3 = gamma.Square() - this.X * TWO;
ECFieldElement y3 = gamma * (this.X - x3) - this.Y;
return new ECPoint(x3, y3, Curve);
}
private static sbyte[] WindowNaf(sbyte width, BigInteger k)
{
sbyte[] wnaf = new sbyte[k.GetBitLength() + 1];
short pow2wB = (short)(1 << width);
int i = 0;
int length = 0;
while (k.Sign > 0)
{
if (!k.IsEven)
{
BigInteger remainder = k % pow2wB;
if (remainder.TestBit(width - 1))
{
wnaf[i] = (sbyte)(remainder - pow2wB);
}
else
{
wnaf[i] = (sbyte)remainder;
}
k -= wnaf[i];
length = i;
}
else
{
wnaf[i] = 0;
}
k >>= 1;
i++;
}
length++;
sbyte[] wnafShort = new sbyte[length];
Array.Copy(wnaf, 0, wnafShort, 0, length);
return wnafShort;
}
public static ECPoint operator -(ECPoint x)
{
return new ECPoint(x.X, -x.Y, x.Curve);
}
public static ECPoint operator *(ECPoint p, byte[] n)
{
if (p == null || n == null)
throw new ArgumentNullException();
if (n.Length != 32)
throw new ArgumentException();
if (p.IsInfinity)
return p;
BigInteger k = new BigInteger(n, isUnsigned: true, isBigEndian: true);
if (k.Sign == 0)
return p.Curve.Infinity;
return Multiply(p, k);
}
public static ECPoint operator +(ECPoint x, ECPoint y)
{
if (x.IsInfinity)
return y;
if (y.IsInfinity)
return x;
if (x.X.Equals(y.X))
{
if (x.Y.Equals(y.Y))
return x.Twice();
return x.Curve.Infinity;
}
ECFieldElement gamma = (y.Y - x.Y) / (y.X - x.X);
ECFieldElement x3 = gamma.Square() - x.X - y.X;
ECFieldElement y3 = gamma * (x.X - x3) - x.Y;
return new ECPoint(x3, y3, x.Curve);
}
public static ECPoint operator -(ECPoint x, ECPoint y)
{
if (y.IsInfinity)
return x;
return x + (-y);
}
}
}
| 34.143529 | 139 | 0.457033 | [
"MIT"
] | ShawnYun/neo | src/neo/Cryptography/ECC/ECPoint.cs | 14,511 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Kmd.Logic.Cvr.Client.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class LineOfIndustries
{
/// <summary>
/// Initializes a new instance of the LineOfIndustries class.
/// </summary>
public LineOfIndustries()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the LineOfIndustries class.
/// </summary>
public LineOfIndustries(Branch mainBusiness = default(Branch), Branch biBranch1 = default(Branch), Branch biBranch2 = default(Branch), Branch biBranch3 = default(Branch))
{
MainBusiness = mainBusiness;
BiBranch1 = biBranch1;
BiBranch2 = biBranch2;
BiBranch3 = biBranch3;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "mainBusiness")]
public Branch MainBusiness { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "biBranch1")]
public Branch BiBranch1 { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "biBranch2")]
public Branch BiBranch2 { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "biBranch3")]
public Branch BiBranch3 { get; set; }
}
}
| 29.016393 | 178 | 0.580791 | [
"MIT"
] | Araballi/kmd-logic-cvr-client | src/Kmd.Logic.Cvr.Client/Models/LineOfIndustries.cs | 1,770 | C# |
//******************************************************************************
//
// Copyright (c) 2016 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium.Windows;
using OpenQA.Selenium.Remote;
using System.Threading;
namespace CortanaTest
{
[TestClass]
public class BingSearch
{
private const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
private static WindowsDriver<WindowsElement> cortanaSession;
private static WindowsDriver<WindowsElement> desktopSession;
private static WindowsElement searchBox;
[TestMethod]
public void LocalSearch()
{
// Type "add" in Cortana search box
searchBox.SendKeys("add");
Thread.Sleep(TimeSpan.FromSeconds(1));
var bingPane = cortanaSession.FindElementByName("Bing");
Assert.IsNotNull(bingPane);
// Verify that a shortcut to "System settings Add or remove programs" is shown as a search result
var bingResult = bingPane.FindElementByXPath("//ListItem[starts-with(@Name, \"Add or remove\")]");
Assert.IsNotNull(bingResult);
Assert.IsTrue(bingResult.Text.Contains("System settings"));
}
[TestMethod]
public void WebSearchCalculator()
{
// Type a math sentence in Cortana search box
searchBox.SendKeys("What is eight times eleven");
Thread.Sleep(TimeSpan.FromSeconds(1));
var bingPane = cortanaSession.FindElementByName("Bing");
Assert.IsNotNull(bingPane);
// Verify that a Calculator result is shown as one of the search results
var bingResult = bingPane.FindElementByXPath("//*[contains(@Name, \"= 88\")]");
Assert.IsNotNull(bingResult);
Assert.IsTrue(bingResult.Text.Contains("8"));
Assert.IsTrue(bingResult.Text.Contains("11"));
}
[TestMethod]
public void WebSearchStockName()
{
// Type a Microsoft stock name in Cortana search box
searchBox.SendKeys("msft");
Thread.Sleep(TimeSpan.FromSeconds(1));
var bingPane = cortanaSession.FindElementByName("Bing");
Assert.IsNotNull(bingPane);
// Verify that a Microsoft stock in NASDAQ is shown as one of the search results
var bingResult = bingPane.FindElementByXPath("//*[contains(@Name, \"Microsoft\")]");
Assert.IsNotNull(bingResult);
Assert.IsTrue(bingResult.Text.Contains("NASDAQ"));
Assert.IsTrue(bingResult.Text.Contains("MSFT"));
}
[ClassInitialize]
public static void Setup(TestContext context)
{
// Create a session for Desktop
DesiredCapabilities desktopCapabilities = new DesiredCapabilities();
desktopCapabilities.SetCapability("app", "Root");
desktopSession = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), desktopCapabilities);
Assert.IsNotNull(desktopSession);
// Launch Cortana Window using Windows Key + S keyboard shortcut to allow session creation to find it
desktopSession.Keyboard.SendKeys(OpenQA.Selenium.Keys.Meta + "s" + OpenQA.Selenium.Keys.Meta);
Thread.Sleep(TimeSpan.FromSeconds(1));
WindowsElement CortanaWindow = desktopSession.FindElementByName("Cortana");
string CortanaTopLevelWindowHandle = CortanaTopLevelWindowHandle = (int.Parse(CortanaWindow.GetAttribute("NativeWindowHandle"))).ToString("x");
// Create session for already running Cortana
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("appTopLevelWindow", CortanaTopLevelWindowHandle);
cortanaSession = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
Assert.IsNotNull(cortanaSession);
// Set implicit timeout to 5 seconds to make element search to retry every 500 ms for at most ten times
cortanaSession.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
}
[ClassCleanup]
public static void TearDown()
{
searchBox = null;
if (cortanaSession != null)
{
// Send escape key to close Cortana window
cortanaSession.Keyboard.SendKeys(OpenQA.Selenium.Keys.Escape + OpenQA.Selenium.Keys.Escape);
cortanaSession.Quit();
cortanaSession = null;
}
if (desktopSession != null)
{
desktopSession.Quit();
desktopSession = null;
}
}
[TestInitialize]
public void ClearSearchBox()
{
try
{
// Locate Cortana search box to ensure it is still displayed on the screen
searchBox = cortanaSession.FindElementByAccessibilityId("SearchTextBox");
searchBox.Clear();
}
catch
{
// Use Windows Key + S to relaunch Cortana window if it is not displayed
desktopSession.Keyboard.SendKeys(OpenQA.Selenium.Keys.Meta + "s" + OpenQA.Selenium.Keys.Meta);
Thread.Sleep(TimeSpan.FromSeconds(1));
searchBox = cortanaSession.FindElementByAccessibilityId("SearchTextBox");
}
Assert.IsNotNull(searchBox);
Thread.Sleep(TimeSpan.FromSeconds(0.5));
}
}
}
| 42.777027 | 155 | 0.620439 | [
"MIT"
] | Accordingtomark/WinAppDriver | Samples/C#/CortanaTest/BingSearch.cs | 6,333 | C# |
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using NhapMonCNPM.MultiTenancy;
namespace NhapMonCNPM.Sessions.Dto
{
[AutoMapFrom(typeof(Tenant))]
public class TenantLoginInfoDto : EntityDto
{
public string TenancyName { get; set; }
public string Name { get; set; }
}
}
| 21 | 47 | 0.695238 | [
"MIT"
] | huyquyen0501/NhapMonCNPM | aspnet-core/src/NhapMonCNPM.Application/Sessions/Dto/TenantLoginInfoDto.cs | 317 | C# |
/****************************************************************************
Copyright (c) 2015 Lingjijian
Created by Lingjijian on 2015
342854406@qq.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace Lui
{
public enum ProgressLabStyle
{
Normal,
Value
}
[SLua.CustomLuaClass]
public class LProgress : MonoBehaviour {
public float maxValue;
public float minValue;
private float _value;
public RectMask2D mask;
public Text label;
private bool _isStartProgress;
private float _arrivePercentage;
private float _startProgressStep;
public UnityAction onProgress;
public UnityAction onProgressEnd;
public ProgressLabStyle style;
protected float _width;
protected float _height;
public LProgress()
{
maxValue = 100;
minValue = 0;
_value = 15;
_isStartProgress = false;
_arrivePercentage = 0;
_startProgressStep = 0;
style = ProgressLabStyle.Normal;
}
public void setValue(float value)
{
this._value = Mathf.Min(maxValue, Mathf.Max(minValue, value));
mask.GetComponent<RectTransform>().sizeDelta = new Vector2(
GetComponent<RectTransform>().rect.width * getPercentage(),
GetComponent<RectTransform>().rect.height);
mask.gameObject.SetActive(_value != 0);
if (label)
{
if(style == ProgressLabStyle.Normal){
label.text = (this._value / maxValue * 100).ToString("0.0") + "%";
}else if(style == ProgressLabStyle.Value){
label.text = string.Format("{0}/{1}",this._value,maxValue);
}
}
}
public float getValue()
{
return _value;
}
public float getPercentage()
{
return (_value - minValue) / (maxValue - minValue);
}
public void startProgress(float value,float step)
{
if (value <= minValue && value >= maxValue) {
return;
}
_arrivePercentage = (value - minValue) / (maxValue - minValue);
_startProgressStep = step;
_isStartProgress = true;
}
void Update()
{
if (_isStartProgress) {
_value = _value + _startProgressStep;
float perc = getPercentage ();
mask.GetComponent<RectTransform>().sizeDelta = new Vector2(
GetComponent<RectTransform>().rect.width * perc,
GetComponent<RectTransform>().rect.height);
if (label) {
if (style == ProgressLabStyle.Normal)
{
label.text = (perc * 100).ToString("0.0") + "%";
}
else if (style == ProgressLabStyle.Value)
{
label.text = string.Format("{0}/{1}", this._value, maxValue);
}
}
if (perc < _arrivePercentage) {
if (onProgress!=null)
onProgress.Invoke ();
} else {
if (onProgressEnd!=null)
onProgressEnd.Invoke ();
_isStartProgress = false;
}
}
}
}
} | 30.219858 | 83 | 0.61441 | [
"MIT"
] | LingJiJian/uLui | Assets/Game/Resources/Scripts/LWidget/LProgress.cs | 4,263 | C# |
// <copyright file="LocateableExtensions.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.AdminPanel.Map
{
using MUnique.OpenMU.GameLogic;
/// <summary>
/// Extension methods for <see cref="ILocateable"/>.
/// </summary>
public static class LocateableExtensions
{
/// <summary>
/// Creates a map object for the given locateable object.
/// </summary>
/// <param name="locateable">The locateable object.</param>
/// <returns>The created map object.</returns>
public static MapObject CreateMapObject(this ILocateable locateable)
{
return new MapObject
{
Direction = (locateable as IRotatable)?.Rotation ?? default,
Id = locateable.Id,
MapId = locateable.CurrentMap?.MapId ?? 0,
Name = locateable.ToString() ?? string.Empty,
X = locateable.Position.X,
Y = locateable.Position.Y,
};
}
}
} | 35.25 | 101 | 0.590426 | [
"MIT"
] | cristian-eriomenco/OpenMU | src/AdminPanel/Map/LocateableExtensions.cs | 1,130 | C# |
#region Copyright (C) 2020 Kevin (OSS开源实验室) 公众号:osscore
/***************************************************************************
* 文件功能描述:OSS.Adapter 性别枚举
*
* 创建人: Kevin
* 创建人Email:1985088337@qq.com
* 创建日期:20120-8-14
*
*****************************************************************************/
#endregion
namespace OSS.Adapter.Oauth.Interface.Mos.Enums
{
public enum OauthSexType
{
UnKnow = 0,
Male = 1,
Female = 2
}
}
| 19.115385 | 78 | 0.396378 | [
"Apache-2.0"
] | KevinWG/OSS.Adapers | Oauth/OSS.Adapter.Oauth.Interface/Mos/Enums/OauthSexType.cs | 573 | C# |
// Node.cs
//
// Copyright 2012 The Minions Project (http:/github.com/Minions).
// All rights reserved. Usage as permitted by the LICENSE.txt file for this project.
namespace Fools.cs.AST
{
public abstract class Node {}
}
| 22.8 | 84 | 0.719298 | [
"BSD-3-Clause"
] | arlobelshee/Minions | src/Fools.cs/AST/Node.cs | 228 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using EdFi.Common.Extensions;
using EdFi.Ods.CodeGen.Extensions;
using EdFi.Ods.CodeGen.Models;
using EdFi.Ods.Common.Conventions;
using EdFi.Ods.Common.Extensions;
using EdFi.Ods.Common.Models.Domain;
using EdFi.Ods.Common.Models.Resource;
using EdFi.Ods.Common.Specifications;
namespace EdFi.Ods.CodeGen.Generators.Resources
{
public class ResourcePropertyRenderer
{
public object AssembleProperties(ResourceClassBase resource)
{
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
var props = CreateProperties(resource)
.ToList();
return props.Any()
? new {Properties = CreatePropertyDtos(props)}
: ResourceRenderer.DoNotRenderProperty;
}
public object AssemblePrimaryKeys(
ResourceProfileData profileData,
ResourceClassBase resourceClass,
TemplateContext templateContext)
{
if (profileData == null)
{
throw new ArgumentNullException(nameof(profileData));
}
if (resourceClass == null)
{
throw new ArgumentNullException(nameof(resourceClass));
}
if (templateContext == null)
{
throw new ArgumentNullException(nameof(templateContext));
}
var pks = new List<object>();
var activeResource = profileData.GetProfileActiveResource(resourceClass);
var filteredResource = profileData.GetContainedResource(resourceClass) ?? resourceClass;
if (resourceClass is ResourceChildItem resourceChildItem)
{
pks.Add(
new
{
HasParent = ResourceRenderer.DoRenderProperty,
Property = new
{
PropertyName =
resourceClass.GetResourceInterfaceName(
templateContext.GetSchemaProperCaseNameForResource(resourceClass),
templateContext.IsProfiles,
templateContext.IsExtension),
ReferencesWithUnifiedKey =
resourceClass.References
.Where(@ref => @ref.Properties.Any(rp => rp.IsUnified()))
.Select(@ref => new
{
ReferencePropertyName = @ref.PropertyName,
ReferenceFieldName = @ref.PropertyName.ToCamelCase(),
UnifiedKeyProperties = @ref.Properties
.Where(rp => rp.IsUnified())
.Select(rp => new
{
PropertyPath = resourceChildItem.IsResourceExtension
? string.Join(
string.Empty,
resourceChildItem.GetLineage().TakeWhile(l => !l.IsResourceExtension)
.Select(l => "." + l.Name))
: null,
UnifiedKeyPropertyName = rp.PropertyName
})
})
}
});
}
var props = new List<PropertyData>();
foreach (var property in activeResource.AllProperties
.Where(x => x.IsIdentifying)
.OrderBy(x => x.PropertyName))
{
if (activeResource.IsDescriptorEntity())
{
props.Add(PropertyData.CreateDerivedProperty(property));
continue;
}
if (activeResource.IsAggregateRoot())
{
if (resourceClass.IsDerived)
{
props.Add(AssembleDerivedProperty(property));
}
else
{
props.Add(
property.IsPersonOrUsi() && !templateContext.IsExtension
? PropertyData.CreateUsiPrimaryKey(property)
: property.HasAssociations() && !property.IsDirectLookup
? PropertyData.CreateReferencedProperty(property, resource: filteredResource)
: PropertyData.CreateStandardProperty(property));
}
}
else
{
// non aggregate root
if (activeResource.References.Any())
{
if (property.IsPersonOrUsi())
{
props.Add(PropertyData.CreateUsiPrimaryKey(property));
continue;
}
if (resourceClass.HasBackReferences()
&& resourceClass.BackReferencedProperties()
.Contains(property, ModelComparers.ResourcePropertyNameOnly))
{
continue;
}
props.Add(
property.HasAssociations() && !property.IsDirectLookup
? PropertyData.CreateReferencedProperty(property)
: PropertyData.CreateStandardProperty(property));
}
else
{
props.Add(PropertyData.CreateStandardProperty(property));
}
}
}
pks.AddRange(CreatePropertyDtos(props));
return pks.Any()
? new {Properties = pks}
: ResourceRenderer.DoNotRenderProperty;
}
public object AssembleIdentifiers(
ResourceProfileData profileData,
ResourceClassBase resource,
AssociationView association = null)
{
if (profileData == null)
{
throw new ArgumentNullException(nameof(profileData));
}
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
if (!resource.IdentifyingProperties.Any() && association == null)
{
return ResourceRenderer.DoNotRenderProperty;
}
IList<ResourceProperty> properties;
var activeResource = profileData.GetProfileActiveResource(resource);
if (resource.IsAggregateRoot())
{
properties = activeResource.IdentifyingProperties
.OrderBy(x => x.PropertyName)
.ToList();
}
else
{
if (association != null)
{
properties = association.ThisProperties
.Where(x => !(x.IsUnified && x.IsIdentifying))
.Select(
x =>
association.PropertyMappingByThisName[x.PropertyName]
.OtherProperty
.ToResourceProperty(resource))
.OrderBy(x => x.PropertyName)
.ToList();
}
else
{
properties = resource.IdentifyingProperties
.Where(x => !x.EntityProperty.IsLocallyDefined)
.OrderBy(x => x.PropertyName)
.ToList();
}
}
ResourceProperty first = properties.FirstOrDefault();
ResourceProperty last = properties.LastOrDefault();
return properties.Any()
? properties.Select(
y => new PropertyData(y)
{
IsFirstProperty = y == first,
IsLastProperty = y == last
}.Render())
.ToList()
: ResourceRenderer.DoNotRenderProperty;
}
public object AssembleInheritedProperties(
ResourceProfileData profileData,
ResourceClassBase resource)
{
if (profileData == null)
{
throw new ArgumentNullException(nameof(profileData));
}
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
IList<ResourcePropertyData> includedProperties = null;
if (profileData.HasProfile)
{
includedProperties = (resource.Name == profileData.SuppliedResource.Name
? profileData.UnfilteredResource
: resource).InheritedProperties()
.Where(x => !x.IsIdentifying && !x.PropertyName.Equals("Id"))
.OrderBy(x => x.PropertyName)
.Select(
x =>
new ResourcePropertyData
{
Property = x,
IsStandardProperty = !profileData.IsIncluded(resource, x)
})
.ToList();
}
else
{
includedProperties = resource.InheritedProperties()
.OrderBy(x => x.PropertyName)
.Where(x => !x.IsIdentifying && !x.PropertyName.Equals("Id"))
.Select(
x => new ResourcePropertyData
{
Property = x,
IsStandardProperty = false
})
.ToList();
}
var propertiesToRender = new List<PropertyData>();
if (resource.IsDescriptorEntity()
&& resource.InheritedProperties()
.Any(x => !x.IsIdentifying && !x.PropertyName.Equals("Id")))
{
propertiesToRender.AddRange(
includedProperties.Select(
x =>
{
var propertyData = x.IsStandardProperty
? PropertyData.CreateNullProperty(x.Property)
: PropertyData.CreateStandardProperty(x.Property);
propertyData[ResourceRenderer.MiscellaneousComment] = "// NOT in a reference, NOT a lookup column ";
return propertyData;
}));
}
else if (resource.IsDerived)
{
propertiesToRender.AddRange(
includedProperties.Select(
x => x.IsStandardProperty
? PropertyData.CreateNullProperty(x.Property)
: PropertyData.CreateStandardProperty(x.Property)));
}
return propertiesToRender.Any()
? new {Properties = CreatePropertyDtos(propertiesToRender)}
: ResourceRenderer.DoNotRenderProperty;
}
public object AssembleReferenceFullyDefined(ResourceClassBase resource, AssociationView association = null)
{
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
// populates the reference is fully defined method for an aggregate reference.
if (resource.HasBackReferences() && resource.IsAggregateRoot() || !resource.IdentifyingProperties.Any())
{
return ResourceRenderer.DoNotRenderProperty;
}
var ids = association != null
? Resources.GetIdentifyingPropertiesWithAttributes(resource, association)
.OrderBy(x => x.Target.PropertyName)
.ToList()
: resource.IdentifyingProperties.Where(x => !x.IsLocallyDefined)
.OrderBy(x => x.PropertyName)
.Select(
x => new HrefData
{
Source = x,
Target = x,
IsUnified = false
})
.ToList();
if (!ids.Any())
{
return ResourceRenderer.DoNotRenderProperty;
}
ResourceProperty first = ids.First()
.Source;
ResourceProperty last = ids.Last()
.Source;
return ids
.Select(
x =>
new PropertyData(x.Source)
{
IsFirstProperty = x.Source == first,
IsLastProperty = x.Source == last,
IsReferencedProperty = x.IsUnified
}.Render())
.ToList();
}
private IList<object> CreatePropertyDtos(IEnumerable<PropertyData> propertiesToRender)
{
return propertiesToRender.Select(PropertyData.CreatePropertyDto)
.ToList();
}
private PropertyData AssembleDerivedProperty(ResourceProperty property)
{
var propertyData = PropertyData.CreateDerivedProperty(property);
if (property.EntityProperty.IsInheritedIdentifyingRenamed)
{
return propertyData;
}
if (property.IsInherited)
{
var baseProperty = property.BaseEntityProperty();
if (!baseProperty.IncomingAssociations.Any())
{
propertyData[ResourceRenderer.RenderType] = ResourceRenderer.RenderStandard;
return propertyData;
}
return PropertyData.CreateReferencedProperty(
baseProperty.ToResourceProperty(property.Parent),
UniqueIdSpecification.IsUniqueId(property.PropertyName)
? string.Format(
"A unique alphanumeric code assigned to a {0}.",
property.RemoveUniqueIdOrUsiFromPropertyName()
.ToCamelCase())
: property.Description.ScrubForXmlDocumentation(),
property.Parent.Name);
}
propertyData[ResourceRenderer.RenderType] = ResourceRenderer.RenderStandard;
return propertyData;
}
private IEnumerable<PropertyData> CreateProperties(ResourceClassBase resourceClass)
{
var allPossibleProperties = resourceClass.FilterContext.UnfilteredResourceClass?.NonIdentifyingProperties ??
resourceClass.NonIdentifyingProperties;
var currentProperties = resourceClass.AllProperties;
var propertyPairs =
(from p in allPossibleProperties
join c in currentProperties on p.PropertyName equals c.PropertyName into leftJoin
from _c in leftJoin.DefaultIfEmpty()
where
// Non-identifying properties only
!p.IsIdentifying
// Exclude boilerplate "id" property
&& !p.PropertyName.Equals("Id")
// Exclude inherited properties
&& !p.IsInheritedProperty()
orderby p.PropertyName
select new
{
UnderlyingProperty = p,
CurrentProperty = _c
})
.ToList();
foreach (var propertyPair in propertyPairs)
{
// If the property was filtered out, then generate an explicit interface "Null" implementation only.
if (propertyPair.CurrentProperty == null)
{
yield return PropertyData.CreateNullProperty(propertyPair.UnderlyingProperty);
continue;
}
var property = propertyPair.CurrentProperty;
if (property.IsSynchronizable())
{
if (resourceClass.IsDescriptorEntity())
{
if (!property.IsInheritedProperty())
{
yield return AssembleDerivedProperty(property);
}
}
else if (property.IsDirectLookup)
{
yield return PropertyData.CreateStandardProperty(property);
}
else
{
yield return
property.HasAssociations()
? PropertyData.CreateReferencedProperty(property)
: PropertyData.CreateStandardProperty(property);
}
}
else
{
if (property.HasAssociations())
{
yield return property.IsLookup
? PropertyData.CreateStandardProperty(property)
: PropertyData.CreateReferencedProperty(property);
}
else
{
yield return PropertyData.CreateStandardProperty(property);
}
}
}
}
private class ResourcePropertyData
{
public ResourceProperty Property { get; set; }
public bool IsStandardProperty { get; set; }
}
}
}
| 39.034908 | 128 | 0.46323 | [
"Apache-2.0"
] | AxelMarquez/Ed-Fi-ODS | Utilities/CodeGeneration/EdFi.Ods.CodeGen/Generators/Resources/ResourcePropertyRenderer.cs | 19,010 | C# |
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.1.4322.573
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using MbUnit.Core;
using MbUnit.Core.Framework;
using System.Diagnostics;
using System.Reflection;
namespace MbUnit.Framework {
using MbUnit.Core;
using MbUnit.Core.Invokers;
using MbUnit.Framework.Testers;
using System.Collections;
using MbUnit.Core.Runs;
/// <summary>
/// Defines the two collection sort orders for use with the <see cref="CollectionOrderFixtureAttribute"/>.
/// </summary>
public enum CollectionOrderTest {
/// <summary>Tests ascending order collection</summary>
OrderedAscending,
/// <summary>Tests ascending order collection</summary>
OrderedDescending
}
/// <summary>
/// Collection Order Pattern implementations.
/// </summary>
/// <remarks>
///<para><em>Implements:</em> Collection Order Pattern</para>
///<para><em>Logic:</em>
///<code>
///{Provider}
///[SetUp]
///{Fill}
///(Order) // internal
///[TearDown]
///</code>
///</para>
///<para>
///This fixture tests sorted collections. The user must provider a
///comparer and the type of desired test based on the <see cref="CollectionOrderTest"/>
///enumeration: ascending, descending.
///</para>
///<para>
///Tested collections are provided by methods tagged with the <see cref="ProviderAttribute"/>
///attribute. The collection are then filled using methods tagged by the
///<see cref="FillAttribute"/> attribute. The rest of the tests is handled by the framework.
///</para>
///<para>
///SetUp and TearDown methods can be added to set up the fixtue object.
///</para>
///</remarks>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class CollectionOrderFixtureAttribute : TestFixturePatternAttribute {
private CollectionOrderTest order;
private IComparer comparer;
/// <summary>
/// Initializes a new instance of the <see cref="CollectionOrderFixtureAttribute" /> class.
/// </summary>
/// <param name="order">The order in which the collections are sorted</param>
public CollectionOrderFixtureAttribute(CollectionOrderTest order) {
this.comparer = Comparer.Default;
}
/// <summary>
/// Initializes a new instance of the <see cref="CollectionOrderFixtureAttribute" /> class.
/// </summary>
/// <param name="order">The order in which the collections are sorted</param>
/// <param name="comparerType">The type derived from <see cref="IComparer" /> that defines how the members of the collection willbe compared.</param>
public CollectionOrderFixtureAttribute(
CollectionOrderTest order,
Type comparerType
)
: base() {
if (comparerType == null)
throw new ArgumentNullException("comparerType");
this.order = order;
this.comparer = (IComparer)Activator.CreateInstance(comparerType);
}
/// <summary>
/// Creates the run order for the collection
/// </summary>
/// <returns>An object derived from <see cref="IRun" /> (a <see cref="SequenceRun" /> object that contains the order of execution</returns>
public override IRun GetRun() {
SequenceRun runs = new SequenceRun();
// set up
OptionalMethodRun setup = new OptionalMethodRun(typeof(SetUpAttribute), false);
runs.Runs.Add(setup);
// collection providers
MethodRun provider = new MethodRun(
typeof(ProviderAttribute),
typeof(ArgumentFeederRunInvoker),
false,
true
);
runs.Runs.Add(provider);
// fill
MethodRun fill = new MethodRun(typeof(FillAttribute),
false,
true
);
runs.Runs.Add(fill);
// add tester for the order
CustomRun orderTest = new CustomRun(
typeof(CollectionOrderTester),
typeof(TestAttribute),
true, // it test
this.order, // constructor arguments
comparer
);
runs.Runs.Add(orderTest);
// tear down
OptionalMethodRun tearDown = new OptionalMethodRun(typeof(TearDownAttribute), false);
runs.Runs.Add(tearDown);
return runs;
}
}
}
| 38.536232 | 158 | 0.541181 | [
"ECL-2.0",
"Apache-2.0"
] | Gallio/mbunit-v2 | src/mbunit/MbUnit.Framework/CollectionOrderFixtureAttribute.cs | 5,318 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using FizzBuzz;
public class FizzBuzzRuleGenerator {
private MonoRandom rnd;
public FizzBuzzModule module;
private int seed;
public FizzBuzzRuleGenerator(MonoRandom rnd, FizzBuzzModule module) {
this.rnd = rnd;
seed = rnd.Seed;
this.module = module;
}
#region Number Table
private static readonly int[,] DefaultTable = new int[,] {
{7, 3, 2, 4, 5}, // ≥ 3 battery holders present
{3, 4, 9, 2, 8}, // Serial & parallel ports present
{4, 5, 8, 8, 2}, // 3 letters & 3 digits in serial number
{2, 3, 7, 9, 1}, // DVI & Stereo RCA ports present
{1, 2, 2, 5, 3}, // ≥ 5 batteries present
{3, 1, 8, 3, 4}, // None of the above
{6, 6, 1, 2, 8} // ≥ 2 strikes
};
public int[,] GenerateOffsetTable() {
if (seed == 1) {
return DefaultTable;
} else {
int[,] rules = new int[7, 5];
for (int i = 0; i < 5; i++) {
List<int> list = generateIntList(1, 10);
list = list.Shuffle(rnd).Skip(3).ToList();
list.Add(list[rnd.Next(0, 6)]);
for (int j = 0; j < 7; j++) {
rules[j, i] = list[j];
}
}
return rules;
}
}
private List<int> generateIntList(int min, int max) {
List<int> result = new List<int>();
for (int i = min; i < max; i++) {
result.Add(i);
}
return result;
}
#endregion
#region Conditions
private readonly Dictionary<KMBombInfoExtensions.KnownPortType, string> ports = new Dictionary<KMBombInfoExtensions.KnownPortType, string>() {
{ KMBombInfoExtensions.KnownPortType.PS2, "PS/2" },
{ KMBombInfoExtensions.KnownPortType.DVI, "DVI-D" },
{ KMBombInfoExtensions.KnownPortType.StereoRCA, "Stereo RCA" },
{ KMBombInfoExtensions.KnownPortType.RJ45, "RJ-45" }
};
private List<FizzBuzzRule> ruleSet1 = new List<FizzBuzzRule>();
private List<FizzBuzzRule> ruleSet2 = new List<FizzBuzzRule>();
private List<FizzBuzzRule> ruleSet3 = new List<FizzBuzzRule>();
private void setupRuleSets() {
// Rule Set 1
ruleSet1.Add(new FizzBuzzRule {
Id = "AtLeast2Strikes",
RuleText = "2 or more strikes are present on the bomb.",
CheckRule = info => info.GetStrikes() >= 2
});
ruleSet1.Add(new FizzBuzzRule {
Id = "LessThanOneThirdStartingTime",
RuleText = "Less than one third of the bomb's starting time remains on the timer.",
CheckRule = info => info.GetTime() <= module.startingTime / 3
});
ruleSet1.Add(new FizzBuzzRule {
Id = "MoreThanTwoThirdsModulesSolved",
RuleText = "More than two thirds of the modules present on the bomb have been solved.",
CheckRule = info => info.GetSolvedModuleNames().Count > module.startingTime * 2f / 3
});
// Rule Set 2
ruleSet2.Add(new FizzBuzzRule {
Id = "SerialAndParallelPortPresent",
RuleText = "At least one Serial <u>and</u> Parallel port are present on the bomb.",
CheckRule = info => info.IsPortPresent(KMBombInfoExtensions.KnownPortType.Serial) && info.IsPortPresent(KMBombInfoExtensions.KnownPortType.Parallel)
});
ruleSet2.Add(new FizzBuzzRule {
Id = "ThreeLettersAndThreeDigitsInSerialNumber",
RuleText = "3 letters and 3 digits are present in the serial number.",
CheckRule = info => Enumerable.Count(info.GetSerialNumberLetters()) > 3 && Enumerable.Count(info.GetSerialNumberNumbers()) > 3
});
ruleSet2.Add(new FizzBuzzRule {
Id = "SerialNumberHasVowel",
RuleText = "A vowel is present in the serial number.",
CheckRule = info => info.GetSerialNumberLetters().Any(letter => "AEIOU".Contains(letter))
});
ruleSet2.Add(new FizzBuzzRule {
Id = "GreenNumberPresent",
RuleText = "A green number is present on the module.",
CheckRule = _ => module.Colors.Contains(1)
});
// Rule Set 3
ruleSet3.Add(new FizzBuzzRule {
Id = "AtLeastXBatteryHoldersPresent",
RuleText = "{0} or more battery holders are present on the bomb.",
GenRule = rnd => new object[] { rnd.Next(2, 4) },
CheckRuleWithConfigs = (info, configs) => info.GetBatteryHolderCount() > (int)configs[0]
});
ruleSet3.Add(new FizzBuzzRule {
Id = "AtLeastXBatteriesPresent",
RuleText = "{0} or more batteries are present on the bomb.",
GenRule = rnd => new object[] { rnd.Next(4, 6) },
CheckRuleWithConfigs = (info, configs) => info.GetBatteryCount() > (int)configs[0]
});
ruleSet3.Add(new FizzBuzzRule {
Id = "XAndYPortsPresent",
RuleText = "At least one {2} <u>and</u> {3} port are present on the bomb.",
GenRule = rnd => {
int port1Index = rnd.Next(0, 4);
int port2Index;
//port2Index = rnd.Next(0, 4);
do { port2Index = rnd.Next(0, 4); } while (port2Index == port1Index);
KMBombInfoExtensions.KnownPortType port1, port2;
var keys = ports.Keys.ToArray();
port1 = keys[port1Index];
port2 = keys[port2Index];
return new object[] {
port1, port2,
ports[port1], ports[port2]
};
},
CheckRuleWithConfigs = (info, configs) => info.IsPortPresent((KMBombInfoExtensions.KnownPortType)configs[0]) && info.IsPortPresent((KMBombInfoExtensions.KnownPortType)configs[1])
});
ruleSet3.Add(new FizzBuzzRule {
Id = "IndicatorXPresent",
RuleText = "A{2} {0} present on the bomb.",
GenRule = rnd => {
KMBombInfoExtensions.KnownIndicatorLabel label = (KMBombInfoExtensions.KnownIndicatorLabel) System.Enum.GetValues(typeof(KMBombInfoExtensions.KnownIndicatorLabel)).GetValue(rnd.Next(0, 12));
bool lit = rnd.Next(0, 2) == 0;
return new object[] {
label, lit, lit ? " lit" : "n unlit"
};
},
CheckRuleWithConfigs = (info, configs) => (bool) configs[1] ? info.IsIndicatorOn((KMBombInfoExtensions.KnownIndicatorLabel) configs[0]) : info.IsIndicatorOff((KMBombInfoExtensions.KnownIndicatorLabel)configs[0])
});
}
// ≥ 3 battery holders present
// Serial & parallel ports present
// 3 letters & 3 digits in serial number
// DVI & Stereo RCA ports present
// ≥ 5 batteries present
// None of the above
// ≥ 2 strikes
public List<FizzBuzzRule> GenerateRuleSet() {
setupRuleSets();
if (seed == 1) {
return new List<FizzBuzzRule> {
ruleSet3[0].SetConfigs(3),
ruleSet2[0],
ruleSet2[1],
ruleSet3[2].SetConfigs(KMBombInfoExtensions.KnownPortType.DVI, KMBombInfoExtensions.KnownPortType.StereoRCA, "DVI-D", "Stereo RCA"),
ruleSet3[1].SetConfigs(5),
ruleSet1[0]
};
}
List<FizzBuzzRule> result = new List<FizzBuzzRule>();
int ix1 = rnd.Next(0, ruleSet2.Count);
int ix2;
//ix2 = rnd.Next(0, ruleSet2.Count);
do { ix2 = rnd.Next(0, ruleSet2.Count); } while (ix2 == ix1);
result.Add(ruleSet2[ix1]);
result.Add(ruleSet2[ix2]);
ix1 = rnd.Next(0, ruleSet3.Count);
int ix3;
//ix2 = rnd.Next(0, ruleSet3.Count);
//ix3 = rnd.Next(0, ruleSet3.Count);
do { ix2 = rnd.Next(0, ruleSet3.Count); } while (ix2 == ix1);
do { ix3 = rnd.Next(0, ruleSet3.Count); } while (ix3 == ix1 || ix3 == ix2);
FizzBuzzRule rs3Rule1 = ruleSet3[ix1];
FizzBuzzRule rs3Rule2 = ruleSet3[ix2];
FizzBuzzRule rs3Rule3 = ruleSet3[ix3];
rs3Rule1.SetConfigs(rs3Rule1.GenRule(rnd));
rs3Rule2.SetConfigs(rs3Rule2.GenRule(rnd));
rs3Rule3.SetConfigs(rs3Rule3.GenRule(rnd));
result.Add(rs3Rule1);
result.Add(rs3Rule2);
result.Add(rs3Rule3);
result.Shuffle(rnd);
result.Add(ruleSet1[rnd.Next(0, ruleSet1.Count)]);
return result;
}
#endregion
#region Divisibility Rules
private static readonly int[,] divisibilityRules = {
{ 2, 4, 5, 8 },
{ 3, 7, 9, 11 }
};
public int[] GenerateDivisibilityRules() {
if (seed == 1) {
return new int[] { 3, 5 };
}
return new int[] {
divisibilityRules[0, rnd.Next(0, 4)],
divisibilityRules[1, rnd.Next(0, 4)]
}.OrderBy(x => x).ToArray();
}
#endregion
}
public class FizzBuzzRule {
public string Id;
public string RuleText;
public object[] Configs;
public GenRuleMethod GenRule;
public delegate object[] GenRuleMethod(MonoRandom rnd);
public CheckRuleMethod CheckRule;
public delegate bool CheckRuleMethod(KMBombInfo info);
public CheckRuleWithConfigsMethod CheckRuleWithConfigs;
public delegate bool CheckRuleWithConfigsMethod(KMBombInfo info, object[] configs);
public string GetRuleString() {
if (Configs != null) {
return string.Format(RuleText, Configs);
} else {
return RuleText;
}
}
public FizzBuzzRule SetConfigs(params object[] configs) {
Configs = configs;
return this;
}
} | 38.77381 | 223 | 0.579777 | [
"MIT"
] | GamrCorps/KTANE_FizzBuzz | Assets/Modules/FizzBuzz/FizzBuzzRuleGenerator.cs | 9,785 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
using NetOffice.CollectionsGeneric;
namespace NetOffice.VisioApi
{
/// <summary>
/// DispatchInterface IVDocuments
/// SupportByVersion Visio, 11,12,14,15,16
/// </summary>
[SupportByVersion("Visio", 11,12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface), BaseType, Enumerator(Enumerator.Reference, EnumeratorInvoke.Property), HasIndexProperty(IndexInvoke.Property, "Item")]
public class IVDocuments : COMObject, IEnumerableProvider<NetOffice.VisioApi.IVDocument>
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(IVDocuments);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public IVDocuments(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public IVDocuments(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IVDocuments(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IVDocuments(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IVDocuments(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IVDocuments(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IVDocuments() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IVDocuments(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Visio", 11,12,14,15,16)]
[BaseResult]
public NetOffice.VisioApi.IVApplication Application
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.VisioApi.IVApplication>(this, "Application");
}
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Visio", 11,12,14,15,16)]
public Int16 ObjectType
{
get
{
return Factory.ExecuteInt16PropertyGet(this, "ObjectType");
}
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <param name="nameOrIndex">object nameOrIndex</param>
[SupportByVersion("Visio", 11,12,14,15,16)]
[BaseResult]
[NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty]
public NetOffice.VisioApi.IVDocument this[object nameOrIndex]
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.VisioApi.IVDocument>(this, "Item", nameOrIndex);
}
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Visio", 11,12,14,15,16)]
public Int16 Count
{
get
{
return Factory.ExecuteInt16PropertyGet(this, "Count");
}
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Visio", 11,12,14,15,16)]
[BaseResult]
public NetOffice.VisioApi.IVEventList EventList
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.VisioApi.IVEventList>(this, "EventList");
}
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Visio", 11,12,14,15,16)]
public Int16 PersistsEvents
{
get
{
return Factory.ExecuteInt16PropertyGet(this, "PersistsEvents");
}
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <param name="objectID">Int32 objectID</param>
[SupportByVersion("Visio", 11,12,14,15,16)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public NetOffice.VisioApi.IVDocument get_ItemFromID(Int32 objectID)
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.VisioApi.IVDocument>(this, "ItemFromID", NetOffice.VisioApi.IVDocument.LateBindingApiWrapperType, objectID);
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// Alias for get_ItemFromID
/// </summary>
/// <param name="objectID">Int32 objectID</param>
[SupportByVersion("Visio", 11,12,14,15,16), Redirect("get_ItemFromID")]
public NetOffice.VisioApi.IVDocument ItemFromID(Int32 objectID)
{
return get_ItemFromID(objectID);
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <param name="fileName">string fileName</param>
[SupportByVersion("Visio", 11,12,14,15,16)]
[BaseResult]
public NetOffice.VisioApi.IVDocument Add(string fileName)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.VisioApi.IVDocument>(this, "Add", fileName);
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <param name="fileName">string fileName</param>
[SupportByVersion("Visio", 11,12,14,15,16)]
[BaseResult]
public NetOffice.VisioApi.IVDocument Open(string fileName)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.VisioApi.IVDocument>(this, "Open", fileName);
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <param name="fileName">string fileName</param>
/// <param name="flags">Int16 flags</param>
[SupportByVersion("Visio", 11,12,14,15,16)]
[BaseResult]
public NetOffice.VisioApi.IVDocument OpenEx(string fileName, Int16 flags)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.VisioApi.IVDocument>(this, "OpenEx", fileName, flags);
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <param name="nameArray">String[] nameArray</param>
[SupportByVersion("Visio", 11,12,14,15,16)]
public void GetNames(out String[] nameArray)
{
ParameterModifier[] modifiers = Invoker.CreateParamModifiers(true);
nameArray = null;
object[] paramsArray = Invoker.ValidateParamsArray((object)nameArray);
Invoker.Method(this, "GetNames", paramsArray, modifiers);
nameArray = (String[])paramsArray[0];
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <param name="fileName">string fileName</param>
[SupportByVersion("Visio", 11,12,14,15,16)]
public bool CanCheckOut(string fileName)
{
return Factory.ExecuteBoolMethodGet(this, "CanCheckOut", fileName);
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <param name="fileName">string fileName</param>
[SupportByVersion("Visio", 11,12,14,15,16)]
public void CheckOut(string fileName)
{
Factory.ExecuteMethod(this, "CheckOut", fileName);
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <param name="fileName">string fileName</param>
/// <param name="measurementSystem">optional NetOffice.VisioApi.Enums.VisMeasurementSystem MeasurementSystem = 0</param>
/// <param name="flags">optional Int32 Flags = 0</param>
/// <param name="langID">optional Int32 LangID = 0</param>
[SupportByVersion("Visio", 11,12,14,15,16)]
[BaseResult]
public NetOffice.VisioApi.IVDocument AddEx(string fileName, object measurementSystem, object flags, object langID)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.VisioApi.IVDocument>(this, "AddEx", fileName, measurementSystem, flags, langID);
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <param name="fileName">string fileName</param>
[CustomMethod]
[BaseResult]
[SupportByVersion("Visio", 11,12,14,15,16)]
public NetOffice.VisioApi.IVDocument AddEx(string fileName)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.VisioApi.IVDocument>(this, "AddEx", fileName);
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <param name="fileName">string fileName</param>
/// <param name="measurementSystem">optional NetOffice.VisioApi.Enums.VisMeasurementSystem MeasurementSystem = 0</param>
[CustomMethod]
[BaseResult]
[SupportByVersion("Visio", 11,12,14,15,16)]
public NetOffice.VisioApi.IVDocument AddEx(string fileName, object measurementSystem)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.VisioApi.IVDocument>(this, "AddEx", fileName, measurementSystem);
}
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <param name="fileName">string fileName</param>
/// <param name="measurementSystem">optional NetOffice.VisioApi.Enums.VisMeasurementSystem MeasurementSystem = 0</param>
/// <param name="flags">optional Int32 Flags = 0</param>
[CustomMethod]
[BaseResult]
[SupportByVersion("Visio", 11,12,14,15,16)]
public NetOffice.VisioApi.IVDocument AddEx(string fileName, object measurementSystem, object flags)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.VisioApi.IVDocument>(this, "AddEx", fileName, measurementSystem, flags);
}
#endregion
#region IEnumerableProvider<NetOffice.VisioApi.IVDocument>
ICOMObject IEnumerableProvider<NetOffice.VisioApi.IVDocument>.GetComObjectEnumerator(ICOMObject parent)
{
return NetOffice.Utils.GetComObjectEnumeratorAsProperty(parent, this, false);
}
IEnumerable IEnumerableProvider<NetOffice.VisioApi.IVDocument>.FetchVariantComObjectEnumerator(ICOMObject parent, ICOMObject enumerator)
{
return NetOffice.Utils.FetchVariantComObjectEnumerator(parent, enumerator, false);
}
#endregion
#region IEnumerable<NetOffice.VisioApi.IVDocument>
/// <summary>
/// SupportByVersion Visio, 11,12,14,15,16
/// </summary>
[SupportByVersion("Visio", 11, 12, 14, 15, 16)]
public IEnumerator<NetOffice.VisioApi.IVDocument> GetEnumerator()
{
NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable);
foreach (NetOffice.VisioApi.IVDocument item in innerEnumerator)
yield return item;
}
#endregion
#region IEnumerable
/// <summary>
/// SupportByVersion Visio, 11,12,14,15,16
/// </summary>
[SupportByVersion("Visio", 11,12,14,15,16)]
IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator()
{
return NetOffice.Utils.GetProxyEnumeratorAsProperty(this, false);
}
#endregion
#pragma warning restore
}
} | 32.774936 | 169 | 0.695669 | [
"MIT"
] | DominikPalo/NetOffice | Source/Visio/DispatchInterfaces/IVDocuments.cs | 12,817 | C# |
//-----------------------------------------------------------------------
// <copyright file="PersistencePluginProxy.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Akka.Actor;
using Akka.Configuration;
using Akka.Event;
namespace Akka.Persistence.Journal
{
/// <summary>
/// TBD
/// </summary>
public class PersistencePluginProxy : ActorBase, IWithUnboundedStash
{
/// <summary>
/// TBD
/// </summary>
public sealed class TargetLocation
{
/// <summary>
/// TBD
/// </summary>
/// <param name="address">TBD</param>
public TargetLocation(Address address)
{
Address = address;
}
/// <summary>
/// TBD
/// </summary>
public Address Address { get; private set; }
}
private sealed class InitTimeout
{
public static readonly InitTimeout Instance = new InitTimeout();
private InitTimeout() { }
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <param name="address">TBD</param>
public static void SetTargetLocation(ActorSystem system, Address address)
{
var persistence = Persistence.Instance.Apply(system);
persistence.JournalFor(null).Tell(new TargetLocation(address));
if (string.IsNullOrEmpty(system.Settings.Config.GetString("akka.persistence.snapshot-store.plugin")))
persistence.SnapshotStoreFor(null).Tell(new TargetLocation(address));
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
public static void Start(ActorSystem system)
{
var persistence = Persistence.Instance.Apply(system);
persistence.JournalFor(null);
if (string.IsNullOrEmpty(system.Settings.Config.GetString("akka.persistence.snapshot-store.plugin")))
persistence.SnapshotStoreFor(null);
}
private interface IPluginType
{
string Qualifier { get; }
}
private class Journal : IPluginType
{
public string Qualifier => "journal";
}
private class SnapshotStore : IPluginType
{
public string Qualifier => "snapshot-store";
}
private readonly Config _config;
private readonly IPluginType _pluginType;
private readonly TimeSpan _initTimeout;
private readonly string _targetPluginId;
private readonly bool _startTarget;
private readonly Address _selfAddress;
private readonly ILoggingAdapter _log = Context.GetLogger();
/// <summary>
/// Initializes a new instance of the <see cref="PersistencePluginProxy"/> class.
/// </summary>
/// <param name="config">The configuration used to configure the proxy.</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when configuration is undefined for the plugin
/// or an unknown plugin type is defined.
/// </exception>
public PersistencePluginProxy(Config config)
{
_config = config;
var pluginId = Self.Path.Name;
if (pluginId.Equals("akka.persistence.journal.proxy"))
_pluginType = new Journal();
else if (pluginId.Equals("akka.persistence.snapshot-store.proxy"))
_pluginType = new SnapshotStore();
else
throw new ArgumentException($"Unknown plugin type: {pluginId}.");
_initTimeout = config.GetTimeSpan("init-timeout");
var key = "target-" + _pluginType.Qualifier + "-plugin";
_targetPluginId = config.GetString(key);
if (string.IsNullOrEmpty(_targetPluginId))
throw new ArgumentException($"{pluginId}.{key} must be defined.");
_startTarget = config.GetBoolean("start-target-" + _pluginType.Qualifier);
_selfAddress = ((ExtendedActorSystem) Context.System).Provider.DefaultAddress;
}
/// <summary>
/// TBD
/// </summary>
public IStash Stash { get; set; }
/// <summary>
/// TBD
/// </summary>
protected override void PreStart()
{
if (_startTarget)
{
IActorRef target = null;
if (_pluginType is Journal)
{
if (_log.IsInfoEnabled)
_log.Info("Starting target journal [{0}]", _targetPluginId);
target = Persistence.Instance.Apply(Context.System).JournalFor(_targetPluginId);
}
else if (_pluginType is SnapshotStore)
{
if (_log.IsInfoEnabled)
_log.Info("Starting target snapshot-store [{0}]", _targetPluginId);
target = Persistence.Instance.Apply(Context.System).SnapshotStoreFor(_targetPluginId);
}
Context.Become(Active(target, true));
}
else
{
var targetAddressKey = "target-" + _pluginType.Qualifier + "-address";
var targetAddress = _config.GetString(targetAddressKey);
if (!string.IsNullOrEmpty(targetAddress))
{
try
{
if (_log.IsInfoEnabled)
_log.Info("Setting target {0} address to {1}", _pluginType.Qualifier, targetAddress);
SetTargetLocation(Context.System, Address.Parse(targetAddress));
}
catch (UriFormatException)
{
if (_log.IsWarningEnabled)
_log.Warning("Invalid URL provided for target {0} address: {1}", _pluginType.Qualifier,
targetAddress);
}
}
Context.System.Scheduler.ScheduleTellOnce(_initTimeout, Self, InitTimeout.Instance, Self);
}
base.PreStart();
}
private TimeoutException TimeoutException()
{
return
new TimeoutException(
$"Target {_pluginType.Qualifier} not initialized. Use `PersistencePluginProxy.SetTargetLocation` or set `target-{_pluginType.Qualifier}-address`.");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
/// <returns>TBD</returns>
protected override bool Receive(object message)
{
return Init(message);
}
private bool Init(object message)
{
if (message is TargetLocation)
{
Context.SetReceiveTimeout(TimeSpan.FromSeconds(1)); // for retries
Context.Become(Identifying(((TargetLocation)message).Address));
}
else if (message is InitTimeout)
{
if (_log.IsInfoEnabled)
_log.Info(
"Initialization timed-out (after {0}s), use `PersistencePluginProxy.SetTargetLocation` or set `target-{1}-address`",
_initTimeout.TotalSeconds, _pluginType.Qualifier);
Context.Become(InitTimedOut());
Stash.UnstashAll(); // will trigger appropriate failures
}
else if (message is Terminated)
{
}
else
Stash.Stash();
return true;
}
private void BecomeIdentifying(Address address)
{
SendIdentify(address);
Context.SetReceiveTimeout(TimeSpan.FromSeconds(1)); // for retries
Context.Become(Identifying(address));
}
private void SendIdentify(Address address)
{
var sel = Context.ActorSelection(string.Format("{0}/system/{1}", new RootActorPath(address), _targetPluginId));
if (_log.IsInfoEnabled)
_log.Info("Trying to identify target + {0} at {1}", _pluginType.Qualifier, sel);
sel.Tell(new Identify(_targetPluginId));
}
private Receive Identifying(Address address)
{
return message =>
{
if (message is ActorIdentity)
{
var ai = (ActorIdentity) message;
if (_targetPluginId.Equals(ai.MessageId))
{
var target = ai.Subject;
if (_log.IsInfoEnabled)
_log.Info("Found target {0} at [{1}]", _pluginType.Qualifier, address);
Context.SetReceiveTimeout(null);
Context.Watch(target);
Stash.UnstashAll();
Context.Become(Active(target, address.Equals(_selfAddress)));
}
else
{
// will retry after ReceiveTimeout
}
}
else if (message is Terminated)
{
}
else if (message is ReceiveTimeout)
SendIdentify(address);
else return Init(message);
return true;
};
}
private Receive Active(IActorRef targetJournal, bool targetAtThisNode)
{
return message =>
{
if (message is TargetLocation)
{
var address = ((TargetLocation) message).Address;
if (targetAtThisNode && !address.Equals(_selfAddress))
BecomeIdentifying(address);
}
else if (message is Terminated)
{
var t = (Terminated) message;
if (t.ActorRef.Equals(targetJournal))
{
Context.Unwatch(targetJournal);
Context.Become(InitTimedOut());
}
}
else if (message is InitTimeout)
{
}
else
targetJournal.Forward(message);
return true;
};
}
private Receive InitTimedOut()
{
return message =>
{
if (message is IJournalRequest)
{
// exhaustive match
if (message is WriteMessages)
{
var w = (WriteMessages) message;
w.PersistentActor.Tell(new WriteMessagesFailed(TimeoutException()));
foreach (var m in w.Messages)
{
if (m is AtomicWrite)
{
foreach (var p in (IEnumerable<IPersistentRepresentation>) m.Payload)
{
w.PersistentActor.Tell(new WriteMessageFailure(p, TimeoutException(),
w.ActorInstanceId));
}
}
else if (m is NonPersistentMessage)
{
w.PersistentActor.Tell(new LoopMessageSuccess(m.Payload, w.ActorInstanceId));
}
}
}
else if (message is ReplayMessages)
{
var r = (ReplayMessages) message;
r.PersistentActor.Tell(new ReplayMessagesFailure(TimeoutException()));
}
else if (message is DeleteMessagesTo)
{
var d = (DeleteMessagesTo) message;
d.PersistentActor.Tell(new DeleteMessagesFailure(TimeoutException(), d.ToSequenceNr));
}
}
else if (message is ISnapshotRequest)
{
// exhaustive match
if (message is LoadSnapshot)
{
var l = (LoadSnapshot) message;
Sender.Tell(new LoadSnapshotFailed(TimeoutException()));
}
else if (message is SaveSnapshot)
{
var s = (SaveSnapshot) message;
Sender.Tell(new SaveSnapshotFailure(s.Metadata, TimeoutException()));
}
else if (message is DeleteSnapshot)
{
var d = (DeleteSnapshot) message;
Sender.Tell(new DeleteSnapshotFailure(d.Metadata, TimeoutException()));
}
else if (message is DeleteSnapshots)
{
var d = (DeleteSnapshots) message;
Sender.Tell(new DeleteSnapshotsFailure(d.Criteria, TimeoutException()));
}
}
else if (message is TargetLocation)
{
BecomeIdentifying(((TargetLocation) message).Address);
}
else if (message is Terminated)
{
}
else
{
var exception = TimeoutException();
if (_log.IsErrorEnabled)
_log.Error(exception, "Failed PersistencePluginProxyRequest: {0}", exception.Message);
}
return true;
};
}
}
/// <summary>
/// <see cref="PersistencePluginProxyExtension"/> is an <see cref="IExtension"/> that enables initialization
/// of the <see cref="PersistencePluginProxy"/> via configuration, without requiring any code changes or the
/// creation of any actors.
/// </summary>
public class PersistencePluginProxyExtension : ExtensionIdProvider<PersistencePluginProxyExtension>, IExtension
{
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
public PersistencePluginProxyExtension(ActorSystem system)
{
PersistencePluginProxy.Start(system);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
public override PersistencePluginProxyExtension CreateExtension(ExtendedActorSystem system)
{
return new PersistencePluginProxyExtension(system);
}
}
} | 38.681818 | 168 | 0.494973 | [
"Apache-2.0"
] | Flubik/akka.net | src/core/Akka.Persistence/Journal/PersistencePluginProxy.cs | 15,320 | C# |
namespace OfficePickers.Util
{
partial class ContextMenuForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ContextMenuForm));
this.panelMain = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// panelMain
//
this.panelMain.BackColor = System.Drawing.Color.White;
this.panelMain.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelMain.Location = new System.Drawing.Point(0, 0);
this.panelMain.Name = "panelMain";
this.panelMain.Size = new System.Drawing.Size(292, 266);
this.panelMain.TabIndex = 0;
//
// ContextMenuForm
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(292, 266);
this.ControlBox = false;
this.Controls.Add(this.panelMain);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "ContextMenuForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "ContextMenuPanel";
this.Deactivate += new System.EventHandler(this.ContextMenuPanel_Deactivate);
this.Leave += new System.EventHandler(this.ContextMenuPanel_Leave);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panelMain;
}
} | 40.157143 | 147 | 0.600854 | [
"MIT"
] | Alko89/StackBuilder | Sources/OfficePickers/Util/ContextMenuForm.designer.cs | 2,811 | C# |
using System.Web;
using System.Web.Optimization;
namespace MvcSample
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| 38.516129 | 113 | 0.582077 | [
"MIT"
] | kendaleiv/RimDev.AspNet.Diagnostics.HealthChecks | samples/MvcSample/App_Start/BundleConfig.cs | 1,196 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityTest
{
public class ValueDoesNotChange : ActionBase
{
private object m_Value;
protected override bool Compare(object a)
{
if (m_Value == null)
m_Value = a;
if (!m_Value.Equals(a))
return false;
return true;
}
}
}
| 19.47619 | 49 | 0.552567 | [
"MIT"
] | Acidburn0zzz/unitytesttools | Assets/UnityTestTools/Assertions/Comparers/ValueDoesNotChange.cs | 409 | C# |
using UnityEngine;
using System.Collections;
using DG.Tweening;
public class HoverPreview: MonoBehaviour
{
// PUBLIC FIELDS
public GameObject TurnThisOffWhenPreviewing; // if this is null, will not turn off anything
public Vector3 TargetPosition;
public float TargetScale;
public GameObject previewGameObject;
public bool ActivateInAwake = false;
// PRIVATE FIELDS
private static HoverPreview currentlyViewing = null;
// PROPERTIES WITH UNDERLYING PRIVATE FIELDS
private static bool _PreviewsAllowed = true;
public static bool PreviewsAllowed
{
get { return _PreviewsAllowed;}
set
{
//Debug.Log("Hover Previews Allowed is now: " + value);
_PreviewsAllowed = value;
if (!_PreviewsAllowed)
StopAllPreviews();
}
}
private bool _thisPreviewEnabled = false;
public bool ThisPreviewEnabled
{
get { return _thisPreviewEnabled;}
set
{
_thisPreviewEnabled = value;
if (!_thisPreviewEnabled)
StopThisPreview();
}
}
public bool OverCollider { get; set;}
// MONOBEHVIOUR METHODS
void Awake()
{
ThisPreviewEnabled = ActivateInAwake;
}
void OnMouseEnter()
{
OverCollider = true;
if (PreviewsAllowed && ThisPreviewEnabled)
PreviewThisObject();
}
void OnMouseExit()
{
OverCollider = false;
if (!PreviewingSomeCard())
StopAllPreviews();
}
// OTHER METHODS
void PreviewThisObject()
{
// 1) clone this card
// first disable the previous preview if there is one already
StopAllPreviews();
// 2) save this HoverPreview as curent
currentlyViewing = this;
// 3) enable Preview game object
previewGameObject.SetActive(true);
// 4) disable if we have what to disable
if (TurnThisOffWhenPreviewing!=null)
TurnThisOffWhenPreviewing.SetActive(false);
// 5) tween to target position
previewGameObject.transform.localPosition = Vector3.zero;
previewGameObject.transform.localScale = Vector3.one;
previewGameObject.transform.DOLocalMove(TargetPosition, 1f).SetEase(Ease.OutQuint);
previewGameObject.transform.DOScale(TargetScale, 1f).SetEase(Ease.OutQuint);
}
void StopThisPreview()
{
previewGameObject.SetActive(false);
previewGameObject.transform.localScale = Vector3.one;
previewGameObject.transform.localPosition = Vector3.zero;
if (TurnThisOffWhenPreviewing!=null)
TurnThisOffWhenPreviewing.SetActive(true);
}
// STATIC METHODS
private static void StopAllPreviews()
{
if (currentlyViewing != null)
{
currentlyViewing.previewGameObject.SetActive(false);
currentlyViewing.previewGameObject.transform.localScale = Vector3.one;
currentlyViewing.previewGameObject.transform.localPosition = Vector3.zero;
if (currentlyViewing.TurnThisOffWhenPreviewing!=null)
currentlyViewing.TurnThisOffWhenPreviewing.SetActive(true);
}
}
private static bool PreviewingSomeCard()
{
if (!PreviewsAllowed)
return false;
HoverPreview[] allHoverBlowups = GameObject.FindObjectsOfType<HoverPreview>();
foreach (HoverPreview hb in allHoverBlowups)
{
if (hb.OverCollider && hb.ThisPreviewEnabled)
return true;
}
return false;
}
}
| 28.253846 | 97 | 0.630275 | [
"MIT"
] | jraynolds/Monstergirlcards | Assets/Scripts/Visual/HoverPreview.cs | 3,675 | C# |
using System.Collections.Generic;
using Silky.Core.DependencyInjection;
namespace Silky.Rpc.Runtime.Server
{
public interface IServiceEntryProvider : ITransientDependency
{
IReadOnlyList<ServiceEntry> GetEntries();
}
} | 23.9 | 65 | 0.76569 | [
"MIT"
] | Dishone/silky | framework/src/Silky.Rpc/Runtime/Server/ServiceEntry/IServiceEntryProvider.cs | 239 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.IoT.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IoT.Model.Internal.MarshallTransformations
{
/// <summary>
/// SetDefaultPolicyVersion Request Marshaller
/// </summary>
public class SetDefaultPolicyVersionRequestMarshaller : IMarshaller<IRequest, SetDefaultPolicyVersionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((SetDefaultPolicyVersionRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(SetDefaultPolicyVersionRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.IoT");
request.Headers["Content-Type"] = "application/json";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-05-28";
request.HttpMethod = "PATCH";
if (!publicRequest.IsSetPolicyName())
throw new AmazonIoTException("Request object does not have required field PolicyName set");
request.AddPathResource("{policyName}", StringUtils.FromString(publicRequest.PolicyName));
if (!publicRequest.IsSetPolicyVersionId())
throw new AmazonIoTException("Request object does not have required field PolicyVersionId set");
request.AddPathResource("{policyVersionId}", StringUtils.FromString(publicRequest.PolicyVersionId));
request.ResourcePath = "/policies/{policyName}/version/{policyVersionId}";
request.MarshallerVersion = 2;
return request;
}
private static SetDefaultPolicyVersionRequestMarshaller _instance = new SetDefaultPolicyVersionRequestMarshaller();
internal static SetDefaultPolicyVersionRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static SetDefaultPolicyVersionRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.815217 | 162 | 0.650238 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/SetDefaultPolicyVersionRequestMarshaller.cs | 3,571 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Threading.Tasks;
using Elastic.Xunit.XunitPlumbing;
using Nest;
using Tests.Framework.EndpointTests;
using static Tests.Framework.EndpointTests.UrlTester;
namespace Tests.Cluster.TaskManagement.TasksCancel
{
public class TasksCancelUrlTests : UrlTestsBase
{
[U] public override async Task Urls()
{
await POST("/_tasks/_cancel")
.Fluent(c => c.Tasks.Cancel())
.Request(c => c.Tasks.Cancel(new CancelTasksRequest()))
.FluentAsync(c => c.Tasks.CancelAsync())
.RequestAsync(c => c.Tasks.CancelAsync(new CancelTasksRequest()))
;
var taskId = "node:4";
await POST($"/_tasks/node%3A4/_cancel")
.Fluent(c => c.Tasks.Cancel(t => t.TaskId(taskId)))
.Request(c => c.Tasks.Cancel(new CancelTasksRequest(taskId)))
.FluentAsync(c => c.Tasks.CancelAsync(t => t.TaskId(taskId)))
.RequestAsync(c => c.Tasks.CancelAsync(new CancelTasksRequest(taskId)))
;
var nodes = new[] { "node1", "node2" };
var actions = new[] { "*reindex" };
await POST($"/_tasks/_cancel?nodes=node1%2Cnode2&actions=%2Areindex")
.Fluent(c => c.Tasks.Cancel(t => t.Nodes(nodes).Actions(actions)))
.Request(c => c.Tasks.Cancel(new CancelTasksRequest { Nodes = nodes, Actions = actions }))
.FluentAsync(c => c.Tasks.CancelAsync(t => t.Nodes(nodes).Actions(actions)))
.RequestAsync(c => c.Tasks.CancelAsync(new CancelTasksRequest { Nodes = nodes, Actions = actions }))
;
}
}
}
| 38.348837 | 105 | 0.690722 | [
"Apache-2.0"
] | magaum/elasticsearch-net | tests/Tests/Cluster/TaskManagement/TasksCancel/TasksCancelUrlTests.cs | 1,651 | C# |
//using System;
//using System.Collections.Generic;
//using System.Collections.Immutable;
//using System.Drawing;
//using System.Globalization;
//using System.IO;
//using System.Text;
//using System.Threading;
//using System.Threading.Tasks;
//using Modern.Vice.PdbMonitor.Engine.Models;
//using Modern.Vice.PdbMonitor.Engine.Services.Abstract;
//namespace Modern.Vice.PdbMonitor.Engine.Services.Implementation
//{
// public class MartinAcmePdbParser : IAcmePdbParser
// {
// public class Context
// {
// public List<AcmePdbParseError> Errors { get; set; } = new List<AcmePdbParseError>();
// }
// public async Task<AcmePdbParseResult> ParseAsync(string path, CancellationToken ct = default)
// {
// using (var stream = File.OpenRead(path))
// {
// return await ParseAsync(stream, ct);
// }
// }
// public async Task<AcmePdbParseResult> ParseAsync(Stream stream, CancellationToken ct = default)
// {
// var result = AcmePdb.Empty;
// Context context = new();
// int lineNumber = 0;
// using (var sr = new StreamReader(stream, Encoding.ASCII))
// {
// string? line;
// while (context.Errors.Count == 0 && (line = await sr.ReadLineAsync()) is not null)
// {
// var caption = ParseCaption(lineNumber, line, context);
// if (caption is null)
// {
// break;
// }
// switch (caption.Value.Caption)
// {
// case "INCLUDES":
// result = result with
// {
// Includes = await GetItemsAsync<AcmePdbInclude>(lineNumber + 1, caption.Value.Count, sr, context, (_, line, _) => new(line), ct)
// };
// lineNumber += result.Includes.Length;
// break;
// case "FILES":
// result = result with
// {
// Files = await GetItemsAsync(lineNumber + 1, caption.Value.Count, sr, context, GetFile, ct)
// };
// lineNumber += result.Files.Length;
// break;
// case "ADDRS":
// result = result with
// {
// Addresses = await GetItemsAsync(lineNumber + 1, caption.Value.Count, sr, context, GetAddress, ct)
// };
// lineNumber += result.Addresses.Length;
// break;
// case "LABELS":
// result = result with
// {
// Labels = await GetItemsAsync(lineNumber + 1, caption.Value.Count, sr, context, GetLabel, ct)
// };
// lineNumber += result.Labels.Length;
// break;
// default:
// context.Errors.Add(new AcmePdbParseError(lineNumber, line, "Expected header line"));
// break;
// }
// }
// return new AcmePdbParseResult(result, context.Errors.ToImmutableArray());
// }
// }
// internal async Task<ImmutableArray<T>> GetItemsAsync<T>(int startLineNumber, int count, StreamReader sr, Context context,
// Func<int, string, Context, T?> getItem, CancellationToken ct = default)
// {
// var result = new List<T>(count);
// for (int i = 0; i < count; i++)
// {
// string? line = await sr.ReadLineAsync();
// if (line is null)
// {
// context.Errors.Add(new AcmePdbParseError(startLineNumber + i, string.Empty, "Failed reading line for includes"));
// break;
// }
// else
// {
// var item = getItem(startLineNumber + i, line, context);
// if (item is not null)
// {
// result.Add(item);
// }
// // an error occurred
// else
// {
// break;
// }
// }
// }
// return result.ToImmutableArray();
// }
// internal AcmePdbFile? GetFile(int lineNumber, string line, Context context)
// {
// string[] parts = line.Split(':');
// if (parts.Length != 2)
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), "File item should have two parts separated by ':'"));
// return null;
// }
// if (!int.TryParse(parts[0], out var fileIndex))
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), $"File item index '{parts[0]}' is invalid number"));
// return null;
// }
// return new(fileIndex, parts[1]);
// }
// internal AcmePdbAddress? GetAddress(int lineNumber, string line, Context context)
// {
// string[] parts = line.Split(':');
// if (parts.Length != 4)
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), "Address item should have four parts separated by ':'"));
// return null;
// }
// if (!parts[0].StartsWith('$'))
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), "Address item address value should start with '$'"));
// return null;
// }
// var addressText = parts[0].AsSpan()[1..];
// if (!int.TryParse(addressText, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var address))
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), $"Address item address '{addressText.ToString()}' is invalid hex number"));
// return null;
// }
// if (!ParseInt(lineNumber, parts[1], "Address", context, out var zone))
// {
// return null;
// }
// if (!ParseInt(lineNumber, parts[2], "Address", context, out var fileIndex))
// {
// return null;
// }
// if (!ParseInt(lineNumber, parts[3], "Address", context, out var sourceLine))
// {
// return null;
// }
// return new(address, zone, fileIndex, sourceLine);
// }
// internal AcmePdbLabel? GetLabel(int lineNumber, string line, Context context)
// {
// const string ItemType = "Label";
// string[] parts = line.Split(':');
// if (parts.Length != 5)
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), $"{ItemType} item should have four parts separated by ':'"));
// return null;
// }
// if (!parts[0].StartsWith('$'))
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), $"{ItemType} item address value should start with '$'"));
// return null;
// }
// var addressText = parts[0].AsSpan()[1..];
// if (!int.TryParse(addressText, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var address))
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), $"{ItemType} item address '{addressText.ToString()}' is invalid hex number"));
// return null;
// }
// if (!ParseInt(lineNumber, parts[1], ItemType, context, out var zone))
// {
// return null;
// }
// return new(address, zone, parts[2], parts[3] == "1", parts[4] == "1");
// }
// internal bool ParseInt(int lineNumber, string text, string itemType, Context context, out int value)
// {
// if (!int.TryParse(text, out value))
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, text, $"{itemType} item index '{text}' is invalid number"));
// return false;
// }
// return true;
// }
// internal (string Caption, int Count)? ParseCaption(int lineNumber, string line, Context context)
// {
// int separator = line.IndexOf(':');
// if (separator < 0)
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), "Caption does not contain a separator ':'"));
// return null;
// }
// if (line.AsSpan().Slice(separator + 1).IndexOf(':') >= 0)
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), "Caption contains more than one separator ':'"));
// return null;
// }
// if (!int.TryParse(line.AsSpan()[(separator + 1)..^0], out int count))
// {
// context.Errors.Add(new AcmePdbParseError(lineNumber, line.ToString(), "Caption does not contain number of items"));
// return null;
// }
// return (line.Substring(0, separator), count);
// }
// }
//}
| 45.901869 | 166 | 0.475313 | [
"MIT"
] | MihaMarkic/modern-vice-pdb-monitor | source/Modern.Vice.PdbMonitor/Modern.Vice.PdbMonitor.Engine/Services/Implementation/MartinAcmePdbParser.cs | 9,825 | C# |
/*<copyright>
Mo+ Solution Builder is a model oriented programming language and IDE, used for building models and generating code and other documents in a model driven development process.
Copyright (C) 2013 Dave Clemmer, Intelligent Coding Solutions, LLC
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
</copyright>*/
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Text;
using MoPlus.Common;
using MoPlus.Data;
using BLL = MoPlus.Interpreter.BLL;
namespace MoPlus.Interpreter.BLL.Interpreter
{
///--------------------------------------------------------------------------------
/// <summary></summary>
///
/// This file is for adding customizations to the DebugItem class
/// (change the Status below to something other than Generated).
///
/// <CreatedByUserName>INCODE-1\Dave</CreatedByUserName>
/// <CreatedDate>4/9/2013</CreatedDate>
/// <Status>Generated</Status>
///--------------------------------------------------------------------------------
public partial class DebugItem : BusinessObjectBase
{
#region "Constants"
#endregion "Constants"
#region "Fields and Properties"
#endregion "Fields and Properties"
#region "Methods"
#endregion "Methods"
#region "Constructors"
#endregion "Constructors"
}
} | 40.041667 | 239 | 0.700312 | [
"BSD-2-Clause"
] | moplus/modelorientedplus | MoPlus.Interpreter/Exts/BLL/Interpreter/DebugItem_Ext.cs | 1,922 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GoodCompanyModLoader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GoodCompanyModLoader")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.392857 | 93 | 0.751105 | [
"MIT"
] | SeppahBaws/GoodCompanyModLoader | GCModLoaderApp/Properties/AssemblyInfo.cs | 2,265 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NumbericTextBox.cs" company="Catel development team">
// Copyright (c) 2008 - 2014 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.Windows.Interactivity
{
#if NETFX_CORE
using global::Windows.UI.Core;
using global::Windows.UI.Xaml;
using global::Windows.UI.Xaml.Controls;
using Key = global::Windows.System.VirtualKey;
using UIEventArgs = global::Windows.UI.Xaml.RoutedEventArgs;
#else
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using UIEventArgs = System.EventArgs;
#endif
using System;
using System.Collections.Generic;
using System.Windows;
using Catel.Logging;
using Catel.Windows.Input;
/// <summary>
/// Behavior to only allow numeric input on a <see cref="TextBox"/>.
/// </summary>
public class NumericTextBox : BehaviorBase<TextBox>
{
/// <summary>
/// The log.
/// </summary>
private static readonly ILog Log = LogManager.GetCurrentClassLogger();
private const string MinusCharacter = "-";
private const string PeriodCharacter = ".";
private const string CommaCharacter = ",";
private static readonly List<Key> AllowedKeys = new List<Key>
{
Key.Back,
#if NETFX_CORE
Key.CapitalLock,
#else
Key.CapsLock,
#endif
#if SILVERLIGHT
//Key.Ctrl
#elif NETFX_CORE
Key.LeftControl,
Key.RightControl,
Key.Control,
#else
Key.LeftCtrl,
Key.RightCtrl,
#endif
Key.Down,
Key.End,
Key.Enter,
Key.Escape,
Key.Home,
Key.Insert,
Key.Left,
Key.PageDown,
Key.PageUp,
Key.Right,
#if SILVERLIGHT
//Key.Shift
#else
Key.LeftShift,
Key.RightShift,
#endif
Key.Tab,
Key.Up
};
/// <summary>
/// Initializes this instance.
/// </summary>
protected override void Initialize()
{
base.Initialize();
#if NET
DataObject.AddPastingHandler(AssociatedObject, OnPaste);
#endif
AssociatedObject.KeyDown += OnAssociatedObjectKeyDown;
AssociatedObject.TextChanged += OnAssociatedObjectTextChanged;
}
/// <summary>
/// Uninitializes this instance.
/// </summary>
protected override void Uninitialize()
{
#if NET
DataObject.RemovePastingHandler(AssociatedObject, OnPaste);
#endif
AssociatedObject.KeyDown -= OnAssociatedObjectKeyDown;
AssociatedObject.TextChanged -= OnAssociatedObjectTextChanged;
base.Uninitialize();
}
/// <summary>
/// Gets or sets a value indicating whether negative values are allowed.
/// </summary>
/// <value>
/// <c>true</c> if [allow negative]; otherwise, <c>false</c>.
/// </value>
public bool IsNegativeAllowed
{
get { return (bool)GetValue(IsNegativeAllowedProperty); }
set
{
if (value)
{
#if NET
AllowedKeys.Add(Key.OemMinus);
}
else
{
if (AllowedKeys.Contains(Key.OemMinus))
{
AllowedKeys.Remove(Key.OemMinus);
}
#endif
}
SetValue(IsNegativeAllowedProperty, value);
}
}
/// <summary>
/// Are negative numbers allowed
/// </summary>
public static readonly DependencyProperty IsNegativeAllowedProperty =
DependencyProperty.Register("IsNegativeAllowed", typeof(bool), typeof(NumericTextBox), new PropertyMetadata(true));
/// <summary>
/// Gets or sets a value indicating whether decimal values are allowed.
/// </summary>
/// <value>
/// <c>true</c> if decimal values are allowed; otherwise, <c>false</c>.
/// </value>
public bool IsDecimalAllowed
{
get { return (bool)GetValue(IsDecimalAllowedProperty); }
set { SetValue(IsDecimalAllowedProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for IsDecimalAllowed. This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty IsDecimalAllowedProperty =
DependencyProperty.Register("IsDecimalAllowed", typeof(bool), typeof(NumericTextBox), new PropertyMetadata(true));
/// <summary>
/// Called when the <see cref="UIElement.KeyDown"/> occurs.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
private void OnAssociatedObjectKeyDown(object sender, KeyEventArgs e)
{
bool notAllowed = true;
string keyValue = GetKeyValue(e);
System.Globalization.CultureInfo currentCi = System.Threading.Thread.CurrentThread.CurrentCulture;
string numberDecimalSeparator = currentCi.NumberFormat.NumberDecimalSeparator;
if (keyValue == numberDecimalSeparator && IsDecimalAllowed)
{
notAllowed = AssociatedObject.Text.Contains(numberDecimalSeparator);
}
#if SILVERLIGHT
else if (keyValue == MinusCharacter && IsNegativeAllowed)
{
notAllowed = AssociatedObject.Text.Length > 0;
}
else if (AllowedKeys.Contains(e.Key) || IsDigit(e.Key))
{
notAllowed = false;
}
#else
else if (keyValue == MinusCharacter && IsNegativeAllowed)
{
notAllowed = ((TextBox)sender).CaretIndex > 0;
}
else if (AllowedKeys.Contains(e.Key) || IsDigit(e.Key))
{
notAllowed = (e.Key == Key.OemMinus && ((TextBox)sender).CaretIndex > 0 && IsNegativeAllowed);
}
#endif
e.Handled = notAllowed;
}
/// <summary>
/// Called when the <c>TextBox.TextChanged</c> occurs.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Windows.Controls.TextChangedEventArgs"/> instance containing the event data.</param>
private void OnAssociatedObjectTextChanged(object sender, TextChangedEventArgs e)
{
var binding = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
if (binding == null)
{
return;
}
binding.UpdateSource();
}
#if NET
/// <summary>
/// Called when text is pasted into the TextBox.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="DataObjectPastingEventArgs"/> instance containing the event data.</param>
private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(string)))
{
var text = (string)e.DataObject.GetData(typeof(string));
if (!IsDigitsOnly(text))
{
Log.Warning("Pasted text '{0}' contains non-acceptable characters, paste is not allowed", text);
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
#endif
/// <summary>
/// Determines whether the input string only consists of digits.
/// </summary>
/// <param name="input">The input.</param>
/// <returns><c>true</c> if the input string only consists of digits; otherwise, <c>false</c>.</returns>
private bool IsDigitsOnly(string input)
{
foreach (char c in input)
{
if (c < '0' || c > '9')
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether the specified key is a digit.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key is digit; otherwise, <c>false</c>.
/// </returns>
private bool IsDigit(Key key)
{
bool isDigit;
bool isShiftKey = KeyboardHelper.AreKeyboardModifiersPressed(ModifierKeys.Shift);
if (key >= Key.D0 && key <= Key.D9 && !isShiftKey)
{
isDigit = true;
}
else
{
isDigit = key >= Key.NumPad0 && key <= Key.NumPad9;
}
return isDigit;
}
/// <summary>
/// Gets the Key to a string value.
/// </summary>
/// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param>
/// <returns></returns>
private string GetKeyValue(KeyEventArgs e)
{
string keyValue = string.Empty;
#if NET
if (e.Key == Key.OemMinus || e.Key == Key.Subtract)
{
keyValue = MinusCharacter;
}
else if (e.Key == Key.OemComma)
{
keyValue = CommaCharacter;
}
else if (e.Key == Key.OemPeriod)
{
keyValue = PeriodCharacter;
}
#elif NETFX_CORE
if (e.VirtualKey == Key.Subtract)
{
keyValue = MinusCharacter;
}
//else if (e.VirtualKey == Key.)
//{
// keyValue = CommaCharacter;
//}
//else if (e.VirtualKey == Key.Pe)
//{
// keyValue = PeriodCharacter;
//}
#else
if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
{
keyValue = PeriodCharacter;
}
else if (e.PlatformKeyCode == 188)
{
keyValue = CommaCharacter;
}
else if (e.PlatformKeyCode == 189)
{
keyValue = MinusCharacter;
}
else
{
keyValue = e.Key.ToString().Replace("D", "").Replace("NumPad", "");
}
#endif
return keyValue;
}
}
}
| 32.683908 | 204 | 0.5 | [
"MIT"
] | gautamsi/Catel | src/Catel.MVVM/Catel.MVVM.NET40/Windows/Interactivity/NumericTextBox.cs | 11,376 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.5446
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AllJoynNET.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AllJoynNET.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 42.71875 | 176 | 0.623628 | [
"Apache-2.0"
] | alljoyn/core-alljoyn | alljoyn_core/samples/windows/PhotoChat/AllJoynNET/Properties/Resources.Designer.cs | 2,736 | C# |
using MonoMod.Utils;
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace HarmonyLib
{
// Based on https://www.codeproject.com/Articles/14973/Dynamic-Code-Generation-vs-Reflection
/// <summary>A getter delegate type</summary>
/// <typeparam name="T">Type that getter gets field/property value from</typeparam>
/// <typeparam name="S">Type of the value that getter gets</typeparam>
/// <param name="source">The instance get getter uses</param>
/// <returns>An delegate</returns>
///
[Obsolete("Use AccessTools.FieldRefAccess<T, S> for fields and AccessTools.MethodDelegate<Func<T, S>> for property getters")]
public delegate S GetterHandler<in T, out S>(T source);
/// <summary>A setter delegate type</summary>
/// <typeparam name="T">Type that setter sets field/property value for</typeparam>
/// <typeparam name="S">Type of the value that setter sets</typeparam>
/// <param name="source">The instance the setter uses</param>
/// <param name="value">The value the setter uses</param>
/// <returns>An delegate</returns>
///
[Obsolete("Use AccessTools.FieldRefAccess<T, S> for fields and AccessTools.MethodDelegate<Action<T, S>> for property setters")]
public delegate void SetterHandler<in T, in S>(T source, S value);
/// <summary>A constructor delegate type</summary>
/// <typeparam name="T">Type that constructor creates</typeparam>
/// <returns>An delegate</returns>
///
public delegate T InstantiationHandler<out T>();
/// <summary>A helper class for fast access to getters and setters</summary>
public static class FastAccess
{
/// <summary>Creates an instantiation delegate</summary>
/// <typeparam name="T">Type that constructor creates</typeparam>
/// <returns>The new instantiation delegate</returns>
///
public static InstantiationHandler<T> CreateInstantiationHandler<T>()
{
var constructorInfo =
typeof(T).GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null,
new Type[0], null);
if (constructorInfo is null)
{
throw new ApplicationException(string.Format(
"The type {0} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).",
typeof(T)));
}
var dynamicMethod = new DynamicMethodDefinition($"InstantiateObject_{typeof(T).Name}", typeof(T), null);
var generator = dynamicMethod.GetILGenerator();
generator.Emit(OpCodes.Newobj, constructorInfo);
generator.Emit(OpCodes.Ret);
return (InstantiationHandler<T>)dynamicMethod.Generate().CreateDelegate(typeof(InstantiationHandler<T>));
}
/// <summary>Creates an getter delegate for a property</summary>
/// <typeparam name="T">Type that getter reads property from</typeparam>
/// <typeparam name="S">Type of the property that gets accessed</typeparam>
/// <param name="propertyInfo">The property</param>
/// <returns>The new getter delegate</returns>
///
[Obsolete("Use AccessTools.MethodDelegate<Func<T, S>>(PropertyInfo.GetGetMethod(true))")]
public static GetterHandler<T, S> CreateGetterHandler<T, S>(PropertyInfo propertyInfo)
{
var getMethodInfo = propertyInfo.GetGetMethod(true);
var dynamicGet = CreateGetDynamicMethod<T, S>(propertyInfo.DeclaringType);
var getGenerator = dynamicGet.GetILGenerator();
getGenerator.Emit(OpCodes.Ldarg_0);
getGenerator.Emit(OpCodes.Call, getMethodInfo);
getGenerator.Emit(OpCodes.Ret);
return (GetterHandler<T, S>)dynamicGet.Generate().CreateDelegate(typeof(GetterHandler<T, S>));
}
/// <summary>Creates an getter delegate for a field</summary>
/// <typeparam name="T">Type that getter reads field from</typeparam>
/// <typeparam name="S">Type of the field that gets accessed</typeparam>
/// <param name="fieldInfo">The field</param>
/// <returns>The new getter delegate</returns>
///
[Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")]
public static GetterHandler<T, S> CreateGetterHandler<T, S>(FieldInfo fieldInfo)
{
var dynamicGet = CreateGetDynamicMethod<T, S>(fieldInfo.DeclaringType);
var getGenerator = dynamicGet.GetILGenerator();
getGenerator.Emit(OpCodes.Ldarg_0);
getGenerator.Emit(OpCodes.Ldfld, fieldInfo);
getGenerator.Emit(OpCodes.Ret);
return (GetterHandler<T, S>)dynamicGet.Generate().CreateDelegate(typeof(GetterHandler<T, S>));
}
/// <summary>Creates an getter delegate for a field (with a list of possible field names)</summary>
/// <typeparam name="T">Type that getter reads field/property from</typeparam>
/// <typeparam name="S">Type of the field/property that gets accessed</typeparam>
/// <param name="names">A list of possible field names</param>
/// <returns>The new getter delegate</returns>
///
[Obsolete("Use AccessTools.FieldRefAccess<T, S>(name) for fields and " +
"AccessTools.MethodDelegate<Func<T, S>>(AccessTools.PropertyGetter(typeof(T), name)) for properties")]
public static GetterHandler<T, S> CreateFieldGetter<T, S>(params string[] names)
{
foreach (var name in names)
{
var field = typeof(T).GetField(name, AccessTools.all);
if (field is object)
return CreateGetterHandler<T, S>(field);
var property = typeof(T).GetProperty(name, AccessTools.all);
if (property is object)
return CreateGetterHandler<T, S>(property);
}
return null;
}
/// <summary>Creates an setter delegate</summary>
/// <typeparam name="T">Type that setter assigns property value to</typeparam>
/// <typeparam name="S">Type of the property that gets assigned</typeparam>
/// <param name="propertyInfo">The property</param>
/// <returns>The new setter delegate</returns>
///
[Obsolete("Use AccessTools.MethodDelegate<Action<T, S>>(PropertyInfo.GetSetMethod(true))")]
public static SetterHandler<T, S> CreateSetterHandler<T, S>(PropertyInfo propertyInfo)
{
var setMethodInfo = propertyInfo.GetSetMethod(true);
var dynamicSet = CreateSetDynamicMethod<T, S>(propertyInfo.DeclaringType);
var setGenerator = dynamicSet.GetILGenerator();
setGenerator.Emit(OpCodes.Ldarg_0);
setGenerator.Emit(OpCodes.Ldarg_1);
setGenerator.Emit(OpCodes.Call, setMethodInfo);
setGenerator.Emit(OpCodes.Ret);
return (SetterHandler<T, S>)dynamicSet.Generate().CreateDelegate(typeof(SetterHandler<T, S>));
}
/// <summary>Creates an setter delegate for a field</summary>
/// <typeparam name="T">Type that setter assigns field value to</typeparam>
/// <typeparam name="S">Type of the field that gets assigned</typeparam>
/// <param name="fieldInfo">The field</param>
/// <returns>The new getter delegate</returns>
///
[Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")]
public static SetterHandler<T, S> CreateSetterHandler<T, S>(FieldInfo fieldInfo)
{
var dynamicSet = CreateSetDynamicMethod<T, S>(fieldInfo.DeclaringType);
var setGenerator = dynamicSet.GetILGenerator();
setGenerator.Emit(OpCodes.Ldarg_0);
setGenerator.Emit(OpCodes.Ldarg_1);
setGenerator.Emit(OpCodes.Stfld, fieldInfo);
setGenerator.Emit(OpCodes.Ret);
return (SetterHandler<T, S>)dynamicSet.Generate().CreateDelegate(typeof(SetterHandler<T, S>));
}
static DynamicMethodDefinition CreateGetDynamicMethod<T, S>(Type type)
{
return new DynamicMethodDefinition($"DynamicGet_{type.Name}", typeof(S), new Type[] { typeof(T) });
}
static DynamicMethodDefinition CreateSetDynamicMethod<T, S>(Type type)
{
return new DynamicMethodDefinition($"DynamicSet_{type.Name}", typeof(void), new Type[] { typeof(T), typeof(S) });
}
}
}
| 44 | 141 | 0.711002 | [
"MIT"
] | 0x0ade/Harmony | Harmony/Extras/FastAccess.cs | 7,569 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Ecs.Model.V20140526;
namespace Aliyun.Acs.Ecs.Transform.V20140526
{
public class ReInitDiskResponseUnmarshaller
{
public static ReInitDiskResponse Unmarshall(UnmarshallerContext context)
{
ReInitDiskResponse reInitDiskResponse = new ReInitDiskResponse();
reInitDiskResponse.HttpResponse = context.HttpResponse;
reInitDiskResponse.RequestId = context.StringValue("ReInitDisk.RequestId");
return reInitDiskResponse;
}
}
}
| 34.8 | 80 | 0.750718 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-ecs/Ecs/Transform/V20140526/ReInitDiskResponseUnmarshaller.cs | 1,392 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006-2019, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.472)
// Version 5.472.0.0 www.ComponentFactory.com
// *****************************************************************************
namespace ComponentFactory.Krypton.Navigator
{
/// <summary>
/// Details for a direction button (next/previous) action event.
/// </summary>
public class DirectionActionEventArgs : KryptonPageEventArgs
{
#region Instance Fields
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the DirectionActionEventArgs class.
/// </summary>
/// <param name="page">Page effected by event.</param>
/// <param name="index">Index of page in the owning collection.</param>
/// <param name="action">Previous/Next action to take.</param>
public DirectionActionEventArgs(KryptonPage page,
int index,
DirectionButtonAction action)
: base(page, index)
{
Action = action;
}
#endregion
#region Action
/// <summary>
/// Gets and sets the next/previous action to take.
/// </summary>
public DirectionButtonAction Action { get; set; }
#endregion
}
}
| 39.416667 | 157 | 0.57241 | [
"BSD-3-Clause"
] | dave-w-au/Krypton-NET-5.472 | Source/Krypton Components/ComponentFactory.Krypton.Navigator/EventArgs/DirectionActionEventArgs.cs | 1,895 | C# |
namespace ASPNET.Fundamentals.DI.ServiceLifetimes.Services
{
public class OperationService
{
public OperationService(
IOperationTransient transientOperation,
IOperationScoped scopedOperation,
IOperationSingleton singletonOperation,
IOperationSingletonInstance instanceOperation)
{
TransientOperation = transientOperation;
ScopedOperation = scopedOperation;
SingletonOperation = singletonOperation;
SingletonInstanceOperation = instanceOperation;
}
public IOperationTransient TransientOperation { get; }
public IOperationScoped ScopedOperation { get; }
public IOperationSingleton SingletonOperation { get; }
public IOperationSingletonInstance SingletonInstanceOperation { get; }
}
}
| 37.826087 | 79 | 0.678161 | [
"MIT"
] | liammoat/aspnet-fundamentals | src/DI/ServiceLifetimes/Services/OperationService.cs | 872 | C# |
using Netherlands3D.Cameras;
using Netherlands3D.Interface.SidePanel;
using Netherlands3D.ObjectInteraction;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Netherlands3D.Interface.Layers
{
public class CustomLayer : InterfaceLayer, IPointerClickHandler
{
[SerializeField]
private Text layerNameText;
public string GetName => layerNameText.text;
[SerializeField]
private GameObject removeButton;
private int maxNameLength = 24;
private void Start()
{
//Make sure we always add from the top (minus add button, and annotation group)
this.transform.SetSiblingIndex(2);
}
public void OnPointerClick(PointerEventData eventData)
{
//Catch double click on layer, to move camera to the linked object
if (layerType == LayerType.ANNOTATION)
{
Annotation annotation = LinkedObject.GetComponent<Annotation>();
CameraModeChanger.Instance.CurrentCameraControls.MoveAndFocusOnLocation(annotation.WorldPointerFollower.WorldPosition, new Quaternion());
annotation.StartEditingText();
}
else if (layerType == LayerType.CAMERA)
{
WorldPointFollower follower = LinkedObject.GetComponent<WorldPointFollower>();
FirstPersonLocation obj = LinkedObject.GetComponent<FirstPersonLocation>();
CameraModeChanger.Instance.CurrentCameraControls.MoveAndFocusOnLocation(follower.WorldPosition, obj.savedRotation);
}
else
{
//If this is a Transformable, select it
var transformable = LinkedObject.GetComponent<Transformable>();
if (transformable)
{
transformable.Select();
ToggleLayerOpened();
}
}
}
public void Create(string layerName, GameObject link, LayerType type, InterfaceLayers interfaceLayers)
{
layerType = type;
layerNameText.text = layerName;
LinkObject(link);
parentInterfaceLayers = interfaceLayers;
}
public void RenameLayer(string newName){
name = newName; //use our object name to store our full name
if (newName.Length > maxNameLength)
newName = newName.Substring(0, maxNameLength - 3) + "...";
layerNameText.text = newName;
}
/// <summary>
/// Enable or disable layer options based on view mode
/// </summary>
/// <param name="viewOnly">Only view mode enabled</param>
public void ViewingOnly(bool viewOnly)
{
removeButton.SetActive(!viewOnly);
}
public void Remove()
{
//TODO: A confirmation before removing might be required. Can be very annoying. Verify with users.
parentInterfaceLayers.LayerVisuals.Close();
Destroy(gameObject);
}
private void OnDestroy()
{
GameObject.Destroy(LinkedObject);
}
}
} | 34.925532 | 153 | 0.607371 | [
"Apache-2.0",
"MIT"
] | GemeenteUtrecht/3DAmsterdam | 3DAmsterdam/Assets/Netherlands3D/Scripts/Interface/Layers/CustomLayer.cs | 3,285 | C# |
#pragma warning disable GURA04,GURA06 // Move test to correct class.
namespace PropertyChangedAnalyzers.Test
{
using System;
using System.Collections.Generic;
using System.Linq;
using Gu.Roslyn.Asserts;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using NUnit.Framework;
public static class ValidWithAllAnalyzers
{
private static readonly IReadOnlyList<DiagnosticAnalyzer> AllAnalyzers = typeof(Descriptors)
.Assembly
.GetTypes()
.Where(typeof(DiagnosticAnalyzer).IsAssignableFrom)
.Select(t => (DiagnosticAnalyzer)Activator.CreateInstance(t))
.ToArray();
private static readonly Solution AnalyzersProjectSolution = CodeFactory.CreateSolution(
ProjectFile.Find("PropertyChangedAnalyzers.csproj"),
AllAnalyzers,
MetadataReferences.FromAttributes());
private static readonly Solution ValidCodeProjectSln = CodeFactory.CreateSolution(
ProjectFile.Find("ValidCode.csproj"),
AllAnalyzers,
MetadataReferences.FromAttributes());
[Test]
public static void NotEmpty()
{
CollectionAssert.IsNotEmpty(AllAnalyzers);
Assert.Pass($"Count: {AllAnalyzers.Count}");
}
[Ignore("Does not pick up nullable attributes.")]
[TestCaseSource(nameof(AllAnalyzers))]
public static void AnalyzersProject(DiagnosticAnalyzer analyzer)
{
RoslynAssert.Valid(analyzer, AnalyzersProjectSolution);
}
[TestCaseSource(nameof(AllAnalyzers))]
public static void ValidCodeProject(DiagnosticAnalyzer analyzer)
{
RoslynAssert.Valid(analyzer, ValidCodeProjectSln);
}
[TestCaseSource(nameof(AllAnalyzers))]
public static void SomewhatRealisticSample(DiagnosticAnalyzer analyzer)
{
var viewModelBase = @"
namespace N.Core
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool TrySet<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
{
return false;
}
field = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}";
var withMutableField = @"
namespace N
{
public class WithMutableField
{
public int F;
}
}";
var viewModel1Code = @"
namespace N.Client
{
using N.Core;
public class ViewModel1 : ViewModelBase
{
private int value;
private int p2;
public int Sum => this.Value + this.P2;
public int Value
{
#pragma warning disable INPC020 // Prefer expression body accessor.
get
{
return this.value;
}
#pragma warning restore INPC020 // Prefer expression body accessor.
set
{
if (value == this.value)
{
return;
}
this.value = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(Sum));
}
}
public int P2
{
get => this.p2;
set
{
if (this.TrySet(ref this.p2, value))
{
this.OnPropertyChanged(nameof(this.Sum));
}
}
}
}
}";
var viewModel2Code = @"
namespace N
{
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class ViewModel2 : INotifyPropertyChanged
{
private int value;
private readonly WithMutableField p = new WithMutableField();
public event PropertyChangedEventHandler PropertyChanged;
public int Squared => this.Value * this.Value;
public int Value
{
#pragma warning disable INPC020 // Prefer expression body accessor.
get
{
return this.value;
}
#pragma warning restore INPC020 // Prefer expression body accessor.
set
{
if (value == this.value)
{
return;
}
this.value = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(Squared));
}
}
public int P2
{
get => this.p.F;
set
{
if (value == this.p.F)
{
return;
}
this.p.F = value;
this.OnPropertyChanged();
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}";
var oldStyleOnPropertyChanged = @"
namespace N
{
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class OldStyleOnPropertyChanged : INotifyPropertyChanged
{
private int p;
public event PropertyChangedEventHandler PropertyChanged;
public int P
{
get => this.p;
set
{
if (value == this.p)
{
return;
}
this.p = value;
this.OnPropertyChanged();
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = this.PropertyChanged;
if (handler != null)
{
var args = new PropertyChangedEventArgs(propertyName);
handler.Invoke(this, args);
}
}
}
}";
var wrappingPoint = @"
namespace N
{
using System.ComponentModel;
using System.Drawing;
using System.Runtime.CompilerServices;
public class WrappingPoint : INotifyPropertyChanged
{
private Point point;
public event PropertyChangedEventHandler PropertyChanged;
public int X
{
get => this.point.X;
set
{
if (value == this.point.X)
{
return;
}
#pragma warning disable INPC003
this.point = new Point(value, this.point.Y);
#pragma warning restore INPC003
this.OnPropertyChanged();
}
}
public int Y
{
get => this.point.Y;
set
{
if (value == this.point.Y)
{
return;
}
#pragma warning disable INPC003
this.point = new Point(this.point.X, value);
#pragma warning restore INPC003
this.OnPropertyChanged();
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}";
var wrappingTimeSpan = @"
namespace N
{
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class WrappingTimeSpan : INotifyPropertyChanged
{
private TimeSpan timeSpan;
public event PropertyChangedEventHandler PropertyChanged;
public long Ticks
{
get => this.timeSpan.Ticks;
set
{
if (value == this.timeSpan.Ticks)
{
return;
}
this.timeSpan = TimeSpan.FromTicks(value);
this.OnPropertyChanged();
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}";
var radioButtonViewModel = @"
namespace N
{
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class RadioButtonViewModel : INotifyPropertyChanged
{
private double speed;
public event PropertyChangedEventHandler PropertyChanged;
public bool IsSpeed1
{
get => Math.Abs(this.speed - 1) < 1E-2;
set => this.Speed = 1;
}
public double Speed
{
get => this.speed;
set
{
if (value.Equals(this.speed))
{
return;
}
this.speed = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.IsSpeed1));
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}";
var abstractWithAbstractProperty = @"
namespace N
{
using System.ComponentModel;
using System.Runtime.CompilerServices;
public abstract class AbstractWithAbstractProperty : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public abstract int Value { get; }
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}";
var subClassingAbstractWithAbstractProperty = @"
namespace N
{
public class SubClassingAbstractWithAbstractProperty : AbstractWithAbstractProperty
{
private int value;
public override int Value => this.value;
public void Update(int value)
{
this.value = value;
this.OnPropertyChanged(nameof(this.Value));
}
}
}";
var exceptionHandlingRelayCommand = @"
namespace N
{
using System;
using Gu.Reactive;
using Gu.Wpf.Reactive;
public class ExceptionHandlingRelayCommand : ConditionRelayCommand
{
private Exception _exception;
public ExceptionHandlingRelayCommand(Action action, ICondition condition)
: base(action, condition)
{
}
public Exception Exception
{
get => _exception;
private set
{
#pragma warning disable INPC006_b
if (ReferenceEquals(value, _exception))
#pragma warning restore INPC006_b
{
return;
}
_exception = value;
OnPropertyChanged();
}
}
}
}";
RoslynAssert.Valid(
analyzer,
viewModelBase,
withMutableField,
viewModel1Code,
viewModel2Code,
oldStyleOnPropertyChanged,
wrappingPoint,
wrappingTimeSpan,
radioButtonViewModel,
abstractWithAbstractProperty,
subClassingAbstractWithAbstractProperty,
exceptionHandlingRelayCommand);
}
[TestCaseSource(nameof(AllAnalyzers))]
public static void SomewhatRealisticSampleGeneric(DiagnosticAnalyzer analyzer)
{
var viewModelBaseOf_ = @"
namespace N.Core
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public abstract class ViewModelBase<_> : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool TrySet<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
{
return false;
}
field = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}";
var viewModel1 = @"
namespace N.Client
{
using N.Core;
public class ViewModel1 : ViewModelBase<int>
{
private int value;
private int p2;
public int Sum => this.Value + this.P2;
public int Value
{
#pragma warning disable INPC020 // Prefer expression body accessor.
get
{
return this.value;
}
#pragma warning restore INPC020 // Prefer expression body accessor.
set
{
if (value == this.value)
{
return;
}
this.value = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(Sum));
}
}
public int P2
{
get => this.p2;
set
{
if (this.TrySet(ref this.p2, value))
{
this.OnPropertyChanged(nameof(this.Sum));
}
}
}
}
}";
var genericViewModelOfT = @"
namespace N
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class GenericViewModel<T> : INotifyPropertyChanged
{
private T value;
public event PropertyChangedEventHandler PropertyChanged;
public string Text => $""{this.Value} {this.Value}"";
public T Value
{
#pragma warning disable INPC020 // Prefer expression body accessor.
get
{
return this.value;
}
#pragma warning restore INPC020 // Prefer expression body accessor.
set
{
if (EqualityComparer<T>.Default.Equals(value, this.value))
{
return;
}
this.value = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(Text));
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}";
RoslynAssert.Valid(analyzer, viewModelBaseOf_, viewModel1, genericViewModelOfT);
}
}
}
| 26.247423 | 101 | 0.553875 | [
"MIT"
] | jnm2/PropertyChangedAnalyzers | PropertyChangedAnalyzers.Test/ValidWithAllAnalyzers.cs | 15,276 | C# |
namespace Newbe.Claptrap
{
public interface IStateLoaderOptions : IStorageProviderOptions
{
}
} | 17.833333 | 66 | 0.738318 | [
"MIT"
] | Z4t4r/Newbe.Claptrap | src/Newbe.Claptrap.Abstractions/Design/IStateLoaderOptions.cs | 107 | C# |
//Copyright (c) Microsoft Corporation. All rights reserved. Distributed under the Microsoft Public License (MS-PL)
using Microsoft.WindowsAPICodePack.COMNative.Shell;
using Microsoft.WindowsAPICodePack.Win32Native.Shell;
namespace Microsoft.WindowsAPICodePack.COMNative.Shell
{
/// <summary>
/// Represents the different retrieval options for the thumbnail or icon,
/// such as extracting the thumbnail or icon from a file,
/// from the cache only, or from memory only.
/// </summary>
public enum ShellThumbnailRetrievalOption
{
/// <summary>
/// The default behavior loads a thumbnail. If there is no thumbnail for the current ShellItem,
/// the icon is retrieved. The thumbnail or icon is extracted if it is not currently cached.
/// </summary>
Default,
/// <summary>
/// The CacheOnly behavior returns a cached thumbnail if it is available. Allows access to the disk,
/// but only to retrieve a cached item. If no cached thumbnail is available, a cached per-instance icon is returned but
/// a thumbnail or icon is not extracted.
/// </summary>
CacheOnly = SIIGBF.InCacheOnly,
/// <summary>
/// The MemoryOnly behavior returns the item only if it is in memory. The disk is not accessed even if the item is cached.
/// Note that this only returns an already-cached icon and can fall back to a per-class icon if
/// an item has a per-instance icon that has not been cached yet. Retrieving a thumbnail,
/// even if it is cached, always requires the disk to be accessed, so this method should not be
/// called from the user interface (UI) thread without passing ShellThumbnailCacheOptions.MemoryOnly.
/// </summary>
MemoryOnly = SIIGBF.MemoryOnly,
}
/// <summary>
/// Represents the format options for the thumbnails and icons.
/// </summary>
public enum ShellThumbnailFormatOption
{
/// <summary>
/// The default behavior loads a thumbnail. An HBITMAP for the icon of the item is retrieved if there is no thumbnail for the current Shell Item.
/// </summary>
Default,
/// <summary>
/// The ThumbnailOnly behavior returns only the thumbnails, never the icon. Note that not all items have thumbnails
/// so ShellThumbnailFormatOption.ThumbnailOnly can fail in these cases.
/// </summary>
ThumbnailOnly = SIIGBF.ThumbnailOnly,
/// <summary>
/// The IconOnly behavior returns only the icon, never the thumbnail.
/// </summary>
IconOnly = SIIGBF.IconOnly,
}
}
| 44.833333 | 153 | 0.664312 | [
"MIT"
] | bodrick/Windows-API-Code-Pack | source/WindowsAPICodePack/COMNative.Shared/Shell/Common/ShellThumbnailEnums.cs | 2,690 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sidewinder {
public static T CreateMaze<T>(T grid, MazeSidewinderSettings settings) where T : MazeGrid
{
// Random Generator
Random.State initialState = Random.state;
if (settings.useFixedSeed)
{
Random.InitState(settings.seed.GetHashCode());
}
else
{
Random.InitState(Time.time.ToString().GetHashCode());
}
Direction vertical = settings.verticalCarveDirectionNorth ? (Direction.North) : (Direction.South);
Direction horizontal = settings.horizontalCarveDirectionEast ? (Direction.East) : (Direction.West);
foreach (MazeCell[] cellRow in grid.EachRow(vertical, horizontal))
{
List<MazeCell> row = new List<MazeCell>();
foreach (MazeCell cell in cellRow)
{
if (cell == null)
{
continue;
}
row.Add(cell);
//check if is out of width / height to avoid carve walls
bool atVerticalBoundary = settings.verticalCarveDirectionNorth ? (cell.North == null) : (cell.South == null);
bool atHorizontalBoundary = settings.horizontalCarveDirectionEast ? (cell.East == null) : (cell.West == null);
bool carveMainDirection;
if (settings.isVerticalDirectionMain)
{
carveMainDirection = atHorizontalBoundary || (!atVerticalBoundary && Random.value < settings.chanceToCarveOutMain);
}
else
{
carveMainDirection = atVerticalBoundary || (!atHorizontalBoundary && Random.value < settings.chanceToCarveOutMain);
}
if (carveMainDirection)
{
MazeCell member = row[Random.Range(0, row.Count)]; //get random cell in a row
if (settings.isVerticalDirectionMain)
{
if (settings.verticalCarveDirectionNorth)
{
if (member.North != null) //if has neighbour at North => carve out wall
{
member.Link(member.North);
}
}
else
{
if (member.South != null)
{
member.Link(member.South);
}
}
}
else
{
if (settings.horizontalCarveDirectionEast)
{
if (member.East != null)
{
member.Link(member.East);
}
}
else
{
if (member.West != null)
{
member.Link(member.West);
}
}
}
row.Clear(); // Clear row
}
else // if not carve north - break walls in horizontal axis between cells on row
{
if (settings.isVerticalDirectionMain)
{
if (settings.horizontalCarveDirectionEast)
{
cell.Link(cell.East);
}
else
{
cell.Link(cell.West);
}
}
else
{
if (settings.verticalCarveDirectionNorth)
{
cell.Link(cell.North);
}
else
{
cell.Link(cell.South);
}
}
}
}
}
Random.state = initialState;
return grid;
}
}
| 35.346774 | 135 | 0.398814 | [
"MIT"
] | Protosaider/GraduateWork | Assets/Scripts/Algorithms/Maze Map/Sidewinder.cs | 4,385 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
namespace Amazon.PowerShell.Cmdlets.S3
{
/// <summary>
/// Deletes the CORS configuration information set for the bucket.
/// </summary>
[Cmdlet("Remove", "S3CORSConfiguration", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)]
[OutputType("None")]
[AWSCmdlet("Calls the Amazon Simple Storage Service (S3) DeleteCORSConfiguration API operation.", Operation = new[] {"DeleteCORSConfiguration"}, SelectReturnType = typeof(Amazon.S3.Model.DeleteCORSConfigurationResponse))]
[AWSCmdletOutput("None or Amazon.S3.Model.DeleteCORSConfigurationResponse",
"This cmdlet does not generate any output." +
"The service response (type Amazon.S3.Model.DeleteCORSConfigurationResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class RemoveS3CORSConfigurationCmdlet : AmazonS3ClientCmdlet, IExecutor
{
#region Parameter BucketName
/// <summary>
/// <para>
/// The service has not provided documentation for this parameter; please refer to the service's API reference documentation for the latest available information.
/// </para>
/// </summary>
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
public System.String BucketName { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.S3.Model.DeleteCORSConfigurationResponse).
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the BucketName parameter.
/// The -PassThru parameter is deprecated, use -Select '^BucketName' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^BucketName' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.BucketName), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Remove-S3CORSConfiguration (DeleteCORSConfiguration)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.S3.Model.DeleteCORSConfigurationResponse, RemoveS3CORSConfigurationCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.BucketName;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.BucketName = this.BucketName;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.S3.Model.DeleteCORSConfigurationRequest();
if (cmdletContext.BucketName != null)
{
request.BucketName = cmdletContext.BucketName;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.S3.Model.DeleteCORSConfigurationResponse CallAWSServiceOperation(IAmazonS3 client, Amazon.S3.Model.DeleteCORSConfigurationRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Simple Storage Service (S3)", "DeleteCORSConfiguration");
try
{
#if DESKTOP
return client.DeleteCORSConfiguration(request);
#elif CORECLR
return client.DeleteCORSConfigurationAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String BucketName { get; set; }
public System.Func<Amazon.S3.Model.DeleteCORSConfigurationResponse, RemoveS3CORSConfigurationCmdlet, object> Select { get; set; } =
(response, cmdlet) => null;
}
}
}
| 44.059406 | 225 | 0.609663 | [
"Apache-2.0"
] | alexandair/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/S3/Basic/Remove-S3CORSConfiguration-Cmdlet.cs | 8,900 | C# |
using Elbanique.IndyZeth.Configuration;
using Elbanique.IndyZeth.Model;
using Elbanique.IndyZeth.Repositories;
using Serilog;
using System;
using System.Linq;
using System.Reflection;
namespace Elbanique.IndyZeth.Services
{
public class TypeScanner : ITypeScanner
{
private static readonly ILogger logger = Log.Logger.ForContext<TypeScanner>();
private readonly IObjectRepository objectRepository;
private readonly IRelationshipRepository relationshipRepository;
private readonly Settings settings;
public TypeScanner(IObjectRepository objectRepository,
IRelationshipRepository relationshipRepository,
Settings settings)
{
this.objectRepository = objectRepository;
this.relationshipRepository = relationshipRepository;
this.settings = settings;
}
public void AddType(TypeInfo typeInfo)
{
logger.Information($"Scanning type {typeInfo.FullName}");
//Skip those with no namespace, they have no influence on the dependencies
if (typeInfo.Namespace == null) return;
Type baseType = typeInfo.BaseType;
var typeName = typeInfo.GetDisplayableName();
var obj = new Model.Object
{
FullName = typeName,
CompanyName = GetCompanyName(typeInfo.Namespace),
AssemblyName = typeInfo.Assembly.FullName
};
if (typeInfo.IsValueType)
{
if (String.Equals(baseType?.FullName, "System.Enum", StringComparison.InvariantCulture))
{
obj.ObjectKind = ObjectKind.Enum;
}
else
{
obj.ObjectKind = ObjectKind.Struct;
}
}
else if (typeInfo.IsInterface)
{
obj.ObjectKind = ObjectKind.Interface;
}
objectRepository.Insert(obj);
if (typeInfo.IsClass && !String.Equals(baseType.FullName, "System.Object", StringComparison.InvariantCulture))
{
if (baseType.IsGenericType)
{
if (baseType.IsArray || baseType.GetInterface("IEnumerable") != null)
{
//just interested in the dependency => dependency to the generic type of the collection so we can link to it
var genericTypeParameters = baseType.GetGenericArguments();
foreach (var gtp in genericTypeParameters)
{
relationshipRepository.Insert(new Relationship
{
From = typeName,
To = gtp.GetDisplayableName(),
RelationshipKind = RelationshipKind.Inherits
});
}
}
else
{
//just interested in the dependency => dependency to the base class (without generic implementation!) so we can link to it
relationshipRepository.Insert(new Relationship
{
From = typeName,
To = string.Join(".", baseType.Namespace, baseType.Name),
RelationshipKind = RelationshipKind.Inherits
});
}
}
else
{
relationshipRepository.Insert(new Relationship
{
From = typeName,
To = baseType.GetDisplayableName(),
RelationshipKind = RelationshipKind.Inherits
});
}
}
var interfaces = typeInfo.GetInterfaces();
foreach (var @interface in interfaces)
{
//skip the system types
if (@interface.Namespace != null && @interface.Namespace.StartsWith("System")) continue;
if (@interface.IsGenericType)
{
//get the generic type (make it searchable) and list the generic arguments as dependencies
//except for collection
if (!@interface.IsArray || @interface.GetInterface("IEnumerable") != null)
{
relationshipRepository.Insert(new Relationship
{
From = typeName,
To = string.Join(".", @interface.Namespace, @interface.Name),
RelationshipKind = RelationshipKind.Implements
});
}
//gather the type arguments as dependencies
var genericTypeParameters = @interface.GetGenericArguments();
foreach (var gtp in genericTypeParameters)
{
//skip the system types
if (gtp.Namespace != null && gtp.Namespace.StartsWith("System")) continue;
//when the parameter is not declared (like 'T'), skip
var gtpName = gtp.GetDisplayableName();
if (gtpName == typeName) continue;
relationshipRepository.Insert(new Relationship
{
From = typeName,
To = gtpName,
RelationshipKind = RelationshipKind.Depends
});
}
}
else
{
relationshipRepository.Insert(new Relationship
{
From = typeName,
To = @interface.GetDisplayableName(),
RelationshipKind = RelationshipKind.Implements
});
}
}
var ctors = typeInfo.GetConstructors();
foreach (var ctor in ctors)
{
var parameterInfos = ctor.GetParameters();
foreach (var parameterInfo in parameterInfos)
{
//skip the system types
if (parameterInfo.ParameterType.Namespace != null && parameterInfo.ParameterType.Namespace.StartsWith("System")) continue;
//we are only interested in the dependencies, so when a dependency is generic or collection, gather the generic types iso name
if (parameterInfo.ParameterType.IsGenericType)
{
var genericTypeParameters = parameterInfo.ParameterType.GetGenericArguments();
foreach (var gtp in genericTypeParameters)
{
//skip the system types
if (gtp.Namespace != null && gtp.Namespace.StartsWith("System")) continue;
relationshipRepository.Insert(new Relationship
{
From = typeName,
To = gtp.GetDisplayableName(),
RelationshipKind = RelationshipKind.Depends
});
}
}
else
{
relationshipRepository.Insert(new Relationship
{
From = typeName,
To = parameterInfo.ParameterType.GetDisplayableName(),
RelationshipKind = RelationshipKind.Depends
});
}
}
}
}
private string GetCompanyName(string ns)
{
if (ns == null) return "Undefined";
var nsFirstPart = ns.Split(".").First();
var map = settings.CompanyMappings.FirstOrDefault(x => x.NamespaceFirstPart.Equals(nsFirstPart, StringComparison.InvariantCultureIgnoreCase));
if (map != null) return map.CompanyName;
return nsFirstPart;
}
}
}
| 40.961165 | 154 | 0.485542 | [
"MIT"
] | JanKinable/IndyZeth | src/IndyZeth/Services/TypeScanner.cs | 8,440 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MaSchoeller.Extensions.Desktop.Abstracts
{
public interface IRouter
{
event NavigationChangedEventHandler RouteChanged;
event NavigationChangedEventHandler RouteChangeFailed;
string ActualRoute { get; }
//Todo:implementing routing queue
Task<bool> TryNavigateToAsnyc(CancellationToken token = default);
}
public delegate void NavigationChangedEventHandler(object sender, NavigationChangedEventArgs args);
public class NavigationChangedEventArgs : EventArgs
{
}
}
| 24.777778 | 103 | 0.751868 | [
"MIT"
] | maSchoeller/DesktopGenericHost | src/Desktop/MaSchoeller.Extensions.Desktop/Abstracts/IRouter.cs | 671 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Healthcare.Models;
using HeathcareSystem.Models;
using Microsoft.Data.Entity;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace HeathcareSystem.Controllers
{
[Route("api/[controller]/[action]")]
public class DiseaseController : Controller
{
IHealthcareContext context;
public DiseaseController(IHealthcareContext context)
{
this.context = context;
}
// GET: api/values
[HttpGet("id")]
public IActionResult Get(long id)
{
var disease = context.Diseases.SingleOrDefault(a => a.Id==id);
return Ok(disease);
}
[HttpGet]
public IActionResult GetAll()
{
var result = context.Diseases.ToList();
return Ok(result) ;
}
[HttpPost]
public IActionResult AddNewDisease([FromBody]Disease model)
{
if (!ModelState.IsValid)
{
return HttpBadRequest();
}
context.Diseases.Add(model);
context.SaveChange();
return Ok();
}
// DELETE api/values/5
[HttpDelete("{id}")]
public IActionResult Delete(long id)
{
var disease = context.Diseases.SingleOrDefault(a => a.Id == id);
context.SetState(disease, EntityState.Deleted);
context.SaveChange();
return Ok();
}
}
}
| 27.725806 | 116 | 0.556137 | [
"Apache-2.0"
] | nguyenmanhphuc93/healthcare-social-network | src/HeathcareSystem/Controllers/DiseaseController.cs | 1,721 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LumiSoft.Net.IMAP
{
/// <summary>
/// This class represents IMAP CAPABILITY response. Defined in RFC 3501 7.2.1.
/// </summary>
public class IMAP_r_u_Capability : IMAP_r_u
{
private string[] m_pCapabilities = null;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="capabilities">Capabilities list.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>capabilities</b> is null reference.</exception>
public IMAP_r_u_Capability(string[] capabilities)
{
if(capabilities == null){
throw new ArgumentNullException("capabilities");
}
m_pCapabilities = capabilities;
}
#region static method Parse
/// <summary>
/// Parses CAPABILITY response from capability-response string.
/// </summary>
/// <param name="response">Capability response string.</param>
/// <returns>Returns parsed CAPABILITY response.</returns>
/// <exception cref="ArgumentNullException">Is riased when <b>response</b> is null reference.</exception>
public static IMAP_r_u_Capability Parse(string response)
{
if(response == null){
throw new ArgumentNullException("response");
}
/* RFC 3501 7.2.1. CAPABILITY Response.
Contents: capability listing
The CAPABILITY response occurs as a result of a CAPABILITY
command. The capability listing contains a space-separated
listing of capability names that the server supports. The
capability listing MUST include the atom "IMAP4rev1".
In addition, client and server implementations MUST implement the
STARTTLS, LOGINDISABLED, and AUTH=PLAIN (described in [IMAP-TLS])
capabilities. See the Security Considerations section for
important information.
A capability name which begins with "AUTH=" indicates that the
server supports that particular authentication mechanism.
The LOGINDISABLED capability indicates that the LOGIN command is
disabled, and that the server will respond with a tagged NO
response to any attempt to use the LOGIN command even if the user
name and password are valid. An IMAP client MUST NOT issue the
LOGIN command if the server advertises the LOGINDISABLED
capability.
Other capability names indicate that the server supports an
extension, revision, or amendment to the IMAP4rev1 protocol.
Server responses MUST conform to this document until the client
issues a command that uses the associated capability.
Capability names MUST either begin with "X" or be standard or
standards-track IMAP4rev1 extensions, revisions, or amendments
registered with IANA. A server MUST NOT offer unregistered or
non-standard capability names, unless such names are prefixed with
an "X".
Client implementations SHOULD NOT require any capability name
other than "IMAP4rev1", and MUST ignore any unknown capability
names.
A server MAY send capabilities automatically, by using the
CAPABILITY response code in the initial PREAUTH or OK responses,
and by sending an updated CAPABILITY response code in the tagged
OK response as part of a successful authentication. It is
unnecessary for a client to send a separate CAPABILITY command if
it recognizes these automatic capabilities.
Example: S: * CAPABILITY IMAP4rev1 STARTTLS AUTH=GSSAPI XPIG-LATIN
*/
StringReader r = new StringReader(response);
// Eat "*"
r.ReadWord();
// Eat "CAPABILITY"
r.ReadWord();
string[] capabilities = r.ReadToEnd().Split(' ');
return new IMAP_r_u_Capability(capabilities);
}
#endregion
#region override method ToString
/// <summary>
/// Returns this as string.
/// </summary>
/// <returns>Returns this as string.</returns>
public override string ToString()
{
// Example: S: * CAPABILITY IMAP4rev1 STARTTLS AUTH=GSSAPI XPIG-LATIN
StringBuilder retVal = new StringBuilder();
retVal.Append("* CAPABILITY");
foreach(string capability in m_pCapabilities){
retVal.Append(" " + capability);
}
retVal.Append("\r\n");
return retVal.ToString();
}
#endregion
#region Properties impelementation
/// <summary>
/// Gets capabilities list.
/// </summary>
public string[] Capabilities
{
get{ return m_pCapabilities; }
}
#endregion
}
}
| 37.368794 | 117 | 0.596887 | [
"MIT"
] | garakutanokiseki/Join.NET | LumiSoftNet/Net/IMAP/IMAP_r_u_Capability.cs | 5,271 | C# |
namespace ConditionalClockButton
{
public class TwelveHourClock : ClockButton.Clock
{
// Initialize for Hour value of 0
int hour12 = 12;
bool isAm = true;
bool isPm = false;
public int Hour12
{
set { SetProperty<int>(ref hour12, value); }
get { return hour12; }
}
public bool IsAm
{
set { SetProperty<bool>(ref isAm, value); }
get { return isAm; }
}
public bool IsPm
{
set { SetProperty<bool>(ref isPm, value); }
get { return isPm; }
}
protected override void OnPropertyChanged(string propertyName)
{
if (propertyName == "Hour")
{
this.Hour12 = (this.Hour - 1) % 12 + 1;
this.IsAm = this.Hour < 12;
this.IsPm = !this.IsAm;
}
base.OnPropertyChanged(propertyName);
}
}
}
| 24.95122 | 71 | 0.461388 | [
"MIT"
] | nnaabbcc/exercise | windows/pw6e.official/CSharp/Chapter11/ConditionalClockButton/ConditionalClockButton/TwelveHourClock.cs | 1,025 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.rtc.Transform;
using Aliyun.Acs.rtc.Transform.V20180111;
namespace Aliyun.Acs.rtc.Model.V20180111
{
public class DescribeRtcQualityMetricRequest : RpcAcsRequest<DescribeRtcQualityMetricResponse>
{
public DescribeRtcQualityMetricRequest()
: base("rtc", "2018-01-11", "DescribeRtcQualityMetric", "rtc", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
}
private string startTime;
private string subUser;
private string endTime;
private long? ownerId;
private string pubUser;
private string appId;
private string channelId;
public string StartTime
{
get
{
return startTime;
}
set
{
startTime = value;
DictionaryUtil.Add(QueryParameters, "StartTime", value);
}
}
public string SubUser
{
get
{
return subUser;
}
set
{
subUser = value;
DictionaryUtil.Add(QueryParameters, "SubUser", value);
}
}
public string EndTime
{
get
{
return endTime;
}
set
{
endTime = value;
DictionaryUtil.Add(QueryParameters, "EndTime", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public string PubUser
{
get
{
return pubUser;
}
set
{
pubUser = value;
DictionaryUtil.Add(QueryParameters, "PubUser", value);
}
}
public string AppId
{
get
{
return appId;
}
set
{
appId = value;
DictionaryUtil.Add(QueryParameters, "AppId", value);
}
}
public string ChannelId
{
get
{
return channelId;
}
set
{
channelId = value;
DictionaryUtil.Add(QueryParameters, "ChannelId", value);
}
}
public override DescribeRtcQualityMetricResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DescribeRtcQualityMetricResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 22.562092 | 134 | 0.646582 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-rtc/Rtc/Model/V20180111/DescribeRtcQualityMetricRequest.cs | 3,452 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Hci.Models;
using Azure.ResourceManager.Models;
namespace Azure.ResourceManager.Hci
{
/// <summary> A class representing the ArcExtension data model. </summary>
public partial class ArcExtensionData : ResourceData
{
/// <summary> Initializes a new instance of ArcExtensionData. </summary>
public ArcExtensionData()
{
PerNodeExtensionDetails = new ChangeTrackingList<PerNodeExtensionState>();
}
/// <summary> Initializes a new instance of ArcExtensionData. </summary>
/// <param name="id"> The id. </param>
/// <param name="name"> The name. </param>
/// <param name="resourceType"> The resourceType. </param>
/// <param name="systemData"> The systemData. </param>
/// <param name="provisioningState"> Provisioning state of the Extension proxy resource. </param>
/// <param name="aggregateState"> Aggregate state of Arc Extensions across the nodes in this HCI cluster. </param>
/// <param name="perNodeExtensionDetails"> State of Arc Extension in each of the nodes. </param>
/// <param name="forceUpdateTag"> How the extension handler should be forced to update even if the extension configuration has not changed. </param>
/// <param name="publisher"> The name of the extension handler publisher. </param>
/// <param name="typePropertiesExtensionParametersType"> Specifies the type of the extension; an example is "CustomScriptExtension". </param>
/// <param name="typeHandlerVersion"> Specifies the version of the script handler. </param>
/// <param name="autoUpgradeMinorVersion"> Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. </param>
/// <param name="settings"> Json formatted public settings for the extension. </param>
/// <param name="protectedSettings"> Protected settings (may contain secrets). </param>
/// <param name="createdBy"> The identity that created the resource. </param>
/// <param name="createdByType"> The type of identity that created the resource. </param>
/// <param name="createdAt"> The timestamp of resource creation (UTC). </param>
/// <param name="lastModifiedBy"> The identity that last modified the resource. </param>
/// <param name="lastModifiedByType"> The type of identity that last modified the resource. </param>
/// <param name="lastModifiedAt"> The timestamp of resource last modification (UTC). </param>
internal ArcExtensionData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, ProvisioningState? provisioningState, ExtensionAggregateState? aggregateState, IReadOnlyList<PerNodeExtensionState> perNodeExtensionDetails, string forceUpdateTag, string publisher, string typePropertiesExtensionParametersType, string typeHandlerVersion, bool? autoUpgradeMinorVersion, object settings, object protectedSettings, string createdBy, Models.CreatedByType? createdByType, DateTimeOffset? createdAt, string lastModifiedBy, Models.CreatedByType? lastModifiedByType, DateTimeOffset? lastModifiedAt) : base(id, name, resourceType, systemData)
{
ProvisioningState = provisioningState;
AggregateState = aggregateState;
PerNodeExtensionDetails = perNodeExtensionDetails;
ForceUpdateTag = forceUpdateTag;
Publisher = publisher;
TypePropertiesExtensionParametersType = typePropertiesExtensionParametersType;
TypeHandlerVersion = typeHandlerVersion;
AutoUpgradeMinorVersion = autoUpgradeMinorVersion;
Settings = settings;
ProtectedSettings = protectedSettings;
CreatedBy = createdBy;
CreatedByType = createdByType;
CreatedAt = createdAt;
LastModifiedBy = lastModifiedBy;
LastModifiedByType = lastModifiedByType;
LastModifiedAt = lastModifiedAt;
}
/// <summary> Provisioning state of the Extension proxy resource. </summary>
public ProvisioningState? ProvisioningState { get; }
/// <summary> Aggregate state of Arc Extensions across the nodes in this HCI cluster. </summary>
public ExtensionAggregateState? AggregateState { get; }
/// <summary> State of Arc Extension in each of the nodes. </summary>
public IReadOnlyList<PerNodeExtensionState> PerNodeExtensionDetails { get; }
/// <summary> How the extension handler should be forced to update even if the extension configuration has not changed. </summary>
public string ForceUpdateTag { get; set; }
/// <summary> The name of the extension handler publisher. </summary>
public string Publisher { get; set; }
/// <summary> Specifies the type of the extension; an example is "CustomScriptExtension". </summary>
public string TypePropertiesExtensionParametersType { get; set; }
/// <summary> Specifies the version of the script handler. </summary>
public string TypeHandlerVersion { get; set; }
/// <summary> Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. </summary>
public bool? AutoUpgradeMinorVersion { get; set; }
/// <summary> Json formatted public settings for the extension. </summary>
public object Settings { get; set; }
/// <summary> Protected settings (may contain secrets). </summary>
public object ProtectedSettings { get; set; }
/// <summary> The identity that created the resource. </summary>
public string CreatedBy { get; set; }
/// <summary> The type of identity that created the resource. </summary>
public Models.CreatedByType? CreatedByType { get; set; }
/// <summary> The timestamp of resource creation (UTC). </summary>
public DateTimeOffset? CreatedAt { get; set; }
/// <summary> The identity that last modified the resource. </summary>
public string LastModifiedBy { get; set; }
/// <summary> The type of identity that last modified the resource. </summary>
public Models.CreatedByType? LastModifiedByType { get; set; }
/// <summary> The timestamp of resource last modification (UTC). </summary>
public DateTimeOffset? LastModifiedAt { get; set; }
}
}
| 69.07 | 670 | 0.699725 | [
"MIT"
] | siegfried01/azure-sdk-for-net | sdk/azurestackhci/Azure.ResourceManager.Hci/src/Generated/ArcExtensionData.cs | 6,907 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BackupJobsOperations operations.
/// </summary>
internal partial class BackupJobsOperations : IServiceOperations<RecoveryServicesBackupClient>, IBackupJobsOperations
{
/// <summary>
/// Initializes a new instance of the BackupJobsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BackupJobsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Provides a pageable list of jobs.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='skipToken'>
/// skipToken Filter.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<JobResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, ODataQuery<JobQueryObject> odataQuery = default(ODataQuery<JobQueryObject>), string skipToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2021-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("skipToken", skipToken);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (skipToken != null)
{
_queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<JobResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Provides a pageable list of jobs.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<JobResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<JobResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 44.130631 | 373 | 0.56109 | [
"MIT"
] | AME-Redmond/azure-sdk-for-net | sdk/recoveryservices-backup/Microsoft.Azure.Management.RecoveryServices.Backup/src/Generated/BackupJobsOperations.cs | 19,594 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("JsonParser")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JsonParser")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("65dabe5c-8881-4ef5-b632-d3099af8ef56")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.513514 | 84 | 0.747118 | [
"MIT"
] | kmuthyala/JsonParser | JsonUtils/JsonUtils/Properties/AssemblyInfo.cs | 1,391 | C# |
/**
* Copyright 2018 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
using Newtonsoft.Json;
namespace IBM.WatsonDeveloperCloud.SpeechToText.v1.Model
{
/// <summary>
/// AcousticModels.
/// </summary>
public class AcousticModels : BaseModel
{
/// <summary>
/// An array of `AcousticModel` objects that provides information about each available custom acoustic model.
/// The array is empty if the requesting credentials own no custom acoustic models (if no language is specified)
/// or own no custom acoustic models for the specified language.
/// </summary>
[JsonProperty("customizations", NullValueHandling = NullValueHandling.Ignore)]
public List<AcousticModel> Customizations { get; set; }
}
}
| 35.526316 | 120 | 0.714815 | [
"Apache-2.0"
] | anlblci/dotnetwatson | src/IBM.WatsonDeveloperCloud.SpeechToText.v1/Model/AcousticModels.cs | 1,350 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Problem 8. Most frequest Number")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Problem 8. Most frequest Number")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a52bb040-d2f4-4139-bbd5-340f81fef003")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.648649 | 84 | 0.747552 | [
"MIT"
] | Supbads/Softuni-Education | 07 ProgrammingFundamentals 05.17/07. Arrays-Exercises/Problem 8. Most frequest Number/Properties/AssemblyInfo.cs | 1,433 | C# |
using DevRelKr.UrlShortener.Domains;
using DevRelKr.UrlShortener.Models.Configurations;
using DevRelKr.UrlShortener.Services;
using FluentAssertions;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace DevRelKr.UrlShortener.FunctionApp.Tests
{
[TestClass]
public class StartUpTests
{
// [TestMethod]
// public void Given_Dependency_When_Configure_Invoked_THen_It_Should_Return_Result()
// {
// var services = new ServiceCollection();
// var builder = new Mock<IFunctionsHostBuilder>();
// builder.SetupGet(p => p.Services).Returns(services);
// var instance = new StartUp();
// instance.Configure(builder.Object);
// services.Should().Contain(p => p.ServiceType == typeof(AppSettings));
// services.Should().Contain(p => p.ServiceType == typeof(IShortenerService));
// services.Should().Contain(p => p.ServiceType == typeof(IUrl));
// }
}
}
| 32.25 | 94 | 0.656331 | [
"MIT"
] | devrel-kr/dvrl-kr | test/DevRelKr.UrlShortener.FunctionApp.Tests/StartUpTests.cs | 1,161 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Services.Social.Messaging
{
using System;
using System.Data;
using System.Xml.Serialization;
using DotNetNuke.Entities;
using DotNetNuke.Entities.Modules;
/// -----------------------------------------------------------------------------
/// Project: DotNetNuke
/// Namespace: DotNetNuke.Entities.Messaging
/// Class: MessageAttachment
/// -----------------------------------------------------------------------------
/// <summary>
/// The MessageAttachment class describes the content attachments associated with a message.
/// </summary>
/// -----------------------------------------------------------------------------
[Serializable]
public class MessageAttachment : BaseEntityInfo, IHydratable
{
private int _messageattachmentID = -1;
/// <summary>
/// Gets or sets messageAttachmentID - The primary key.
/// </summary>
[XmlAttribute]
public int MessageAttachmentID
{
get
{
return this._messageattachmentID;
}
set
{
this._messageattachmentID = value;
}
}
/// <summary>
/// Gets or sets messageID of the message that contains this attachment.
/// </summary>
[XmlAttribute]
public int MessageID { get; set; }
/// <summary>
/// Gets or sets the FileID of the attachment (what will be used against the Files table to provide the attachment).
/// </summary>
[XmlAttribute]
public int FileID { get; set; }
/// <summary>
/// Gets or sets iHydratable.KeyID.
/// </summary>
[XmlIgnore]
public int KeyID
{
get
{
return this.MessageAttachmentID;
}
set
{
this.MessageAttachmentID = value;
}
}
/// <summary>
/// Fill the object with data from database.
/// </summary>
/// <param name="dr">the data reader.</param>
public void Fill(IDataReader dr)
{
this.MessageAttachmentID = Convert.ToInt32(dr["MessageAttachmentID"]);
this.MessageID = Convert.ToInt32(dr["MessageID"]);
this.FileID = Convert.ToInt32(dr["FileID"]);
// add audit column data
this.FillInternal(dr);
}
}
}
| 30.738636 | 124 | 0.504251 | [
"MIT"
] | Acidburn0zzz/Dnn.Platform | DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs | 2,707 | C# |
using System.Threading.Tasks;
namespace BabyYodaBot.Core.Net.WebSocket
{
public interface IConnection
{
void EnqueueSend<T>(T data);
Task SendAsync<T>(T data);
Task<T> ReceiveAsync<T>();
Task SendAsync(Packet packet);
void Close();
bool Closed { get; }
Task KeepAlive();
}
} | 22.933333 | 40 | 0.59593 | [
"MIT"
] | haycc/BabyYoda | src/BabyYodaBot/BabyYodaBot.Core/Net/WebSocket/IConnection.cs | 346 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using SKM.V3.Models;
namespace SKM.V3.Internal
{
/// <summary>
/// <para>
/// This namespace contains methods that are used internally to communicate with the Web API. You will most likely not need to use them.
/// </para>
/// </summary>
internal class NamespaceDoc
{
}
/// <summary>
/// The methods that are being used under the hood.
/// </summary>
public class HelperMethods
{
public static IWebProxy proxy;
private static bool notSet = false;
/// <summary>
/// This should be true in most case for performance reasons.
/// In rare cases, please set this to true.
/// </summary>
public static bool KeepAlive = true;
internal static string DOMAIN = "https://app.cryptolens.io/";
internal static string SERVER = DOMAIN + "api/";
/// <summary>
/// Used to send requests to Web API 3.
/// </summary>
public static T SendRequestToWebAPI3<T>(RequestModel inputParameters,
string typeOfAction,
string token,
int version = 1,
int modelVersion = 1)
{
// converting the input
Dictionary<string, object> inputParams = (from x in inputParameters.GetType().GetProperties() select x)
.ToDictionary(x => x.Name, x => (x.GetGetMethod()
.Invoke(inputParameters, null) == null ? "" : x.GetGetMethod()
.Invoke(inputParameters, null)));
string server = SERVER;
if (KeepAlive)
{
#if !KeepAliveDisabled
using (WebClient client = new WebClient())
{
NameValueCollection reqparm = new NameValueCollection();
foreach (var input in inputParams)
{
if (input.Key == "LicenseServerUrl" && input.Value != null)
{
if (!string.IsNullOrEmpty(input.Value.ToString()))
{
server = input.Value + "/api/";
}
continue;
}
if(input.Value == null) { continue; }
if (input.Value.GetType() == typeof(List<short>))
{
reqparm.Add(input.Key, Newtonsoft.Json.JsonConvert.SerializeObject(input.Value));
}
else
{
reqparm.Add(input.Key, input.Value.ToString());
}
}
reqparm.Add("token", token);
reqparm.Add("v", "1");
reqparm.Add("modelversion", modelVersion.ToString());
// make sure .NET uses the default proxy set up on the client device.
client.Proxy = WebRequest.DefaultWebProxy;
client.Proxy.Credentials = CredentialCache.DefaultCredentials;
try
{
byte[] responsebytes = client.UploadValues(server + typeOfAction, "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responsebody);
}
catch (WebException ex)
{
try
{
using (var sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(sr.ReadToEnd());
}
}
catch (Exception ex2)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(Newtonsoft.Json.JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Error, Message = "An error occurred when contacting the server." }));
}
}
catch (Exception ex)
{
return default(T);
}
}
#else
throw new ArgumentException("Please set Helpers.KeepAlive = false when calling the library with the 'KeepAliveDisabled' flag.");
#endif
}
else
{
using (WebClient client = new CustomWebClient())
{
NameValueCollection reqparm = new NameValueCollection();
foreach (var input in inputParams)
{
if (input.Key == "LicenseServerUrl" && input.Value != null)
{
if (!string.IsNullOrEmpty(input.Value.ToString()))
{
server = input.Value.ToString() + "/api/";
}
continue;
}
if (input.Value == null) { continue; }
if (input.Value.GetType() == typeof(List<short>))
{
reqparm.Add(input.Key, Newtonsoft.Json.JsonConvert.SerializeObject(input.Value));
}
else
{
reqparm.Add(input.Key, input.Value.ToString());
}
}
reqparm.Add("token", token);
reqparm.Add("v", "1");
reqparm.Add("modelversion", modelVersion.ToString());
// make sure .NET uses the default proxy set up on the client device.
client.Proxy = WebRequest.DefaultWebProxy;
client.Proxy.Credentials = CredentialCache.DefaultCredentials;
try
{
byte[] responsebytes = client.UploadValues(server + typeOfAction, "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responsebody);
}
catch (WebException ex)
{
using (var sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(sr.ReadToEnd());
}
}
catch (Exception ex)
{
return default(T);
}
}
}
}
/// <summary>
/// Useful snippets by @Mehrdad
/// http://stackoverflow.com/questions/472906/converting-a-string-to-byte-array
/// </summary>
public static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
/// <summary>
/// Useful snippets by @Mehrdad
/// http://stackoverflow.com/questions/472906/converting-a-string-to-byte-array
/// </summary>
public static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
public static string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
}
// from https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/best-practices/business-logic/set-keepalive-false-interacting-external-hosts-plugin
internal class CustomWebClient : WebClient
{
// Overrides the GetWebRequest method and sets keep alive to false
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest req = (HttpWebRequest)base.GetWebRequest(address);
req.KeepAlive = false;
return req;
}
}
}
| 38.737288 | 235 | 0.470904 | [
"BSD-3-Clause"
] | Cryptolens/cryptolens-dotnet | Cryptolens.Licensing/Core/HelperMethods.cs | 9,144 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LaDanseDiscordBot.Persistence.Entities
{
public enum AuthSessionState
{
Pending,
Consumed,
Removed
}
public class AuthSession
{
public int AuthSessionId { get; set; }
public string Nonce { get; set; }
public long CreatedOn { get; set; }
public AuthSessionState State { get; set; }
public DiscordUser DiscordUser { get; set; }
}
}
| 18.592593 | 52 | 0.623506 | [
"MIT"
] | GuildLaDanse/discord-bot | LaDanseDiscordBot/Persistence/Entities/AuthSession.cs | 504 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Framework;
using Microsoft.DotNet.Helix.Client;
using Microsoft.WindowsAzure.Storage;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.DotNet.Helix.Sdk
{
public class SendHelixJob : HelixTask
{
/// <summary>
/// The 'type' value reported to Helix
/// </summary>
/// <remarks>
/// This value is used to filter and sort jobs on Mission Control
/// </remarks>
[Required]
public string Type { get; set; }
/// <summary>
/// The Helix queue this job should run on
/// </summary>
[Required]
public string TargetQueue { get; set; }
/// <summary>
/// Required if sending anonymous, not allowed if authenticated
/// The GitHub username of the job creator
/// </summary>
public string Creator { get; set; }
/// <summary>
/// <see langword="true"/> when the work items are executing on a Posix shell; <see langword="false"/> otherwise.
/// </summary>
public bool IsPosixShell { get; set; }
/// <summary>
/// When the task finishes, the correlation id of the job that has been created
/// </summary>
[Output]
public string JobCorrelationId { get; set; }
/// <summary>
/// When the task finishes, the results container uri should be available in case we want to download files.
/// </summary>
[Output]
public string ResultsContainerUri { get; set; }
/// <summary>
/// If the job is internal, we need to give the DownloadFromResultsContainer task the Write SAS to download files.
/// </summary>
[Output]
public string ResultsContainerReadSAS { get; set; }
/// <summary>
/// A collection of commands that will run for each work item before any work item commands.
/// Use ';' to separate commands and escape a ';' with ';;'
/// </summary>
public string[] PreCommands { get; set; }
/// <summary>
/// A collection of commands that will run for each work item after any work item commands.
/// Use ';' to separate commands and escape a ';' with ';;'
/// </summary>
public string[] PostCommands { get; set; }
/// <summary>
/// A set of correlation payloads that will be sent for the helix job.
/// </summary>
/// <remarks>
/// These Items can be either:
/// A Directory - The specified directory will be zipped up and sent as a correlation payload
/// A File - The specified archive file will be sent as a correlation payload
/// A Uri - The Item's Uri metadata will be used as a correlation payload
/// </remarks>
public ITaskItem[] CorrelationPayloads { get; set; }
/// <summary>
/// A set of work items that will run in the helix job.
/// </summary>
/// <remarks>
/// Required Metadata:
/// Identity - The WorkItemName
/// Command - The command that is invoked to execute the work item
/// Optional Metadata:
/// NOTE: only a single Payload parameter should be used; they are not to be used in combination
/// PayloadDirectory - A directory that will be zipped up and sent as the Work Item payload
/// PayloadArchive - An archive that will be sent up as the Work Item payload
/// PayloadUri - An uri of the archive that will be sent up as the Work Item payload
/// Timeout - A <see cref="System.TimeSpan"/> string that specifies that Work Item execution timeout
/// PreCommands
/// A collection of commands that will run for this work item before the 'Command' Runs
/// Use ';' to separate commands and escape a ';' with ';;'
/// PostCommands
/// A collection of commands that will run for this work item after the 'Command' Runs
/// Use ';' to separate commands and escape a ';' with ';;'
/// Destination
/// The directory in which to unzip the correlation payload on the Helix agent
/// </remarks>
public ITaskItem[] WorkItems { get; set; }
/// <summary>
/// A set of properties for helix to map the job using architecture and configuration
/// </summary>
/// <remarks>
/// Required Metadata:
/// Identity - The property Key
/// Value - The property Value mapped to the key.
/// </remarks>
public ITaskItem[] HelixProperties { get; set; }
/// <summary>
/// Max automatic retry of workitems which do not return 0
/// </summary>
public int MaxRetryCount { get; set; }
private CommandPayload _commandPayload;
protected override async Task ExecuteCore(CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(AccessToken) && string.IsNullOrEmpty(Creator))
{
Log.LogError("Creator is required when using anonymous access.");
return;
}
if (!string.IsNullOrEmpty(AccessToken) && !string.IsNullOrEmpty(Creator))
{
Log.LogError("Creator is forbidden when using authenticated access.");
return;
}
Type = Type.ToLowerInvariant();
cancellationToken.ThrowIfCancellationRequested();
using (_commandPayload = new CommandPayload(this))
{
var currentHelixApi = HelixApi;
IJobDefinition def = currentHelixApi.Job.Define()
.WithType(Type)
.WithTargetQueue(TargetQueue)
.WithMaxRetryCount(MaxRetryCount);
Log.LogMessage($"Initialized job definition with type '{Type}', and target queue '{TargetQueue}'");
if (!string.IsNullOrEmpty(Creator))
{
def = def.WithCreator(Creator);
Log.LogMessage($"Setting creator to '{Creator}'");
}
Log.LogMessage(MessageImportance.High, $"Uploading payloads for Job on {TargetQueue}...");
if (CorrelationPayloads != null)
{
foreach (ITaskItem correlationPayload in CorrelationPayloads)
{
def = AddCorrelationPayload(def, correlationPayload);
}
}
if (WorkItems != null)
{
foreach (ITaskItem workItem in WorkItems)
{
def = AddWorkItem(def, workItem);
}
}
else
{
Log.LogError("SendHelixJob given no WorkItems to send.");
}
if (_commandPayload.TryGetPayloadDirectory(out string directory))
{
def = def.WithCorrelationPayloadDirectory(directory);
}
Log.LogMessage(MessageImportance.High, $"Finished uploading payloads for Job on {TargetQueue}...");
if (HelixProperties != null)
{
foreach (ITaskItem helixProperty in HelixProperties)
{
def = AddProperty(def, helixProperty);
}
}
// don't send the job if we have errors
if (Log.HasLoggedErrors)
{
return;
}
Log.LogMessage(MessageImportance.High, $"Sending Job to {TargetQueue}...");
cancellationToken.ThrowIfCancellationRequested();
ISentJob job = await def.SendAsync(msg => Log.LogMessage(msg));
JobCorrelationId = job.CorrelationId;
ResultsContainerUri = job.ResultsContainerUri;
ResultsContainerReadSAS = job.ResultsContainerReadSAS;
cancellationToken.ThrowIfCancellationRequested();
}
cancellationToken.ThrowIfCancellationRequested();
}
private IJobDefinition AddProperty(IJobDefinition def, ITaskItem property)
{
if (!property.GetRequiredMetadata(Log, "Identity", out string key))
{
return def;
}
if (!property.GetRequiredMetadata(Log, "Value", out string value))
{
return def;
}
def.WithProperty(key, value);
Log.LogMessage($"Added property '{key}' (value: '{value}') to job definition.");
return def;
}
private IJobDefinition AddWorkItem(IJobDefinition def, ITaskItem workItem)
{
if (!workItem.GetRequiredMetadata(Log, "Identity", out string name))
{
return def;
}
if (!workItem.GetRequiredMetadata(Log, "Command", out string command))
{
return def;
}
Log.LogMessage(MessageImportance.Low, $"Adding work item '{name}'");
var commands = GetCommands(workItem, command).ToList();
IWorkItemDefinitionWithPayload wiWithPayload;
if (commands.Count == 1)
{
wiWithPayload = def.DefineWorkItem(name).WithCommand(commands[0]);
Log.LogMessage(MessageImportance.Low, $" Command: '{commands[0]}'");
}
else
{
string commandFile = _commandPayload.AddCommandFile(commands);
string helixCorrelationPayload =
IsPosixShell ? "$HELIX_CORRELATION_PAYLOAD/" : "%HELIX_CORRELATION_PAYLOAD%\\";
wiWithPayload = def.DefineWorkItem(name).WithCommand(helixCorrelationPayload + commandFile);
Log.LogMessage(MessageImportance.Low, $" Command File: '{commandFile}'");
foreach (string c in commands)
{
Log.LogMessage(MessageImportance.Low, $" {c}");
}
}
string payloadDirectory = workItem.GetMetadata("PayloadDirectory");
string payloadArchive = workItem.GetMetadata("PayloadArchive");
string payloadUri = workItem.GetMetadata("PayloadUri");
IWorkItemDefinition wi;
if (!string.IsNullOrEmpty(payloadUri))
{
wi = wiWithPayload.WithPayloadUri(new Uri(payloadUri));
Log.LogMessage(MessageImportance.Low, $" Uri Payload: '{payloadUri}'");
}
else if (!string.IsNullOrEmpty(payloadDirectory))
{
wi = wiWithPayload.WithDirectoryPayload(payloadDirectory);
Log.LogMessage(MessageImportance.Low, $" Directory Payload: '{payloadDirectory}'");
}
else if (!string.IsNullOrEmpty(payloadArchive))
{
wi = wiWithPayload.WithArchivePayload(payloadArchive);
Log.LogMessage(MessageImportance.Low, $" Archive Payload: '{payloadArchive}'");
}
else
{
wi = wiWithPayload.WithEmptyPayload();
Log.LogMessage(MessageImportance.Low, " Empty Payload");
}
string timeoutString = workItem.GetMetadata("Timeout");
if (!string.IsNullOrEmpty(timeoutString))
{
if (TimeSpan.TryParse(timeoutString, CultureInfo.InvariantCulture, out TimeSpan timeout))
{
wi = wi.WithTimeout(timeout);
Log.LogMessage(MessageImportance.Low, $" Timeout: '{timeout}'");
}
else
{
Log.LogWarning($"Timeout value '{timeoutString}' could not be parsed.");
}
}
else
{
Log.LogMessage(MessageImportance.Low, " Default Timeout");
}
return wi.AttachToJob();
}
private IEnumerable<string> GetCommands(ITaskItem workItem, string workItemCommand)
{
if (PreCommands != null)
{
foreach (string command in PreCommands)
{
yield return command;
}
}
if (workItem.TryGetMetadata("PreCommands", out string workItemPreCommandsString))
{
foreach (string command in SplitCommands(workItemPreCommandsString))
{
yield return command;
}
}
yield return workItemCommand;
string exitCodeVariableName = "_commandExitCode";
// Capture helix command exit code, in case work item command (i.e xunit call) exited with a failure,
// this way we can exit the process honoring that exit code, needed for retry.
yield return IsPosixShell ? $"export {exitCodeVariableName}=$?" : $"set {exitCodeVariableName}=%ERRORLEVEL%";
if (workItem.TryGetMetadata("PostCommands", out string workItemPostCommandsString))
{
foreach (string command in SplitCommands(workItemPostCommandsString))
{
yield return command;
}
}
if (PostCommands != null)
{
foreach (string command in PostCommands)
{
yield return command;
}
}
// Exit with the captured exit code from workitem command.
yield return IsPosixShell ? $"exit ${exitCodeVariableName}" : $"EXIT /b %{exitCodeVariableName}%";
}
private IEnumerable<string> SplitCommands(string value)
{
var sb = new StringBuilder();
using (var enumerator = value.GetEnumerator())
{
char prev = default;
while (enumerator.MoveNext())
{
if (enumerator.Current != ';')
{
if (prev == ';' && sb.Length != 0)
{
var part = sb.ToString().Trim();
if (!string.IsNullOrEmpty(part))
{
yield return part;
}
sb.Length = 0;
}
sb.Append(enumerator.Current);
}
else if (enumerator.Current == ';')
{
if (prev == ';')
{
sb.Append(';');
prev = default;
continue;
}
}
prev = enumerator.Current;
}
}
if (sb.Length != 0)
{
var part = sb.ToString().Trim();
if (!string.IsNullOrEmpty(part))
{
yield return part;
}
}
}
private IJobDefinition AddCorrelationPayload(IJobDefinition def, ITaskItem correlationPayload)
{
string path = correlationPayload.GetMetadata("FullPath");
string uri = correlationPayload.GetMetadata("Uri");
string destination = correlationPayload.GetMetadata("Destination") ?? "";
if (!string.IsNullOrEmpty(uri))
{
Log.LogMessage(MessageImportance.Low, $"Adding Correlation Payload URI '{uri}', destination '{destination}'");
if (!string.IsNullOrEmpty(destination))
{
return def.WithCorrelationPayloadUris(new Dictionary<Uri, string>() { { new Uri(uri), destination } });
}
else
{
return def.WithCorrelationPayloadUris(new Uri(uri));
}
}
if (Directory.Exists(path))
{
string includeDirectoryNameStr = correlationPayload.GetMetadata("IncludeDirectoryName");
bool.TryParse(includeDirectoryNameStr, out bool includeDirectoryName);
Log.LogMessage(MessageImportance.Low, $"Adding Correlation Payload Directory '{path}', destination '{destination}'");
return def.WithCorrelationPayloadDirectory(path, includeDirectoryName, destination);
}
if (File.Exists(path))
{
Log.LogMessage(MessageImportance.Low, $"Adding Correlation Payload Archive '{path}', destination '{destination}'");
return def.WithCorrelationPayloadArchive(path, destination);
}
Log.LogError($"Correlation Payload '{path}' not found.");
return def;
}
}
}
| 38.709534 | 133 | 0.531447 | [
"MIT"
] | AaronRobinsonMSFT/arcade | src/Microsoft.DotNet.Helix/Sdk/SendHelixJob.cs | 17,458 | C# |
using DCL;
using DCL.Components;
using DCL.Helpers;
using DCL.Models;
using System.Collections;
using DCL.Controllers;
using NUnit.Framework;
using Tests;
using UnityEngine;
using UnityEngine.TestTools;
using Assert = UnityEngine.Assertions.Assert;
public class VideoComponenteDesktopShould : IntegrationTestSuite
{
private ParcelScene scene;
/* Remote videos to test locally:
"https://vimeo.com/671880962",
"https://player.vimeo.com/external/552481870.m3u8?s=c312c8533f97e808fccc92b0510b085c8122a875",
"https://theuniverse.club/live/genesisplaza/index.m3u8",
"https://theuniverse.club/live/consensys/index.m3u8",
"https://www.youtube.com/watch?v=LiE1VgWdcQM",
"https://dcl.cubeprohost.com/live/dcl/index.m3u8?sign=4101743660-b5a7da280765e8a17c4d7209b6782872",
"https://206-189-115-14.nip.io/live/dclgoethe/index.m3u8",
"https://peer-lb.decentraland.org/content/contents/QmWPLo8CroLCVC57ja25RKixbXCsNM7SoTsWWnx3TPydkA",
"https://peer-lb.decentraland.org/content/contents/QmTvAo7fTpFRgS1nY4VMxWbzzv4nEHsqs5paQ8euYCKdFi",
"https://peer-lb.decentraland.org/content/contents/Qmf5XAr9gBs3nYEmrmuqQNZK7zpSTfSNtvk2ZmqHq341B8",
"https://ipfs.io/ipfs/QmXkGhWzbAd4kN6xpdi793JNd7ABG9A4eL9ANxNrmDsEba?filename=2021-10-22%2015-12-55.mp4",
"https://carls1987.cafe24.com/video/rhythmical-nft-club.mp4",
"http://carls1987.cafe24.com/video/carls1.mp4",
"https://5caf24a595d94.streamlock.net:1937/8094/8094/playlist.m3u8",
"https://5dcc6a54d90e8c5dc4345c16-s-4.ssai.zype.com/5dcc6a54d90e8c5dc4345c16-s-4/manifest.m3u8"
*/
protected override void InitializeServices(ServiceLocator serviceLocator)
{
DCLVideoTexture.videoPluginWrapperBuilder = () => new VideoPluginWrapper_Native();
serviceLocator.Register<ISceneController>(() => new SceneController());
serviceLocator.Register<IWorldState>(() => new WorldState());
serviceLocator.Register<IRuntimeComponentFactory>(() => new RuntimeComponentFactory());
}
[UnitySetUp]
protected override IEnumerator SetUp()
{
yield return base.SetUp();
scene = TestUtils.CreateTestScene();
CommonScriptableObjects.rendererState.Set(true);
MainSceneFactory.CreateSettingsController();
}
[UnityTest]
[Category("Explicit")]
[Explicit]
public IEnumerator BasicVideo()
{
DCLVideoClip clip =
TestUtils.SharedComponentCreate<DCLVideoClip, DCLVideoClip.Model>(scene, CLASS_ID.VIDEO_CLIP, new DCLVideoClip.Model() { url = "https://player.vimeo.com/external/552481870.m3u8?s=c312c8533f97e808fccc92b0510b085c8122a875" });
yield return clip.routine;
DCLVideoTexture videoTexture = TestUtils.SharedComponentCreate<DCLVideoTexture, DCLVideoTexture.Model>(scene, CLASS_ID.VIDEO_TEXTURE, new DCLVideoTexture.Model() { videoClipId = clip.id, playing = true });
Assert.IsNotNull(videoTexture, "VideoTexture not loaded");
yield return videoTexture.routine;
}
}
| 45.060606 | 236 | 0.755212 | [
"Apache-2.0"
] | decentraland/explorer-desktop | unity-renderer-desktop/Assets/Scripts/MainScripts/DCL/Components/Video/Tests/VideoComponenteDesktopShould.cs | 2,974 | C# |
namespace Funcky;
public static partial class AsyncSequence
{
/// <summary>
/// Generates a sequence that contains the same sequence of elements over and over again as an endless generator.
/// </summary>
/// <typeparam name="TItem">Type of the elements to be cycled.</typeparam>
/// <param name="sequence">The sequence of elements which are cycled. Throws an exception if the sequence is empty.</param>
/// <returns>Returns an infinite IEnumerable repeating the same sequence of elements.</returns>
[Pure]
public static IAsyncBuffer<TItem> CycleRange<TItem>(IAsyncEnumerable<TItem> sequence)
where TItem : notnull
=> CycleBuffer.Create(sequence);
private static class CycleBuffer
{
public static AsyncCycleBuffer<TSource> Create<TSource>(IAsyncEnumerable<TSource> source, Option<int> maxCycles = default)
=> new(source, maxCycles);
}
private sealed class AsyncCycleBuffer<T> : IAsyncBuffer<T>
{
private readonly List<T> _buffer = new();
private readonly IAsyncEnumerator<T> _source;
private readonly Option<int> _maxCycles;
private bool _disposed;
public AsyncCycleBuffer(IAsyncEnumerable<T> source, Option<int> maxCycles = default)
=> (_source, _maxCycles) = (source.GetAsyncEnumerator(), maxCycles);
public async ValueTask DisposeAsync()
{
if (!_disposed)
{
await _source.DisposeAsync().ConfigureAwait(false);
_buffer.Clear();
_disposed = true;
}
}
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
return GetEnumeratorInternal();
}
private async IAsyncEnumerator<T> GetEnumeratorInternal()
{
if (HasNoCycles())
{
yield break;
}
for (var index = 0; true; ++index)
{
ThrowIfDisposed();
if (index == _buffer.Count)
{
if (await _source.MoveNextAsync().ConfigureAwait(false))
{
_buffer.Add(_source.Current);
}
else
{
break;
}
}
yield return _buffer[index];
}
if (_buffer.Count is 0)
{
if (_maxCycles.Match(none: true, some: False))
{
throw new InvalidOperationException("you cannot cycle an empty enumerable");
}
else
{
yield break;
}
}
// this can change on Dispose!
var bufferCount = _buffer.Count;
for (int cycle = 1; IsCycling(cycle); ++cycle)
{
for (var index = 0; index < bufferCount; ++index)
{
ThrowIfDisposed();
yield return _buffer[index];
}
}
}
private bool HasNoCycles()
=> _maxCycles.Match(none: false, some: maxCycles => maxCycles is 0);
private bool IsCycling(int cycle)
=> _maxCycles.Match(
none: true,
some: maxCycles => cycle < maxCycles);
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(CycleBuffer));
}
}
}
}
| 30.941176 | 130 | 0.520913 | [
"Apache-2.0",
"MIT"
] | FreeApophis/Funcky | Funcky.Async/AsyncSequence/AsyncSequence.CycleRange.cs | 3,682 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BolaoNet.Infra.Notification.Mail.Templates
{
public class ApostasBolaoInicialTemplateEmail : BaseTemplateMailUser, ITemplateMail
{
#region Constants
private const string TemplateHtmlFile = "ApostasBolaoInicial.htm";
private const string Title = "Apostas do Bolão - Inicial";
#endregion
#region Constructors/Destructors
public ApostasBolaoInicialTemplateEmail(string currentUserName, string folder)
: base(currentUserName, folder, TemplateHtmlFile, Title, null)
{
}
#endregion
}
}
| 24.655172 | 87 | 0.700699 | [
"MIT"
] | Thoris/BolaoNet | BolaoNet.Infra.Notification.Mail/Templates/ApostasBolaoInicialTemplateEmail.cs | 718 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.18051
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace ResetAurora.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 37.148148 | 152 | 0.549352 | [
"Apache-2.0"
] | hupo376787/Aurora_Intelligent_Adjustment_Mapping_Reporting | ResetAurora/ResetAurora/Properties/Settings.Designer.cs | 1,111 | C# |
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Assignment01.Models;
namespace Assignment01.Models
{
// You can add User data for the user by adding more properties to your User class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
{
return Task.FromResult(GenerateUserIdentity(manager));
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
#region Helpers
namespace Assignment01
{
public static class IdentityHelper
{
// Used for XSRF when linking external logins
public const string XsrfKey = "XsrfId";
public const string ProviderNameKey = "providerName";
public static string GetProviderNameFromRequest(HttpRequest request)
{
return request.QueryString[ProviderNameKey];
}
public const string CodeKey = "code";
public static string GetCodeFromRequest(HttpRequest request)
{
return request.QueryString[CodeKey];
}
public const string UserIdKey = "userId";
public static string GetUserIdFromRequest(HttpRequest request)
{
return HttpUtility.UrlDecode(request.QueryString[UserIdKey]);
}
public static string GetResetPasswordRedirectUrl(string code, HttpRequest request)
{
var absoluteUri = "/Account/ResetPassword?" + CodeKey + "=" + HttpUtility.UrlEncode(code);
return new Uri(request.Url, absoluteUri).AbsoluteUri.ToString();
}
public static string GetUserConfirmationRedirectUrl(string code, string userId, HttpRequest request)
{
var absoluteUri = "/Account/Confirm?" + CodeKey + "=" + HttpUtility.UrlEncode(code) + "&" + UserIdKey + "=" + HttpUtility.UrlEncode(userId);
return new Uri(request.Url, absoluteUri).AbsoluteUri.ToString();
}
private static bool IsLocalUrl(string url)
{
return !string.IsNullOrEmpty(url) && ((url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'))) || (url.Length > 1 && url[0] == '~' && url[1] == '/'));
}
public static void RedirectToReturnUrl(string returnUrl, HttpResponse response)
{
if (!String.IsNullOrEmpty(returnUrl) && IsLocalUrl(returnUrl))
{
response.Redirect(returnUrl);
}
else
{
response.Redirect("~/");
}
}
}
}
#endregion
| 34.851485 | 179 | 0.640341 | [
"MIT"
] | luizerico/Comp229-2016-Assignment-01 | Assignment01/Assignment01/Models/IdentityModels.cs | 3,522 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace WpfComponentApp
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 19.222222 | 43 | 0.67341 | [
"MIT"
] | kwkin/AtomicMapEditor | WpfComponentApp/App.xaml.cs | 348 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Fastly
{
/// <summary>
/// Uploads a TLS certificate to the Fastly Platform TLS service.
///
/// > Each TLS certificate **must** have its corresponding private key uploaded _prior_ to uploading the certificate.
///
/// ## Import
///
/// A certificate can be imported using its Fastly certificate ID, e.g.
///
/// ```sh
/// $ pulumi import fastly:index/tlsPlatformCertificate:TlsPlatformCertificate demo xxxxxxxxxxx
/// ```
/// </summary>
[FastlyResourceType("fastly:index/tlsPlatformCertificate:TlsPlatformCertificate")]
public partial class TlsPlatformCertificate : Pulumi.CustomResource
{
/// <summary>
/// Disable checking whether the root of the certificate chain is trusted. Useful for development purposes to allow use of self-signed CAs. Defaults to false. Write-only on create.
/// </summary>
[Output("allowUntrustedRoot")]
public Output<bool?> AllowUntrustedRoot { get; private set; } = null!;
/// <summary>
/// PEM-formatted certificate.
/// </summary>
[Output("certificateBody")]
public Output<string> CertificateBody { get; private set; } = null!;
/// <summary>
/// ID of TLS configuration to be used to terminate TLS traffic.
/// </summary>
[Output("configurationId")]
public Output<string> ConfigurationId { get; private set; } = null!;
/// <summary>
/// Timestamp (GMT) when the certificate was created.
/// </summary>
[Output("createdAt")]
public Output<string> CreatedAt { get; private set; } = null!;
/// <summary>
/// All the domains (including wildcard domains) that are listed in any certificate's Subject Alternative Names (SAN) list.
/// </summary>
[Output("domains")]
public Output<ImmutableArray<string>> Domains { get; private set; } = null!;
/// <summary>
/// PEM-formatted certificate chain from the `certificate_body` to its root.
/// </summary>
[Output("intermediatesBlob")]
public Output<string> IntermediatesBlob { get; private set; } = null!;
/// <summary>
/// Timestamp (GMT) when the certificate will expire.
/// </summary>
[Output("notAfter")]
public Output<string> NotAfter { get; private set; } = null!;
/// <summary>
/// Timestamp (GMT) when the certificate will become valid.
/// </summary>
[Output("notBefore")]
public Output<string> NotBefore { get; private set; } = null!;
/// <summary>
/// A recommendation from Fastly indicating the key associated with this certificate is in need of rotation.
/// </summary>
[Output("replace")]
public Output<bool> Replace { get; private set; } = null!;
/// <summary>
/// Timestamp (GMT) when the certificate was last updated.
/// </summary>
[Output("updatedAt")]
public Output<string> UpdatedAt { get; private set; } = null!;
/// <summary>
/// Create a TlsPlatformCertificate resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public TlsPlatformCertificate(string name, TlsPlatformCertificateArgs args, CustomResourceOptions? options = null)
: base("fastly:index/tlsPlatformCertificate:TlsPlatformCertificate", name, args ?? new TlsPlatformCertificateArgs(), MakeResourceOptions(options, ""))
{
}
private TlsPlatformCertificate(string name, Input<string> id, TlsPlatformCertificateState? state = null, CustomResourceOptions? options = null)
: base("fastly:index/tlsPlatformCertificate:TlsPlatformCertificate", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing TlsPlatformCertificate resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static TlsPlatformCertificate Get(string name, Input<string> id, TlsPlatformCertificateState? state = null, CustomResourceOptions? options = null)
{
return new TlsPlatformCertificate(name, id, state, options);
}
}
public sealed class TlsPlatformCertificateArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Disable checking whether the root of the certificate chain is trusted. Useful for development purposes to allow use of self-signed CAs. Defaults to false. Write-only on create.
/// </summary>
[Input("allowUntrustedRoot")]
public Input<bool>? AllowUntrustedRoot { get; set; }
/// <summary>
/// PEM-formatted certificate.
/// </summary>
[Input("certificateBody", required: true)]
public Input<string> CertificateBody { get; set; } = null!;
/// <summary>
/// ID of TLS configuration to be used to terminate TLS traffic.
/// </summary>
[Input("configurationId", required: true)]
public Input<string> ConfigurationId { get; set; } = null!;
/// <summary>
/// PEM-formatted certificate chain from the `certificate_body` to its root.
/// </summary>
[Input("intermediatesBlob", required: true)]
public Input<string> IntermediatesBlob { get; set; } = null!;
public TlsPlatformCertificateArgs()
{
}
}
public sealed class TlsPlatformCertificateState : Pulumi.ResourceArgs
{
/// <summary>
/// Disable checking whether the root of the certificate chain is trusted. Useful for development purposes to allow use of self-signed CAs. Defaults to false. Write-only on create.
/// </summary>
[Input("allowUntrustedRoot")]
public Input<bool>? AllowUntrustedRoot { get; set; }
/// <summary>
/// PEM-formatted certificate.
/// </summary>
[Input("certificateBody")]
public Input<string>? CertificateBody { get; set; }
/// <summary>
/// ID of TLS configuration to be used to terminate TLS traffic.
/// </summary>
[Input("configurationId")]
public Input<string>? ConfigurationId { get; set; }
/// <summary>
/// Timestamp (GMT) when the certificate was created.
/// </summary>
[Input("createdAt")]
public Input<string>? CreatedAt { get; set; }
[Input("domains")]
private InputList<string>? _domains;
/// <summary>
/// All the domains (including wildcard domains) that are listed in any certificate's Subject Alternative Names (SAN) list.
/// </summary>
public InputList<string> Domains
{
get => _domains ?? (_domains = new InputList<string>());
set => _domains = value;
}
/// <summary>
/// PEM-formatted certificate chain from the `certificate_body` to its root.
/// </summary>
[Input("intermediatesBlob")]
public Input<string>? IntermediatesBlob { get; set; }
/// <summary>
/// Timestamp (GMT) when the certificate will expire.
/// </summary>
[Input("notAfter")]
public Input<string>? NotAfter { get; set; }
/// <summary>
/// Timestamp (GMT) when the certificate will become valid.
/// </summary>
[Input("notBefore")]
public Input<string>? NotBefore { get; set; }
/// <summary>
/// A recommendation from Fastly indicating the key associated with this certificate is in need of rotation.
/// </summary>
[Input("replace")]
public Input<bool>? Replace { get; set; }
/// <summary>
/// Timestamp (GMT) when the certificate was last updated.
/// </summary>
[Input("updatedAt")]
public Input<string>? UpdatedAt { get; set; }
public TlsPlatformCertificateState()
{
}
}
}
| 40.338983 | 188 | 0.61208 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-fastly | sdk/dotnet/TlsPlatformCertificate.cs | 9,520 | C# |
/*
* Original author: Brian Pratt <bspratt .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2014 University of Washington - Seattle, WA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using pwiz.Skyline.FileUI;
using pwiz.Skyline.Model.Results;
using pwiz.Skyline.Util;
using pwiz.SkylineTestUtil;
namespace TestPerf // Note: tests in the "TestPerf" namespace only run when the global RunPerfTests flag is set
{
/// <summary>
/// Performance tests to verify that changing our zlib implementation isn't
/// going to slow us down with minimization.
/// </summary>
[TestClass]
public class PerfMinimizeResultsTest : AbstractFunctionalTest
{
private static string ZIP_FILE = GetPerfTestDataURL(@"PerfMinimizeResultsTest.zip");
[TestMethod]
public void TestMinimizeResultsPerformance()
{
TestFilesZip = ZIP_FILE; // handles the download if needed
RunFunctionalTest();
}
protected override void DoTest()
{
TestFilesPersistent = new[] { "Buck" };
var testFilesDir = new TestFilesDir(TestContext, TestFilesZip, null, TestFilesPersistent);
string documentPath = testFilesDir.GetTestPath("CM Buck_Lum_Comm_fr III for MS1 paper_v1.sky"); // this will be in user download area as a persistent doc
RunUI(() => SkylineWindow.OpenFile(documentPath));
WaitForConditionUI(() => SkylineWindow.DocumentUI.Settings.MeasuredResults.IsLoaded);
Stopwatch loadStopwatch = new Stopwatch();
var doc = SkylineWindow.Document;
var minimizedFile = testFilesDir.GetTestPath("minimized.sky"); // Not L10N
var cacheFile = Path.ChangeExtension(minimizedFile, ChromatogramCache.EXT);
{
RunUI(() => SkylineWindow.SaveDocument(minimizedFile));
var manageResultsDlg = ShowDialog<ManageResultsDlg>(SkylineWindow.ManageResults);
var minimizeResultsDlg = ShowDialog<MinimizeResultsDlg>(manageResultsDlg.MinimizeResults);
RunUI(() =>
{
minimizeResultsDlg.LimitNoiseTime = false;
});
loadStopwatch.Start();
OkDialog(minimizeResultsDlg, () => minimizeResultsDlg.MinimizeToFile(minimizedFile));
WaitForCondition(() => File.Exists(cacheFile));
WaitForClosedForm(manageResultsDlg);
loadStopwatch.Stop();
}
WaitForDocumentChange(doc);
DebugLog.Info("minimization time = {0}", loadStopwatch.ElapsedMilliseconds);
}
}
}
| 39.686047 | 166 | 0.646352 | [
"Apache-2.0"
] | CSi-Studio/pwiz | pwiz_tools/Skyline/TestPerf/PerfMinimizeResultsTest.cs | 3,415 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MpdBaileyTechnology.Shared.Utils
{
/// <summary>
/// YoUR MOVe cReEP
/// </summary>
public class RoboCop
{
private string[] _Bootup = {
"COMMAND.COM",
"LOAD BIOS",
"BIOS SYSTEM CHECK",
"RAM CHECK",
"CONFIG.SYS",
"BIO.COM INTERFACE",
"TO ROM I/O",
"CONTROLLER",
"COMSPEC.EXE",
"MEMORY.DAT",
"ROBO UTILS",
"SYSTEM BUFFER",
"PARAMETERS",
"PARITY SET",
"MEMORY SET",
"SYSTEM STATUS",
"OK"
};
private string[] _PrimeDirectives ={
"1. SERVE THE PUBLIC TRUST",
"2. PROTECT THE INNOCENT",
"3. UPHOLD THE LAW",
"4. [CLASSIFIED]"
};
private string[] _Quotes ={
"Well give the man a hand!",
"Can you fly, Bobby?",
"I'd buy that for a dollar",
"You know, he's a sweet old man.",
"Pretty simple math, huh, Bob?",
"You better pray that that unholy monster of yours doesn't screw up. ",
"They'll fix you. They fix everything.",
"Looking for me?",
"I know you! You're dead! We killed you!",
"You better watch your back, Bob.",
"Jones is gonna come looking for you.",
"Too bad about Kinney, huh?",
"He fumbled the ball, I was there to pick it up.",
"Soon as some poor schmuck volunteers.",
"Excuse me, I have to go. Somewhere there is a crime happening.",
"Let me make something clear to you. He doesn't have a name. He has a program. He's product.",
"Bitches, leave!",
"See, I got this problem. Cops don't like me. So I don't like cops.",
"Okay Miller! Don't hurt the mayor! We'll give you what you want!",
"Nobody ever takes me seriously! We'll get serious now... and kiss the mayor's ass goodbye!",
"Nice shooting, son. What's your name?",
"Forget it, kid. This guy's a serious asshole.",
"Your client's a scumbag, you're a scumbag, and scumbags see the judge on Monday morning. Now get out of my office, and take laughing boy with you!",
"Murphy, it's you!",
"Please put down your weapon. You have 20 seconds to comply.",
"Four... three... two... one... I am now authorized to use physical force!",
"Thank you for your cooperation. Good night.",
"Book him! What's the charge? He's a cop killer.",
"Dick, you're *fired*!",
"Well guys, the other one was upstairs. She was sweeeeet, mmph-mmm-mmm. I took her out, Ha-ha-ha-ha-ha-ha...",
"You probably don't think I'm a very nice guy... do ya? ",
"I had a guaranteed military sale with ED209! Renovation program! Spare parts for 25 years! Who cares if it worked or not!",
"First, don't mess with me. I'm a desperate man! And second, I want some fresh coffee. And third, I want a recount! And no matter how it turns out, I want my old job back!",
"I'm cashing you out, Bob.",
"Oooh. Guns, guns, guns. C'mon, Sal. The Tigers are playing...",
"Frankie, blow this cocksucker's head off.",
"You call this a GLITCH?",
"I work for Dick Jones! Dick Jones! He's the Number Two Guy at OCP. OCP runs the cops.",
"Don't mess with Jones, man. He'll make sushi out of you.",
"Good night, sweet prince.",
"Nukem. Get them before they get you. Another quality home game from Butler Brothers.",
"Old Detroit has a cancer. That cancer is crime.",
"What? I thought we agreed on total body prosthesis, now lose the arm okay!",
"Shut him down, prep him for surgery.",
"Hey, he's old, we're young, and that's life.",
"Hey, dickey boy, how's tricks? ",
"That's two million workers living in trailers, that means drugs, gambling, prostitution... ",
"We practically are the military.",
"Here at Security Concepts, we're predicting the end of crime in Old Detroit within 40 days. There's a new guy in town. His name is RoboCop.",
"Does it hurt? Does it hurt?",
"Are you a college boy?",
"The Star Wars Space Peace Platform",
"That's life in the big city",
"Hey there buddy boy",
"Good business is where you find it",
"Oh Dick, I'm very disappointed",
"Stay out of trouble",
"Your move creep",
"Dead or alive, you're coming with me",
"And remember, we care",
"Madame, you have suffered an emotional shock. I will notify a rape crisis center.",
"You mind if I, zip this up?",
"Something with reclining leather seats, that goes really fast and gets really shitty gas mileage!"
};
/// <summary>
/// You're gonna be a bad motherfucker
/// </summary>
public IEnumerable<string> Bootup { get { return _Bootup; } }
/// <summary>
/// cAn YOu FLy BobBY
/// </summary>
public IEnumerable<string> PrimeDirectives { get { return _PrimeDirectives; } }
/// <summary>
/// I fucking love this guy
/// </summary>
public IEnumerable<string> Quotes { get { return _Quotes; } }
}
}
| 67.652542 | 209 | 0.393085 | [
"Apache-2.0"
] | PigDogBay/MpdbSharedLibrary | MpdbSharedLibrary/Utils/RoboCop.cs | 7,985 | C# |
// Copyright (c) 2017-2019, Columbia University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Columbia University nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// =============================================================
// Authors:
// Carmine Elvezio, Mengu Sukan, Samuel Silverman, Steven Feiner
// =============================================================
//
//
using System;
namespace MercuryMessaging.Task
{
/// <summary>
/// This class contains transformation threshold information for
/// MmTransformationTaskInfos
/// </summary>
[Serializable]
public class MmTransformTaskThreshold : IMmSerializable {
/// <summary>
/// MmRelayNode angular (in degrees) completion threshold.
/// </summary>
public float AngleThreshold = 5;
/// <summary>
/// MmRelayNode positional completion threshold.
/// </summary>
public float DistanceThreshold = float.MaxValue;
/// <summary>
/// MmRelayNode scalar completion threshold.
/// </summary>
public float ScaleThreshold = float.MaxValue;
/// <summary>
/// Create a default MmTransformTaskThreshold.
/// </summary>
public MmTransformTaskThreshold()
{}
/// <summary>
/// Construct an MmTransformTaskThreshold by setting angle, distance and scale directly.
/// </summary>
/// <param name="angleThreshold">Angular threshold.</param>
/// <param name="distanceThreshold">Distance threshold.</param>
/// <param name="scaleThreshold">Scale threshold.</param>
public MmTransformTaskThreshold(float angleThreshold, float distanceThreshold, float scaleThreshold)
{
AngleThreshold = angleThreshold;
DistanceThreshold = distanceThreshold;
ScaleThreshold = scaleThreshold;
}
/// <summary>
/// Construct MmTransformTaskThreshold by duplicating another threshold.
/// </summary>
/// <param name="orig">Original threshold</param>
public MmTransformTaskThreshold(MmTransformTaskThreshold orig)
{
AngleThreshold = orig.AngleThreshold;
DistanceThreshold = orig.DistanceThreshold;
ScaleThreshold = orig.ScaleThreshold;
}
/// <summary>
/// Duplicate the task threshold.
/// </summary>
/// <returns>Copy of MmTransformTaskThreshold</returns>
public IMmSerializable Copy()
{
return new MmTransformTaskThreshold(this);
}
/// <summary>
/// Deserialize the MmTransformTaskThreshold
/// </summary>
/// <param name="data">Object array representation of a MmTransformTaskThreshold</param>
/// <param name="index">The index of the next element to be read from data</param>
/// <returns>The index of the next element to be read from data</returns>
public int Deserialize(object[] data, int index)
{
AngleThreshold = (float) data[index++];
DistanceThreshold = (float) data[index++];
ScaleThreshold = (float) data[index++];
return index;
}
/// <summary>
/// Serialize the MmTransformTaskThreshold
/// </summary>
/// <returns>Object array representation of a MmTransformTaskThreshold</returns>
public object[] Serialize()
{
object[] thisSerialized = new object[] { AngleThreshold, DistanceThreshold, ScaleThreshold };
return thisSerialized;
}
}
}
| 40.677419 | 108 | 0.642744 | [
"BSD-3-Clause"
] | ColumbiaCGUI/MercuryMessaging | Assets/MercuryMessaging/Task/Transformation/MmTransformTaskThreshold.cs | 5,046 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.SQLite.Interop;
using Roslyn.Utilities;
using SQLitePCL;
namespace Microsoft.CodeAnalysis.SQLite.v2.Interop
{
using static SQLitePersistentStorageConstants;
/// <summary>
/// Encapsulates a connection to a sqlite database. On construction an attempt will be made
/// to open the DB if it exists, or create it if it does not.
///
/// Connections are considered relatively heavyweight and are pooled until the <see cref="SQLitePersistentStorage"/>
/// is <see cref="SQLitePersistentStorage.Dispose"/>d. Connections can be used by different threads,
/// but only as long as they are used by one thread at a time. They are not safe for concurrent
/// use by several threads.
///
/// <see cref="SqlStatement"/>s can be created through the user of <see cref="GetResettableStatement"/>.
/// These statements are cached for the lifetime of the connection and are only finalized
/// (i.e. destroyed) when the connection is closed.
/// </summary>
internal class SqlConnection
{
// Cached utf8 (and null terminated) versions of the common strings we need to pass to sqlite. Used to prevent
// having to convert these names to/from utf16 to utf8 on every call. Sqlite requires these be null terminated.
private static readonly byte[] s_mainNameWithTrailingZero = GetUtf8BytesWithTrailingZero(Database.Main.GetName());
private static readonly byte[] s_writeCacheNameWithTrailingZero = GetUtf8BytesWithTrailingZero(Database.WriteCache.GetName());
private static readonly byte[] s_solutionTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(SolutionDataTableName);
private static readonly byte[] s_projectTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(ProjectDataTableName);
private static readonly byte[] s_documentTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(DocumentDataTableName);
private static readonly byte[] s_checksumColumnNameWithTrailingZero = GetUtf8BytesWithTrailingZero(ChecksumColumnName);
private static readonly byte[] s_dataColumnNameWithTrailingZero = GetUtf8BytesWithTrailingZero(DataColumnName);
private static byte[] GetUtf8BytesWithTrailingZero(string value)
{
var length = Encoding.UTF8.GetByteCount(value);
// Add one for the trailing zero.
var byteArray = new byte[length + 1];
var wrote = Encoding.UTF8.GetBytes(value, 0, value.Length, byteArray, 0);
Contract.ThrowIfFalse(wrote == length);
// Paranoia, but write in the trailing zero no matter what.
byteArray[^1] = 0;
return byteArray;
}
/// <summary>
/// The raw handle to the underlying DB.
/// </summary>
private readonly SafeSqliteHandle _handle;
/// <summary>
/// Our cache of prepared statements for given sql strings.
/// </summary>
private readonly Dictionary<string, SqlStatement> _queryToStatement;
/// <summary>
/// Whether or not we're in a transaction. We currently don't supported nested transactions.
/// If we want that, we can achieve it through sqlite "save points". However, that's adds a
/// lot of complexity that is nice to avoid.
/// </summary>
public bool IsInTransaction { get; private set; }
public static SqlConnection Create(IPersistentStorageFaultInjector? faultInjector, string databasePath)
{
faultInjector?.OnNewConnection();
// Allocate dictionary before doing any sqlite work. That way if it throws
// we don't have to do any additional cleanup.
var queryToStatement = new Dictionary<string, SqlStatement>();
// Use SQLITE_OPEN_NOMUTEX to enable multi-thread mode, where multiple connections can
// be used provided each one is only used from a single thread at a time.
//
// Use SHAREDCACHE so that we can have an in-memory DB that we dump our writes into. We
// need SHAREDCACHE so that all connections see that same in-memory DB. This also
// requires OPEN_URI since we need a `file::memory:` uri for them all to refer to.
//
// see https://sqlite.org/threadsafe.html for more detail
var flags = OpenFlags.SQLITE_OPEN_CREATE |
OpenFlags.SQLITE_OPEN_READWRITE |
OpenFlags.SQLITE_OPEN_NOMUTEX |
OpenFlags.SQLITE_OPEN_SHAREDCACHE |
OpenFlags.SQLITE_OPEN_URI;
var handle = NativeMethods.sqlite3_open_v2(databasePath, (int)flags, vfs: null, out var result);
if (result != Result.OK)
{
handle.Dispose();
throw new SqlException(result, $"Could not open database file: {databasePath} ({result})");
}
try
{
NativeMethods.sqlite3_busy_timeout(handle, (int)TimeSpan.FromMinutes(1).TotalMilliseconds);
var connection = new SqlConnection(handle, queryToStatement);
// Attach (creating if necessary) a singleton in-memory write cache to this connection.
//
// From: https://www.sqlite.org/sharedcache.html Enabling shared-cache for an in-memory database allows
// two or more database connections in the same process to have access to the same in-memory database.
// An in-memory database in shared cache is automatically deleted and memory is reclaimed when the last
// connection to that database closes.
// Using `?mode=memory&cache=shared as writecache` at the end ensures all connections (to the on-disk
// db) see the same db (https://sqlite.org/inmemorydb.html) and the same data when reading and writing.
// i.e. if one connection writes data to this, another connection will see that data when reading.
// Without this, each connection would get their own private memory db independent of all other
// connections.
connection.ExecuteCommand($"attach database '{new Uri(databasePath).AbsoluteUri}?mode=memory&cache=shared' as {Database.WriteCache.GetName()};");
return connection;
}
catch
{
// If we failed to create connection, ensure that we still release the sqlite
// handle.
handle.Dispose();
throw;
}
}
private SqlConnection(SafeSqliteHandle handle, Dictionary<string, SqlStatement> queryToStatement)
{
_handle = handle;
_queryToStatement = queryToStatement;
}
internal void Close_OnlyForUseBySQLiteConnectionPool()
{
// Dispose of the underlying handle at the end of cleanup
using var _ = _handle;
// release all the cached statements we have.
//
// use the struct-enumerator of our dictionary to prevent any allocations here. We
// don't want to risk an allocation causing an OOM which prevents executing the
// following cleanup code.
foreach (var (_, statement) in _queryToStatement)
{
statement.Close_OnlyForUseBySqlConnection();
}
_queryToStatement.Clear();
}
public void ExecuteCommand(string command, bool throwOnError = true)
{
using var resettableStatement = GetResettableStatement(command);
var statement = resettableStatement.Statement;
var result = statement.Step(throwOnError);
if (result != Result.DONE && throwOnError)
{
Throw(result);
}
}
public ResettableSqlStatement GetResettableStatement(string query)
{
if (!_queryToStatement.TryGetValue(query, out var statement))
{
var handle = NativeMethods.sqlite3_prepare_v2(_handle, query, out var result);
try
{
ThrowIfNotOk(result);
statement = new SqlStatement(this, handle);
_queryToStatement[query] = statement;
}
catch
{
handle.Dispose();
throw;
}
}
return new ResettableSqlStatement(statement);
}
public void RunInTransaction<TState>(Action<TState> action, TState state)
{
RunInTransaction(
state =>
{
state.action(state.state);
return (object?)null;
},
(action, state));
}
public TResult RunInTransaction<TState, TResult>(Func<TState, TResult> action, TState state)
{
try
{
if (IsInTransaction)
{
throw new InvalidOperationException("Nested transactions not currently supported");
}
IsInTransaction = true;
ExecuteCommand("begin transaction");
var result = action(state);
ExecuteCommand("commit transaction");
return result;
}
catch (SqlException ex) when (ex.Result == Result.FULL ||
ex.Result == Result.IOERR ||
ex.Result == Result.BUSY ||
ex.Result == Result.LOCKED ||
ex.Result == Result.NOMEM)
{
// See documentation here: https://sqlite.org/lang_transaction.html
// If certain kinds of errors occur within a transaction, the transaction
// may or may not be rolled back automatically. The errors that can cause
// an automatic rollback include:
// SQLITE_FULL: database or disk full
// SQLITE_IOERR: disk I/ O error
// SQLITE_BUSY: database in use by another process
// SQLITE_LOCKED: database in use by another connection in the same process
// SQLITE_NOMEM: out or memory
// It is recommended that applications respond to the errors listed above by
// explicitly issuing a ROLLBACK command. If the transaction has already been
// rolled back automatically by the error response, then the ROLLBACK command
// will fail with an error, but no harm is caused by this.
Rollback(throwOnError: false);
throw;
}
catch (Exception)
{
Rollback(throwOnError: true);
throw;
}
finally
{
IsInTransaction = false;
}
}
private void Rollback(bool throwOnError)
=> ExecuteCommand("rollback transaction", throwOnError);
public int LastInsertRowId()
=> (int)NativeMethods.sqlite3_last_insert_rowid(_handle);
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)]
public Optional<Stream> ReadDataBlob_MustRunInTransaction(Database database, Table table, long rowId)
{
return ReadBlob_MustRunInTransaction(
database, table, Column.Data, rowId,
static (self, blobHandle) => new Optional<Stream>(self.ReadBlob(blobHandle)));
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)]
public Optional<Checksum.HashData> ReadChecksum_MustRunInTransaction(Database database, Table table, long rowId)
{
return ReadBlob_MustRunInTransaction(
database, table, Column.Checksum, rowId,
static (self, blobHandle) =>
{
// If the length of the blob isn't correct, then we can't read a checksum out of this.
var length = NativeMethods.sqlite3_blob_bytes(blobHandle);
if (length != Checksum.HashSize)
return new Optional<Checksum.HashData>();
Span<byte> bytes = stackalloc byte[Checksum.HashSize];
self.ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blobHandle, bytes, offset: 0));
Contract.ThrowIfFalse(MemoryMarshal.TryRead(bytes, out Checksum.HashData result));
return new Optional<Checksum.HashData>(result);
});
}
private Stream ReadBlob(SafeSqliteBlobHandle blob)
{
var length = NativeMethods.sqlite3_blob_bytes(blob);
// If it's a small blob, just read it into one of our pooled arrays, and then
// create a PooledStream over it.
if (length <= SQLitePersistentStorage.MaxPooledByteArrayLength)
{
return ReadBlobIntoPooledStream(blob, length);
}
else
{
// Otherwise, it's a large stream. Just take the hit of allocating.
var bytes = new byte[length];
ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blob, bytes.AsSpan(), offset: 0));
return new MemoryStream(bytes);
}
}
private Stream ReadBlobIntoPooledStream(SafeSqliteBlobHandle blob, int length)
{
var bytes = SQLitePersistentStorage.GetPooledBytes();
try
{
ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blob, new Span<byte>(bytes, start: 0, length), offset: 0));
// Copy those bytes into a pooled stream
return SerializableBytes.CreateReadableStream(bytes, length);
}
finally
{
// Return our small array back to the pool.
SQLitePersistentStorage.ReturnPooledBytes(bytes);
}
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)]
public Optional<T> ReadBlob_MustRunInTransaction<T>(
Database database, Table table, Column column, long rowId,
Func<SqlConnection, SafeSqliteBlobHandle, Optional<T>> readBlob)
{
// NOTE: we do need to do the blob reading in a transaction because of the
// following: https://www.sqlite.org/c3ref/blob_open.html
//
// If the row that a BLOB handle points to is modified by an UPDATE, DELETE,
// or by ON CONFLICT side-effects then the BLOB handle is marked as "expired".
// This is true if any column of the row is changed, even a column other than
// the one the BLOB handle is open on. Calls to sqlite3_blob_read() and
// sqlite3_blob_write() for an expired BLOB handle fail with a return code of
// SQLITE_ABORT.
if (!IsInTransaction)
{
throw new InvalidOperationException("Must read blobs within a transaction to prevent corruption!");
}
var databaseNameBytes = database switch
{
Database.Main => s_mainNameWithTrailingZero,
Database.WriteCache => s_writeCacheNameWithTrailingZero,
_ => throw ExceptionUtilities.UnexpectedValue(database),
};
var tableNameBytes = table switch
{
Table.Solution => s_solutionTableNameWithTrailingZero,
Table.Project => s_projectTableNameWithTrailingZero,
Table.Document => s_documentTableNameWithTrailingZero,
_ => throw ExceptionUtilities.UnexpectedValue(table),
};
var columnNameBytes = column switch
{
Column.Data => s_dataColumnNameWithTrailingZero,
Column.Checksum => s_checksumColumnNameWithTrailingZero,
_ => throw ExceptionUtilities.UnexpectedValue(column),
};
unsafe
{
fixed (byte* databaseNamePtr = databaseNameBytes)
fixed (byte* tableNamePtr = tableNameBytes)
fixed (byte* columnNamePtr = columnNameBytes)
{
// sqlite requires a byte* and a length *not* including the trailing zero. So subtract one from all
// the array lengths to get the length they expect.
const int ReadOnlyFlags = 0;
using var blob = NativeMethods.sqlite3_blob_open(
_handle,
utf8z.FromPtrLen(databaseNamePtr, databaseNameBytes.Length - 1),
utf8z.FromPtrLen(tableNamePtr, tableNameBytes.Length - 1),
utf8z.FromPtrLen(columnNamePtr, columnNameBytes.Length - 1),
rowId,
ReadOnlyFlags,
out var result);
if (result == Result.ERROR)
{
// can happen when rowId points to a row that hasn't been written to yet.
return default;
}
ThrowIfNotOk(result);
return readBlob(this, blob);
}
}
}
public void ThrowIfNotOk(int result)
=> ThrowIfNotOk((Result)result);
public void ThrowIfNotOk(Result result)
=> ThrowIfNotOk(_handle, result);
public static void ThrowIfNotOk(SafeSqliteHandle handle, Result result)
{
if (result != Result.OK)
{
Throw(handle, result);
}
}
public void Throw(Result result)
=> Throw(_handle, result);
public static void Throw(SafeSqliteHandle handle, Result result)
=> throw new SqlException(result,
NativeMethods.sqlite3_errmsg(handle) + Environment.NewLine +
NativeMethods.sqlite3_errstr(NativeMethods.sqlite3_extended_errcode(handle)));
}
}
| 44.751185 | 161 | 0.592534 | [
"MIT"
] | AlekseyTs/roslyn | src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/SqlConnection.cs | 18,887 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _04.SplitByWordCasing
{
class CountNumber
{
static void Main()
{
var readLine = Console.ReadLine();
if (readLine != null)
{
List<string> words = readLine.Split(new[] { ' ', ',', ';', ':', '.', '!', '(', ')', '"', '\'', '/', '\\', '[', ']' },
StringSplitOptions.RemoveEmptyEntries).ToList();
List<string> lowerCase = new List<string>();
List<string> mixedCase = new List<string>();
List<string> upperCase = new List<string>();
foreach (var word in words)
{
bool isAllLowerCase = true;
bool isAllUpperrCase = true;
foreach (char t in word)
{
if (char.IsLower(t))
{
isAllUpperrCase = false;
}
else if (char.IsUpper(t))
{
isAllLowerCase = false;
}
else
{
isAllLowerCase = false;
isAllUpperrCase = false;
}
}
if (isAllLowerCase)
{
lowerCase.Add(word);
}
else if (isAllUpperrCase)
{
upperCase.Add(word);
}
else
{
mixedCase.Add(word);
}
}
Console.WriteLine("Lower-case: {0}", string.Join(", ", lowerCase));
Console.WriteLine("Mixed-case: {0}", string.Join(", ", mixedCase));
Console.WriteLine("Upper-case: {0}", string.Join(", ", upperCase));
}
}
}
} | 35.62069 | 133 | 0.3606 | [
"MIT"
] | fastline32/TechModule | Lists-Lab/04.SplitByWordCasing/Program.cs | 2,068 | C# |
/*----------------------------------------------------------------
Copyright (C) 2017 Senparc
文件名:WeixinException.cs
文件功能描述:微信自定义异常基类
创建标识:Senparc - 20150211
修改标识:Senparc - 20150303
修改描述:整理接口
修改标识:Senparc - 20161225
修改描述:v4.9.7 完善日志记录
修改标识:Senparc - 20170101
修改描述:v4.9.9 优化WeixinTrace
修改标识:Senparc - 20170102
修改描述:v4.9.10 添加AccessTokenOrAppId属性
----------------------------------------------------------------*/
using System;
namespace Senparc.Weixin.Exceptions
{
/// <summary>
/// 微信自定义异常基类
/// </summary>
public class WeixinException : ApplicationException
{
/// <summary>
/// 当前正在请求的公众号AccessToken或AppId
/// </summary>
public string AccessTokenOrAppId { get; set; }
/// <summary>
/// WeixinException
/// </summary>
/// <param name="message">异常消息</param>
/// <param name="logged">是否已经使用WeixinTrace记录日志,如果没有,WeixinException会进行概要记录</param>
public WeixinException(string message, bool logged = false)
: this(message, null, logged)
{
}
/// <summary>
/// WeixinException
/// </summary>
/// <param name="message">异常消息</param>
/// <param name="inner">内部异常信息</param>
/// <param name="logged">是否已经使用WeixinTrace记录日志,如果没有,WeixinException会进行概要记录</param>
public WeixinException(string message, Exception inner, bool logged = false)
: base(message, inner)
{
if (!logged)
{
//WeixinTrace.Log(string.Format("WeixinException({0}):{1}", this.GetType().Name, message));
WeixinTrace.WeixinExceptionLog(this);
}
}
}
}
| 27.138462 | 107 | 0.530612 | [
"Apache-2.0"
] | liyujun1989/WeiXinMPSDK | src/Senparc.Weixin/Senparc.Weixin/Exceptions/WeixinException.cs | 2,094 | C# |
using NUnit.Framework;
using System;
using akarnokd.reactive_extensions;
namespace akarnokd.reactive_extensions_test.single
{
[TestFixture]
public class SingleNeverTest
{
[Test]
public void Basic()
{
SingleSource.Never<int>()
.Test()
.AssertSubscribed()
.AssertEmpty();
}
}
}
| 19.3 | 50 | 0.559585 | [
"Apache-2.0"
] | akarnokd/reactive-extensions | reactive-extensions-test/single/SingleNeverTest.cs | 388 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Web;
using System.Web.Mvc;
using Hospital_Management_System.CollectionViewModels;
using Hospital_Management_System.Models;
using Microsoft.AspNet.Identity;
using System.Data.Entity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Hospital_Management_System.Controllers
{
public class DoctorController : Controller
{
private ApplicationDbContext db;
//Constructor
public DoctorController()
{
db = new ApplicationDbContext();
}
//Destructor
protected override void Dispose(bool disposing)
{
db.Dispose();
}
// GET: Doctor
[Authorize(Roles = "Doctor")]
public ActionResult Index(string message)
{
var date = DateTime.Now.Date;
ViewBag.Messege = message;
var user = User.Identity.GetUserId();
var doctor = db.Doctors.Single(c => c.ApplicationUserId == user);
var model = new CollectionOfAll
{
Ambulances = db.Ambulances.ToList(),
Departments = db.Department.ToList(),
Doctors = db.Doctors.ToList(),
Patients = db.Patients.ToList(),
Medicines = db.Medicines.ToList(),
ActiveAppointments = db.Appointments.Where(c => c.DoctorId == doctor.Id).Where(c => c.Status).Where(c => c.AppointmentDate >= date).ToList(),
PendingAppointments = db.Appointments.Where(c => c.DoctorId == doctor.Id).Where(c => c.Status == false).Where(c => c.AppointmentDate >= date).ToList(),
AmbulanceDrivers = db.AmbulanceDrivers.ToList(),
Announcements = db.Announcements.Where(c => c.AnnouncementFor == "Doctor").ToList()
};
return View(model);
}
//Add Prescription
[Authorize(Roles = "Doctor")]
public ActionResult AddPrescription()
{
var collection = new PrescriptionCollection
{
Prescription = new Prescription(),
Patients = db.Patients.ToList()
};
return View(collection);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddPrescription(PrescriptionCollection model)
{
string user = User.Identity.GetUserId();
var patient = db.Patients.Single(c => c.Id == model.Prescription.PatientId);
var doctor = db.Doctors.Single(c => c.ApplicationUserId == user);
var schedule = db.Schedules.Single(c => c.DoctorId == doctor.Id);
var patientuser = db.Users.Single(c => c.Id == patient.ApplicationUserId);
var prescription = new Prescription
{
PatientId = model.Prescription.PatientId,
DoctorId = doctor.Id,
DoctorName = doctor.FullName,
DoctorSpecialization = doctor.Specialization,
PatientName = patient.FullName,
PatientGender = patient.Gender,
UserName = patientuser.UserName,
MedicalTest1 = model.Prescription.MedicalTest1,
MedicalTest2 = model.Prescription.MedicalTest2,
MedicalTest3 = model.Prescription.MedicalTest3,
MedicalTest4 = model.Prescription.MedicalTest4,
Medicine1 = model.Prescription.Medicine1,
Medicine2 = model.Prescription.Medicine2,
Medicine3 = model.Prescription.Medicine3,
Medicine4 = model.Prescription.Medicine4,
Medicine5 = model.Prescription.Medicine5,
Medicine6 = model.Prescription.Medicine6,
Medicine7 = model.Prescription.Medicine7,
Morning1 = model.Prescription.Morning1,
Morning2 = model.Prescription.Morning2,
Morning3 = model.Prescription.Morning3,
Morning4 = model.Prescription.Morning4,
Morning5 = model.Prescription.Morning5,
Morning6 = model.Prescription.Morning6,
Morning7 = model.Prescription.Morning7,
Afternoon1 = model.Prescription.Afternoon1,
Afternoon2 = model.Prescription.Afternoon2,
Afternoon3 = model.Prescription.Afternoon3,
Afternoon4 = model.Prescription.Afternoon4,
Afternoon5 = model.Prescription.Afternoon5,
Afternoon6 = model.Prescription.Afternoon6,
Afternoon7 = model.Prescription.Afternoon7,
Evening1 = model.Prescription.Evening1,
Evening2 = model.Prescription.Evening2,
Evening3 = model.Prescription.Evening3,
Evening4 = model.Prescription.Evening4,
Evening5 = model.Prescription.Evening5,
Evening6 = model.Prescription.Evening6,
Evening7 = model.Prescription.Evening7,
CheckUpAfterDays = model.Prescription.CheckUpAfterDays,
PrescriptionAddDate = DateTime.Now.Date,
DoctorTiming = "From " + schedule.AvailableStartTime.ToShortTimeString() + " to " + schedule.AvailableEndTime.ToShortTimeString()
};
db.Prescription.Add(prescription);
db.SaveChanges();
return RedirectToAction("ListOfPrescription");
}
//List of Prescription
[Authorize(Roles = "Doctor")]
public ActionResult ListOfPrescription()
{
var user = User.Identity.GetUserId();
var doctor = db.Doctors.Single(c => c.ApplicationUserId == user);
var prescription = db.Prescription.Where(c => c.DoctorId == doctor.Id).ToList();
return View(prescription);
}
//View Of Prescription
[Authorize(Roles = "Doctor")]
public ActionResult ViewPrescription(int id)
{
var prescription = db.Prescription.Single(c => c.Id == id);
return View(prescription);
}
//Delete Prescription
[Authorize(Roles = "Doctor")]
public ActionResult DeletePrescription(int? id)
{
return View();
}
[HttpPost, ActionName("DeletePrescription")]
[ValidateAntiForgeryToken]
public ActionResult DeletePrescription(int id)
{
var prescription = db.Prescription.Single(c => c.Id == id);
db.Prescription.Remove(prescription);
db.SaveChanges();
return RedirectToAction("ListOfPrescription");
}
//Edit Prescription
[Authorize(Roles = "Doctor")]
public ActionResult EditPrescription(int id)
{
var prescription = db.Prescription.Single(c => c.Id == id);
return View(prescription);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPrescription(int id, Prescription model)
{
var prescription = db.Prescription.Single(c => c.Id == id);
prescription.MedicalTest1 = model.MedicalTest1;
prescription.MedicalTest2 = model.MedicalTest2;
prescription.MedicalTest3 = model.MedicalTest3;
prescription.MedicalTest4 = model.MedicalTest4;
prescription.Medicine1 = model.Medicine1;
prescription.Medicine2 = model.Medicine2;
prescription.Medicine3 = model.Medicine3;
prescription.Medicine4 = model.Medicine4;
prescription.Medicine5 = model.Medicine5;
prescription.Medicine6 = model.Medicine6;
prescription.Medicine7 = model.Medicine7;
prescription.Morning1 = model.Morning1;
prescription.Morning2 = model.Morning2;
prescription.Morning3 = model.Morning3;
prescription.Morning4 = model.Morning4;
prescription.Morning5 = model.Morning5;
prescription.Morning6 = model.Morning6;
prescription.Morning7 = model.Morning7;
prescription.Afternoon1 = model.Afternoon1;
prescription.Afternoon2 = model.Afternoon2;
prescription.Afternoon3 = model.Afternoon3;
prescription.Afternoon4 = model.Afternoon4;
prescription.Afternoon5 = model.Afternoon5;
prescription.Afternoon6 = model.Afternoon6;
prescription.Afternoon7 = model.Afternoon7;
prescription.Evening1 = model.Evening1;
prescription.Evening2 = model.Evening2;
prescription.Evening3 = model.Evening3;
prescription.Evening4 = model.Evening4;
prescription.Evening5 = model.Evening5;
prescription.Evening6 = model.Evening6;
prescription.Evening7 = model.Evening7;
prescription.CheckUpAfterDays = model.CheckUpAfterDays;
db.SaveChanges();
return RedirectToAction("ListOfPrescription");
}
//End Prescription Section
//Start Schedule Section
//Check his Schedule
[Authorize(Roles = "Doctor")]
public ActionResult ScheduleDetail()
{
string user = User.Identity.GetUserId();
var doctor = db.Doctors.Single(c => c.ApplicationUserId == user);
var schedule = db.Schedules.Single(c => c.DoctorId == doctor.Id);
return View(schedule);
}
//Edit Schedule
[Authorize(Roles = "Doctor")]
public ActionResult EditSchedule(int id)
{
var schedule = db.Schedules.Single(c => c.Id == id);
return View(schedule);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditSchedule(int id, Schedule model)
{
var schedule = db.Schedules.Single(c => c.Id == id);
schedule.AvailableEndDay = model.AvailableEndDay;
schedule.AvailableEndTime = model.AvailableEndTime;
schedule.AvailableStartDay = model.AvailableStartDay;
schedule.AvailableStartTime = model.AvailableStartTime;
schedule.Status = model.Status;
schedule.TimePerPatient = model.TimePerPatient;
db.SaveChanges();
return RedirectToAction("ScheduleDetail");
}
//End schedule Section
//Start Appointment Section
[Authorize(Roles = "Doctor")]
public ActionResult AddAppointment()
{
var collection = new AppointmentCollection
{
Appointment = new Appointment(),
Patients = db.Patients.ToList()
};
return View(collection);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddAppointment(AppointmentCollection model)
{
string user = User.Identity.GetUserId();
var collection = new AppointmentCollection
{
Appointment = model.Appointment,
Patients = db.Patients.ToList()
};
if (model.Appointment.AppointmentDate >= DateTime.Now.Date)
{
var doctor = db.Doctors.Single(c => c.ApplicationUserId == user);
var appointment = new Appointment();
appointment.PatientId = model.Appointment.PatientId;
appointment.DoctorId = doctor.Id;
appointment.AppointmentDate = model.Appointment.AppointmentDate;
appointment.Problem = model.Appointment.Problem;
appointment.Status = model.Appointment.Status;
db.Appointments.Add(appointment);
db.SaveChanges();
if (model.Appointment.Status == true)
{
return RedirectToAction("ActiveAppointments");
}
else
{
return RedirectToAction("PendingAppointments");
}
}
ViewBag.Messege = "Please Enter the Date greater than today or equal!!";
return View(collection);
}
//List of Active Appointments
[Authorize(Roles = "Doctor")]
public ActionResult ActiveAppointments()
{
var user = User.Identity.GetUserId();
var doctor = db.Doctors.Single(c => c.ApplicationUserId == user);
var date = DateTime.Now.Date;
var appointment = db.Appointments.Include(c => c.Doctor).Include(c => c.Patient).Where(c => c.DoctorId == doctor.Id).Where(c => c.Status == true).Where(c => c.AppointmentDate >= date).ToList();
return View(appointment);
}
//List of Pending Appointments
public ActionResult PendingAppointments()
{
var user = User.Identity.GetUserId();
var doctor = db.Doctors.Single(c => c.ApplicationUserId == user);
var date = DateTime.Now.Date;
var appointment = db.Appointments.Include(c => c.Doctor).Include(c => c.Patient).Where(c => c.DoctorId == doctor.Id).Where(c => c.Status == false).Where(c => c.AppointmentDate >= date).ToList();
return View(appointment);
}
//Edit Appointment
[Authorize(Roles = "Doctor")]
public ActionResult EditAppointment(int id)
{
var collection = new AppointmentCollection
{
Appointment = db.Appointments.Single(c => c.Id == id),
Patients = db.Patients.ToList()
};
return View(collection);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditAppointment(int id, AppointmentCollection model)
{
var collection = new AppointmentCollection
{
Appointment = model.Appointment,
Patients = db.Patients.ToList()
};
if (model.Appointment.AppointmentDate >= DateTime.Now.Date)
{
var appointment = db.Appointments.Single(c => c.Id == id);
appointment.PatientId = model.Appointment.PatientId;
appointment.AppointmentDate = model.Appointment.AppointmentDate;
appointment.Problem = model.Appointment.Problem;
appointment.Status = model.Appointment.Status;
db.SaveChanges();
if (model.Appointment.Status == true)
{
return RedirectToAction("ActiveAppointments");
}
else
{
return RedirectToAction("PendingAppointments");
}
}
ViewBag.Messege = "Please Enter the Date greater than today or equal!!";
return View(collection);
}
//Detail of appointment
[Authorize(Roles = "Doctor")]
public ActionResult DetailOfAppointment(int id)
{
var appointment = db.Appointments.Include(c => c.Doctor).Include(c => c.Patient).Single(c => c.Id == id);
return View(appointment);
}
//Delete Appointment
[Authorize(Roles = "Doctor")]
public ActionResult DeleteAppointment(int? id)
{
var appointment = db.Appointments.Single(c => c.Id == id);
return View(appointment);
}
[HttpPost, ActionName("DeleteAppointment")]
[ValidateAntiForgeryToken]
public ActionResult DeleteAppointment(int id)
{
var appointment = db.Appointments.Single(c => c.Id == id);
db.Appointments.Remove(appointment);
db.SaveChanges();
if (appointment.Status)
{
return RedirectToAction("ActiveAppointments");
}
else
{
return RedirectToAction("PendingAppointments");
}
}
}
} | 40.612658 | 206 | 0.581536 | [
"MIT"
] | obadiahkorir/Hospital-Management | Hospital Management System/Controllers/DoctorController.cs | 16,044 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using NSubstitute;
using NuKeeper.Abstractions.CollaborationModels;
using NuKeeper.Abstractions.CollaborationPlatform;
using NuKeeper.Abstractions.Configuration;
using NuKeeper.Abstractions.Git;
using NuKeeper.Abstractions.Logging;
using NuKeeper.Abstractions.Output;
using NuKeeper.Collaboration;
using NuKeeper.Commands;
using NuKeeper.Engine;
using NuKeeper.GitHub;
using NuKeeper.Inspection.Files;
using NuKeeper.Inspection.Logging;
using NUnit.Framework;
namespace NuKeeper.Tests.Commands
{
[TestFixture]
public class RepositoryCommandTests
{
private IEnvironmentVariablesProvider _environmentVariablesProvider;
[SetUp]
public void Setup()
{
_environmentVariablesProvider = Substitute.For<IEnvironmentVariablesProvider>();
}
[Test]
public async Task ShouldCallEngineAndNotSucceedWithoutParams()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(FileSettings.Empty());
var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider);
var settingsReaders = new List<ISettingsReader> { settingReader };
var collaborationFactory = GetCollaborationFactory(_environmentVariablesProvider, settingsReaders);
var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders);
var status = await command.OnExecute();
Assert.That(status, Is.EqualTo(-1));
await engine
.DidNotReceive()
.Run(Arg.Any<SettingsContainer>());
}
[Test]
public async Task ShouldCallEngineAndSucceedWithRequiredGithubParams()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(FileSettings.Empty());
var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider);
var settingsReaders = new List<ISettingsReader> { settingReader };
var collaborationFactory = GetCollaborationFactory(_environmentVariablesProvider, settingsReaders);
var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders)
{
PersonalAccessToken = "abc",
RepositoryUri = "http://github.com/abc/abc"
};
var status = await command.OnExecute();
Assert.That(status, Is.EqualTo(0));
await engine
.Received(1)
.Run(Arg.Any<SettingsContainer>());
}
[Test]
public async Task ShouldInitialiseCollaborationFactory()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(FileSettings.Empty());
var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider);
var settingsReaders = new List<ISettingsReader> { settingReader };
var collaborationFactory = Substitute.For<ICollaborationFactory>();
collaborationFactory.Settings.Returns(new CollaborationPlatformSettings());
var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders)
{
PersonalAccessToken = "abc",
RepositoryUri = "http://github.com/abc/abc",
ForkMode = ForkMode.PreferSingleRepository
};
await command.OnExecute();
await collaborationFactory
.Received(1)
.Initialise(
Arg.Is(new Uri("https://api.github.com")),
Arg.Is("abc"),
Arg.Is<ForkMode?>(ForkMode.PreferSingleRepository),
Arg.Is((Platform?)null));
}
[Test]
public async Task ShouldInitialiseForkModeFromFile()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(
new FileSettings
{
ForkMode = ForkMode.PreferFork
});
var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider);
var settingsReaders = new List<ISettingsReader> { settingReader };
var collaborationFactory = Substitute.For<ICollaborationFactory>();
collaborationFactory.Settings.Returns(new CollaborationPlatformSettings());
var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders)
{
PersonalAccessToken = "abc",
RepositoryUri = "http://github.com/abc/abc",
ForkMode = null
};
await command.OnExecute();
await collaborationFactory
.Received(1)
.Initialise(
Arg.Is(new Uri("https://api.github.com")),
Arg.Is("abc"),
Arg.Is<ForkMode?>(ForkMode.PreferFork),
Arg.Is((Platform?)null));
}
[Test]
public async Task ShouldInitialisePlatformFromFile()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(
new FileSettings
{
Platform = Platform.BitbucketLocal
});
var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider);
var settingsReaders = new List<ISettingsReader> { settingReader };
var collaborationFactory = Substitute.For<ICollaborationFactory>();
collaborationFactory.Settings.Returns(new CollaborationPlatformSettings());
var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders)
{
PersonalAccessToken = "abc",
RepositoryUri = "http://github.com/abc/abc",
ForkMode = null
};
await command.OnExecute();
await collaborationFactory
.Received(1)
.Initialise(
Arg.Is(new Uri("https://api.github.com")),
Arg.Is("abc"),
Arg.Is((ForkMode?)null),
Arg.Is((Platform?)Platform.BitbucketLocal));
}
[Test]
public async Task ShouldPopulateSourceControlServerSettings()
{
var fileSettings = FileSettings.Empty();
var (settings, platformSettings) = await CaptureSettings(fileSettings);
Assert.That(platformSettings, Is.Not.Null);
Assert.That(platformSettings.Token, Is.Not.Null);
Assert.That(platformSettings.Token, Is.EqualTo("testToken"));
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Scope, Is.EqualTo(ServerScope.Repository));
Assert.That(settings.SourceControlServerSettings.OrganisationName, Is.Null);
}
[Test]
public async Task EmptyFileResultsInDefaultSettings()
{
var fileSettings = FileSettings.Empty();
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.PackageFilters.MinimumAge, Is.EqualTo(TimeSpan.FromDays(7)));
Assert.That(settings.PackageFilters.Excludes, Is.Null);
Assert.That(settings.PackageFilters.Includes, Is.Null);
Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(3));
Assert.That(settings.UserSettings, Is.Not.Null);
Assert.That(settings.UserSettings.AllowedChange, Is.EqualTo(VersionChange.Major));
Assert.That(settings.UserSettings.NuGetSources, Is.Null);
Assert.That(settings.UserSettings.OutputDestination, Is.EqualTo(OutputDestination.Console));
Assert.That(settings.UserSettings.OutputFormat, Is.EqualTo(OutputFormat.Text));
Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(1));
Assert.That(settings.UserSettings.ConsolidateUpdatesInSinglePullRequest, Is.False);
Assert.That(settings.BranchSettings, Is.Not.Null);
Assert.That(settings.BranchSettings.BranchNamePrefix, Is.Null);
Assert.That(settings.BranchSettings.DeleteBranchAfterMerge, Is.EqualTo(true));
Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Null);
Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Null);
}
[Test]
public async Task WillReadApiFromFile()
{
var fileSettings = new FileSettings
{
Api = "http://github.contoso.com/"
};
var (_, platformSettings) = await CaptureSettings(fileSettings);
Assert.That(platformSettings, Is.Not.Null);
Assert.That(platformSettings.BaseApiUrl, Is.Not.Null);
Assert.That(platformSettings.BaseApiUrl, Is.EqualTo(new Uri("http://github.contoso.com/")));
}
[Test]
public async Task WillReadLabelFromFile()
{
var fileSettings = new FileSettings
{
Label = new List<string> { "testLabel" }
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Labels, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Labels, Has.Count.EqualTo(1));
Assert.That(settings.SourceControlServerSettings.Labels, Does.Contain("testLabel"));
}
[Test]
public async Task WillReadMaxPackageUpdatesFromFile()
{
var fileSettings = new FileSettings
{
MaxPackageUpdates = 42
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(42));
}
[Test]
public async Task WillReadConsolidateFromFile()
{
var fileSettings = new FileSettings
{
Consolidate = true
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.UserSettings.ConsolidateUpdatesInSinglePullRequest, Is.True);
}
[Test]
public async Task WillReadBranchNamePrefixFromFile()
{
var fileSettings = new FileSettings
{
BranchNamePrefix = "nukeeper/"
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.BranchSettings, Is.Not.Null);
Assert.That(settings.BranchSettings.BranchNamePrefix, Is.EqualTo("nukeeper/"));
}
[Test]
public async Task WillNotReadMaxRepoFromFile()
{
var fileSettings = new FileSettings
{
MaxRepo = 42
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(1));
}
[Test]
public async Task MaxPackageUpdatesFromCommandLineOverridesFiles()
{
var fileSettings = new FileSettings
{
MaxPackageUpdates = 42
};
var (settings, _) = await CaptureSettings(fileSettings, false, 101);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(101));
}
[Test]
public async Task LabelsOnCommandLineWillReplaceFileLabels()
{
var fileSettings = new FileSettings
{
Label = new List<string> { "testLabel" }
};
var (settings, _) = await CaptureSettings(fileSettings, true);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Labels, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Labels, Has.Count.EqualTo(2));
Assert.That(settings.SourceControlServerSettings.Labels, Does.Contain("runLabel1"));
Assert.That(settings.SourceControlServerSettings.Labels, Does.Contain("runLabel2"));
Assert.That(settings.SourceControlServerSettings.Labels, Does.Not.Contain("testLabel"));
}
public static async Task<(SettingsContainer settingsContainer, CollaborationPlatformSettings platformSettings)> CaptureSettings(
FileSettings settingsIn,
bool addLabels = false,
int? maxPackageUpdates = null)
{
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
var environmentVariablesProvider = Substitute.For<IEnvironmentVariablesProvider>();
fileSettings.GetSettings().Returns(settingsIn);
var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), environmentVariablesProvider);
var settingsReaders = new List<ISettingsReader> { settingReader };
var collaborationFactory = GetCollaborationFactory(environmentVariablesProvider, settingsReaders);
SettingsContainer settingsOut = null;
var engine = Substitute.For<ICollaborationEngine>();
await engine.Run(Arg.Do<SettingsContainer>(x => settingsOut = x));
var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders);
command.PersonalAccessToken = "testToken";
command.RepositoryUri = "http://github.com/test/test";
if (addLabels)
{
command.Label = new List<string> { "runLabel1", "runLabel2" };
}
command.MaxPackageUpdates = maxPackageUpdates;
await command.OnExecute();
return (settingsOut, collaborationFactory.Settings);
}
[Test]
public async Task UseCustomTargetBranchIfParameterIsProvided()
{
var testUri = new Uri("https://github.com");
var collaborationFactorySubstitute = Substitute.For<ICollaborationFactory>();
collaborationFactorySubstitute.ForkFinder.FindPushFork(Arg.Any<string>(), Arg.Any<ForkData>()).Returns(Task.FromResult(new ForkData(testUri, "nukeeper", "nukeeper")));
var updater = Substitute.For<IRepositoryUpdater>();
var gitEngine = new GitRepositoryEngine(updater, collaborationFactorySubstitute, Substitute.For<IFolderFactory>(),
Substitute.For<INuKeeperLogger>(), Substitute.For<IRepositoryFilter>());
await gitEngine.Run(new RepositorySettings
{
RepositoryUri = testUri,
RemoteInfo = new RemoteInfo()
{
BranchName = "custombranch",
},
RepositoryOwner = "nukeeper",
RepositoryName = "nukeeper"
}, new GitUsernamePasswordCredentials()
{
Password = "..",
Username = "nukeeper"
}, new SettingsContainer()
{
SourceControlServerSettings = new SourceControlServerSettings()
{
Scope = ServerScope.Repository
}
}, null);
await updater.Received().Run(Arg.Any<IGitDriver>(),
Arg.Is<RepositoryData>(r => r.DefaultBranch == "custombranch"), Arg.Any<SettingsContainer>());
}
[Test]
public async Task UseCustomTargetBranchIfParameterIsProvidedForLocal()
{
var testUri = new Uri("https://github.com");
var collaborationFactorySubstitute = Substitute.For<ICollaborationFactory>();
collaborationFactorySubstitute.ForkFinder.FindPushFork(Arg.Any<string>(), Arg.Any<ForkData>()).Returns(Task.FromResult(new ForkData(testUri, "nukeeper", "nukeeper")));
var updater = Substitute.For<IRepositoryUpdater>();
var gitEngine = new GitRepositoryEngine(updater, collaborationFactorySubstitute, Substitute.For<IFolderFactory>(),
Substitute.For<INuKeeperLogger>(), Substitute.For<IRepositoryFilter>());
await gitEngine.Run(new RepositorySettings
{
RepositoryUri = testUri,
RemoteInfo = new RemoteInfo()
{
LocalRepositoryUri = testUri,
BranchName = "custombranch",
WorkingFolder = new Uri(Assembly.GetExecutingAssembly().Location),
RemoteName = "github"
},
RepositoryOwner = "nukeeper",
RepositoryName = "nukeeper"
}, new GitUsernamePasswordCredentials()
{
Password = "..",
Username = "nukeeper"
}, new SettingsContainer()
{
SourceControlServerSettings = new SourceControlServerSettings()
{
Scope = ServerScope.Repository
}
}, null);
await updater.Received().Run(Arg.Any<IGitDriver>(),
Arg.Is<RepositoryData>(r => r.DefaultBranch == "custombranch"), Arg.Any<SettingsContainer>());
}
private static ICollaborationFactory GetCollaborationFactory(IEnvironmentVariablesProvider environmentVariablesProvider,
IEnumerable<ISettingsReader> settingReaders = null)
{
return new CollaborationFactory(
settingReaders ?? new ISettingsReader[] { new GitHubSettingsReader(new MockedGitDiscoveryDriver(), environmentVariablesProvider) },
Substitute.For<INuKeeperLogger>()
);
}
}
}
| 41.361925 | 179 | 0.617065 | [
"Apache-2.0"
] | MaxMommersteeg/NuKeeper | NuKeeper.Tests/Commands/RepositoryCommandTests.cs | 19,771 | C# |
namespace AzureSpeed.Web.Shared
{
using System;
using System.Collections.Generic;
/// <summary>
/// IListExtensions methods
/// </summary>
/// <remarks>https://github.com/mariusmuntean/ChartJs.Blazor/blob/master/ChartJs.Blazor.Samples/Shared/IListExtensions.cs</remarks>
public static class IListExtensions
{
// Basically a Polyfill since we now expose IList instead of List
// which is better but IList doesn't have AddRange
public static void AddRange<T>(this IList<T> list, IEnumerable<T> items)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
if (items == null)
throw new ArgumentNullException(nameof(items));
if (list is List<T> asList)
{
asList.AddRange(items);
}
else
{
foreach (T item in items)
{
list.Add(item);
}
}
}
}
} | 29.742857 | 135 | 0.539866 | [
"MIT"
] | kasuken/AzureSpeed | src/AzureSpeed/AzureSpeed.Web/Shared/IListExtensions.cs | 1,043 | C# |
namespace TonSdk.Modules.Net.Enums
{
public enum AggregationFn
{
/// <summary>
/// Returns count of filtered record.
/// </summary>
COUNT,
/// <summary>
/// Returns the minimal value for a field in filtered records.
/// </summary>
MIN,
/// <summary>
/// Returns the maximal value for a field in filtered records.
/// </summary>
MAX,
/// <summary>
/// Returns a sum of values for a field in filtered records.
/// </summary>
SUM,
/// <summary>
/// Returns an average value for a field in filtered records.
/// </summary>
AVERAGE,
}
}
| 23.516129 | 74 | 0.493827 | [
"Apache-2.0"
] | vcvetkovs/TonSdk | src/TonSdk/Modules/Net/Enums/AggregationFn.cs | 731 | C# |
//------------------------------------------------------------------------------
// <copyright file="UITypeEditorEditStyle.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Drawing.Design {
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
/// <include file='doc\UITypeEditorEditStyle.uex' path='docs/doc[@for="UITypeEditorEditStyle"]/*' />
/// <devdoc>
/// <para>Specifies identifiers to indicate the style of
/// a <see cref='System.Drawing.Design.UITypeEditor'/>.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")]
public enum UITypeEditorEditStyle {
/// <include file='doc\UITypeEditorEditStyle.uex' path='docs/doc[@for="UITypeEditorEditStyle.None"]/*' />
/// <devdoc>
/// <para>
/// Indicates no editor style.
/// </para>
/// </devdoc>
None = 1,
/// <include file='doc\UITypeEditorEditStyle.uex' path='docs/doc[@for="UITypeEditorEditStyle.Modal"]/*' />
/// <devdoc>
/// <para>
/// Indicates a modal editor style.
/// </para>
/// </devdoc>
Modal = 2,
/// <include file='doc\UITypeEditorEditStyle.uex' path='docs/doc[@for="UITypeEditorEditStyle.DropDown"]/*' />
/// <devdoc>
/// <para> Indicates a drop-down editor style.</para>
/// </devdoc>
DropDown = 3
}
}
| 39.348837 | 117 | 0.501182 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/fx/src/commonui/System/Drawing/Design/UITypeEditorEditStyle.cs | 1,692 | C# |
namespace ProjetSynthese
{
public class AmmoPack : Item
{
private const int WeightPer30Bullets = 5;
public AmmoType AmmoType { get; set; }
public int NumberOfAmmo { get; set; }
public override int GetWeight()
{
return WeightPer30Bullets * (NumberOfAmmo % 30);
}
}
}
| 20.117647 | 60 | 0.581871 | [
"MIT"
] | Allcatraz/Nullptr_ProjetSynthese | Assets/Scripts/Playmode/State/Item/AmmoPack.cs | 344 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("_16.ArraySymmetry")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("_16.ArraySymmetry")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6c23d93b-b612-4fae-b4b6-cf7f3db53f1d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.891892 | 84 | 0.748217 | [
"MIT"
] | radoslavvv/Programming-Fundamentals-Extended-May-2017 | Exercises/05.ArrayAndMethodsExercises/16.ArraySymmetry/Properties/AssemblyInfo.cs | 1,405 | C# |
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Win32;
using Task = System.Threading.Tasks.Task;
namespace QueryPopSSMS
{
/// <summary>
/// This is the class that implements the package exposed by this assembly.
/// </summary>
/// <remarks>
/// <para>
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell. These attributes tell the pkgdef creation
/// utility what data to put into .pkgdef file.
/// </para>
/// <para>
/// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file.
/// </para>
/// </remarks>
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] // Info on this package for Help/About
[ProvideMenuResource("Menus.ctmenu", 1)]
[Guid(TestCommandPackage.PackageGuidString)]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "pkgdef, VS and vsixmanifest are valid VS terms")]
public sealed class TestCommandPackage : AsyncPackage
{
/// <summary>
/// TestCommandPackage GUID string.
/// </summary>
public const string PackageGuidString = "e8e000ec-c214-4540-8c0c-c7f86dbfa6d9";
/// <summary>
/// Initializes a new instance of the <see cref="TestCommandPackage"/> class.
/// </summary>
public TestCommandPackage()
{
// Inside this method you can place any initialization code that does not require
// any Visual Studio service because at this point the package object is created but
// not sited yet inside Visual Studio environment. The place to do all the other
// initialization is the Initialize method.
}
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
/// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param>
/// <param name="progress">A provider for progress updates.</param>
/// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns>
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
// When initialized asynchronously, the current thread may be a background thread at this point.
// Do any initialization that requires the UI thread after switching to the UI thread.
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
await TestCommand.InitializeAsync(this);
}
#endregion
}
}
| 48.25641 | 176 | 0.743358 | [
"MIT"
] | luisfrr/querypop | src/QueryPopSSMS/TestCommandPackage.cs | 3,766 | C# |
using System.Globalization;
using System.Reactive.Linq;
using BeUtl.Configuration;
using BeUtl.Language;
using Reactive.Bindings;
namespace BeUtl.ViewModels.SettingsPages;
public sealed class ViewSettingsPageViewModel
{
private readonly ViewConfig _config;
public ViewSettingsPageViewModel()
{
_config = GlobalConfiguration.Instance.ViewConfig;
SelectedTheme.Value = (int)_config.Theme;
SelectedTheme.Subscribe(v => _config.Theme = (ViewConfig.ViewTheme)v);
SelectedLanguage.Value = _config.UICulture;
SelectedLanguage.Subscribe(ci => _config.UICulture = ci);
}
public ReactivePropertySlim<int> SelectedTheme { get; } = new();
public ReactivePropertySlim<CultureInfo> SelectedLanguage { get; } = new();
public IEnumerable<CultureInfo> Cultures { get; } = LocalizeService.Instance.SupportedCultures();
}
| 28.419355 | 101 | 0.738933 | [
"MIT"
] | YiB-PC/BeUtl | src/BeUtl/ViewModels/SettingsPages/ViewSettingsPageViewModel.cs | 883 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace Dnn.ExportImport.Components.Common
{
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using DotNetNuke.Common.Utilities.Internal;
/// <summary>
/// Provides compression utilites.
/// </summary>
public static class CompressionUtil
{
/// <summary>
/// Compress a full folder.
/// </summary>
/// <param name="folderPath">Full path of folder to compress.</param>
/// <param name="archivePath">Full path of the archived file.</param>
public static void ZipFolder(string folderPath, string archivePath)
{
if (File.Exists(archivePath))
{
File.Delete(archivePath);
}
ZipFile.CreateFromDirectory(folderPath, archivePath, CompressionLevel.Fastest, false);
}
/// <summary>
/// Unzip compressed file to a folder.
/// </summary>
/// <param name="archivePath">Full path to archive with name.</param>
/// <param name="extractFolder">Full path to the target folder.</param>
/// <param name="overwrite">Overwrites the files on target if true.</param>
public static void UnZipArchive(string archivePath, string extractFolder, bool overwrite = true)
{
UnZipArchiveExcept(archivePath, extractFolder, overwrite);
}
/// <summary>
/// Unzip compressed file to a folder.
/// </summary>
/// <param name="archivePath">Full path to archive with name.</param>
/// <param name="extractFolder">Full path to the target folder.</param>
/// <param name="overwrite">Overwrites the files on target if true.</param>
/// <param name="exceptionList">List of files to exlude from extraction.</param>
/// <param name="deleteFromSoure">Delete the files from the archive after extraction.</param>
public static void UnZipArchiveExcept(
string archivePath,
string extractFolder,
bool overwrite = true,
IEnumerable<string> exceptionList = null,
bool deleteFromSoure = false)
{
if (!File.Exists(archivePath))
{
return;
}
using (var archive = OpenCreate(archivePath))
{
foreach (
var entry in
archive.Entries.Where(
entry =>
((exceptionList != null && !exceptionList.Contains(entry.FullName)) ||
exceptionList == null) &&
!entry.FullName.EndsWith("\\") && !entry.FullName.EndsWith("/") && entry.Length > 0))
{
var path = Path.GetDirectoryName(Path.Combine(extractFolder, entry.FullName));
if (!string.IsNullOrEmpty(path) && !Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!File.Exists(Path.Combine(extractFolder, entry.FullName)) || overwrite)
{
entry.ExtractToFile(Path.Combine(extractFolder, entry.FullName), overwrite);
}
if (deleteFromSoure)
{
entry.Delete();
}
}
}
}
/// <summary>
/// Unzip a single file from an archive.
/// </summary>
/// <param name="fileName">Name of the file to extract. This name should match the entry name in the archive. i.e. it should include complete folder structure inside the archive.</param>
/// <param name="archivePath">Full path to archive with name.</param>
/// <param name="extractFolder">Full path to the target folder.</param>
/// <param name="overwrite">Overwrites the file on target if true.</param>
/// <param name="deleteFromSoure">Delete the file from the archive after extraction.</param>
public static void UnZipFileFromArchive(
string fileName,
string archivePath,
string extractFolder,
bool overwrite = true,
bool deleteFromSoure = false)
{
if (!File.Exists(archivePath))
{
return;
}
using (var archive = OpenCreate(archivePath))
{
var fileUnzipFullName = Path.Combine(extractFolder, fileName);
if (File.Exists(fileUnzipFullName) && !overwrite)
{
return;
}
var fileEntry = archive.GetEntry(fileName);
if (!File.Exists(Path.Combine(extractFolder, fileEntry.FullName)) || overwrite)
{
fileEntry?.ExtractToFile(Path.Combine(extractFolder, fileName), overwrite);
}
if (deleteFromSoure)
{
fileEntry?.Delete();
}
}
}
/// <summary>
/// Add files to an archive. If no archive exists, new one is created.
/// </summary>
/// <param name="archive">Source archive to write the files to.</param>
/// <param name="files">List containing path of files to add to archive.</param>
/// <param name="folderOffset">Starting index(Index in file url) of the root folder in archive based on what the folder structure starts in archive.
/// e.g. if file url is c:\\dnn\files\archived\foldername\1\file.jpg and we want to add all files in foldername folder
/// then the folder offset would be starting index of foldername.</param>
/// <param name="folder">Additional root folder to be added into archive.</param>
public static void AddFilesToArchive(
ZipArchive archive,
IEnumerable<string> files,
int folderOffset,
string folder = null)
{
var enumerable = files as IList<string> ?? files.ToList();
if (!enumerable.Any())
{
return;
}
foreach (var file in enumerable.Where(File.Exists))
{
AddFileToArchive(archive, file, folderOffset, folder);
}
}
/// <summary>
/// Add single file to an archive. If no archive exists, new one is created.
/// </summary>
/// <param name="file">Full path of file to add.</param>
/// <param name="archivePath">Full path of archive file.</param>
/// <param name="folderOffset">Starting index(Index in file url) of the root folder in archive based on what the folder structure starts in archive.
/// e.g. if file url is c:\\dnn\files\archived\foldername\1\file.jpg and we want to add all files in foldername folder
/// then the folder offset would be starting index of foldername.</param>
/// <param name="folder">Additional root folder to be added into archive.</param>
/// <returns>A value indicating whether the operation succeeded.</returns>
public static bool AddFileToArchive(string file, string archivePath, int folderOffset, string folder = null)
{
using (var archive = OpenCreate(archivePath))
{
if (File.Exists(file))
{
return AddFileToArchive(archive, file, folderOffset, folder);
}
}
return false;
}
/// <summary>
/// Adds a file to an archive.
/// </summary>
/// <param name="archive">The archive to add to.</param>
/// <param name="file">The file to add.</param>
/// <param name="folderOffset">Strips this number of characters from the front of the filename.</param>
/// <param name="folder">The folder this file should go into in the archive.</param>
/// <returns>A value indicating whether the operation succeeded.</returns>
public static bool AddFileToArchive(ZipArchive archive, string file, int folderOffset, string folder = null)
{
var entryName = file.Substring(folderOffset); // Makes the name in zip based on the folder
ZipArchiveEntry existingEntry;
// Deletes if the entry already exists in archive.
if ((existingEntry = archive.GetEntry(entryName)) != null)
{
existingEntry.Delete();
}
var fileInfo = new FileInfo(file);
if (fileInfo.Length < 1610612736)
{
archive.CreateEntryFromFile(
file,
string.IsNullOrEmpty(folder) ? entryName : Path.Combine(folder, entryName),
CompressionLevel.Fastest);
return true;
}
return false;
}
/// <summary>
/// Open the archive file for read and write.
/// </summary>
/// <param name="archiveFileName">The name of the archive.</param>
/// <returns>The resulting <see cref="ZipArchive"/>.</returns>
public static ZipArchive OpenCreate(string archiveFileName)
{
if (string.IsNullOrWhiteSpace(archiveFileName))
{
throw new ArgumentNullException(nameof(archiveFileName));
}
ZipArchive zip = null;
RetryableAction.RetryEverySecondFor30Seconds(
() => zip = OpenCreateUnsafe(archiveFileName),
$"{nameof(OpenCreateUnsafe)}(\"{archiveFileName}\")");
return zip;
}
/// <summary>
/// Open the archive file for read and write (no retry).
/// </summary>
/// <param name="archiveFileName">The full zip file path.</param>
/// <returns>A <see cref="ZipArchive"/> instance.</returns>
internal static ZipArchive OpenCreateUnsafe(string archiveFileName)
{
return File.Exists(archiveFileName)
? ZipFile.Open(archiveFileName, ZipArchiveMode.Update, Encoding.UTF8)
: new ZipArchive(new FileStream(archiveFileName, FileMode.Create), ZipArchiveMode.Update);
}
}
}
| 41.936759 | 194 | 0.563808 | [
"MIT"
] | Mariusz11711/DNN | DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs | 10,612 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text;
namespace Project2
{
public partial class Login : System.Web.UI.Page
{
string email;
string password;
bool ValidInfo = false;
bool Access = false;
string username;
string sql;
bool registered = false;
int userID;
string constr = @"Server = tcp:323projectserver.database.windows.net,1433;Initial Catalog = Users; Persist Security Info=False;User ID = projectadmin; Password=Slimkop21%; MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout = 30;";
public SqlConnection con;
public DataSet ds;
public SqlDataAdapter sda;
protected void Page_Load(object sender, EventArgs e)
{
}
public class utils
{
public string EncryptedString(string encrString)
{
byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(encrString);
string encrypted = Convert.ToBase64String(b);
return encrypted;
}
public string DecryptString(string encrString)
{
byte[] b;
string decrypted;
try
{
b = Convert.FromBase64String(encrString);
decrypted = System.Text.ASCIIEncoding.ASCII.GetString(b);
}
catch
{
decrypted = "";
}
return decrypted;
}
}
public string EncryptedString(string encrString)
{
byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(encrString);
string encrypted = Convert.ToBase64String(b);
return encrypted;
}
public string DecryptString(string encrString)
{
byte[] b;
string decrypted;
try
{
b = Convert.FromBase64String(encrString);
decrypted = System.Text.ASCIIEncoding.ASCII.GetString(b);
}
catch
{
decrypted = "";
}
return decrypted;
}
protected void Unnamed4_Click(object sender, EventArgs e)
{
//Determine if the account already exists
try
{
SqlCommand cmd;
con = new SqlConnection(constr);
sda = new SqlDataAdapter();
ds = new DataSet();
con.Open();
sql = @"SELECT * FROM Users WHERE Username='" + txtusername.Text + "' and Password='" + EncryptedString(txtpassword.Text)+ "'";
cmd = new SqlCommand(sql, con);
sda.SelectCommand = cmd;
sda.Fill(ds, "Users");
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
Response.Redirect("Register.aspx");
}
//Insert new user
else
{
con = new SqlConnection(constr);
con.Open();
SqlCommand comm;
string insert_query = @"INSERT INTO Users VALUES(@Username, @Password, @emailAddress)";
comm = new SqlCommand(insert_query, con);
comm.Parameters.AddWithValue("@Username", txtusername.Text);
comm.Parameters.AddWithValue("@Password", EncryptedString(txtpassword.Text));
comm.Parameters.AddWithValue("@emailAddress", txtemail.Text);
comm.ExecuteNonQuery();
con.Close();
ValidInfo = true;
registered = true;
}
}
catch (Exception ex)
{
Response.Write("<script>alert('Error...')</script>" + ex.Message);
}
if (registered == true)
{
//Insert data into cookies so that the information can be pull to the next form
try
{
SqlCommand com;
con = new SqlConnection(constr);
sda = new SqlDataAdapter();
ds = new DataSet();
con.Open();
sql = "SELECT UserID FROM Users WHERE Username='" + txtusername.Text + "' and Password='" + EncryptedString(txtpassword.Text) + "'";
com = new SqlCommand(sql, con);
sda.SelectCommand = com;
userID = (int)com.ExecuteScalar();
email = txtemail.Text;
password = txtpassword.Text;
username = txtusername.Text;
HttpCookie cookie = new HttpCookie("UserInfo");
cookie["email"] = txtemail.Text;
cookie["username"] = txtusername.Text;
cookie["UserID"] = userID.ToString();
cookie.Expires = DateTime.Now.AddSeconds(20);
Response.Cookies.Add(cookie);
con.Close();
}
catch (Exception ex)
{
Response.Write("<script>alert('Error...')</script>" + ex.Message);
}
Response.Redirect("ImageShare.aspx");
}
}
protected void btnAccess_Click(object sender, EventArgs e)
{
Response.Redirect("ImageAccess.aspx");
}
}
} | 34.511628 | 279 | 0.485175 | [
"MIT"
] | MichaelRosin/Project-2 | Project2/Login.aspx.cs | 5,938 | C# |
using System.Collections.Generic;
namespace UCloudSDK.Models
{
/// <summary>
/// 根据提供信息,分配弹性IP
/// <para>
/// http://docs.ucloud.cn/api/unet/allocate_eip.html
/// </para>
/// </summary>
public partial class AllocateEIPSet
{
/// <summary>
/// 申请到的EIP资源ID
/// </summary>
public string EIPId { get; set; }
/// <summary>
/// 申请到的IPv4地址
/// <para>
/// 双线拥有两个IP地址)
/// </para>
/// </summary>
public List<AllocateEIPAddr> EIPAddr { get; set; }
}
}
| 22.357143 | 60 | 0.456869 | [
"MIT"
] | icyflash/ucloud-csharp-sdk | UCloudSDK/Models/UNet/AllocateEIP.EIPSet.cs | 690 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using VerifyCS = ImportAnalyzer.Test.CSharpCodeFixVerifier<
ImportAnalyzer.ImportAnalyzer,
ImportAnalyzer.ImportAnalyzerCodeFixProvider>;
namespace ImportAnalyzer.Test
{
[TestClass]
public class ImportAnalyzerUnitTest
{
//No diagnostics expected to show up
[TestMethod]
public async Task TestMethod1()
{
var test = @"";
await VerifyCS.VerifyAnalyzerAsync(test);
}
//Diagnostic and CodeFix both triggered and checked for
[TestMethod]
public async Task TestMethod2()
{
var test = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
class {|#0:TypeName|}
{
}
}";
var fixtest = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
class TYPENAME
{
}
}";
var expected = VerifyCS.Diagnostic("ImportAnalyzer").WithLocation(0).WithArguments("TypeName");
await VerifyCS.VerifyCodeFixAsync(test, expected, fixtest);
}
}
}
| 24.216667 | 107 | 0.629043 | [
"MIT"
] | knollsen/csharp_analyzers | ImportAnalyzer/ImportAnalyzer/ImportAnalyzer.Test/ImportAnalyzerUnitTests.cs | 1,455 | C# |
namespace SystemDot.Messaging.Specifications
{
public class TestReplyMessageHandler<TRequest>
{
public void Handle(TRequest message)
{
Bus.Reply(message);
}
}
public class TestReplyMessageHandler<TRequest, TResponse> where TResponse : new()
{
public void Handle(TRequest message)
{
Bus.Reply(new TResponse());
}
}
} | 22.888889 | 85 | 0.601942 | [
"Apache-2.0"
] | SystemDot/SystemDotServiceBus | SystemDotMessaging/Projects/SystemDot.Messaging.Specifications/TestReplyMessageHandler.cs | 412 | C# |
using System;
using System.Data.SqlClient;
using System.Threading.Tasks;
using Npgsql;
using Shouldly;
using Xunit;
namespace Weasel.Postgresql.Tests
{
public class advisory_lock_usage
{
[Fact]
public async Task explicitly_release_global_session_locks()
{
using (var conn1 = new NpgsqlConnection(ConnectionSource.ConnectionString))
using (var conn2 = new NpgsqlConnection(ConnectionSource.ConnectionString))
using (var conn3 = new NpgsqlConnection(ConnectionSource.ConnectionString))
{
await conn1.OpenAsync();
await conn2.OpenAsync();
await conn3.OpenAsync();
await conn1.GetGlobalLock(1);
// Cannot get the lock here
(await conn2.TryGetGlobalLock(1)).ShouldBeFalse();
await conn1.ReleaseGlobalLock(1);
for (var j = 0; j < 5; j++)
{
if (await conn2.TryGetGlobalLock(1)) return;
await Task.Delay(250);
}
throw new Exception("Advisory lock was not released");
}
}
[Fact]
public async Task explicitly_release_global_tx_session_locks()
{
using (var conn1 = new NpgsqlConnection(ConnectionSource.ConnectionString))
using (var conn2 = new NpgsqlConnection(ConnectionSource.ConnectionString))
using (var conn3 = new NpgsqlConnection(ConnectionSource.ConnectionString))
{
await conn1.OpenAsync();
await conn2.OpenAsync();
await conn3.OpenAsync();
var tx1 = conn1.BeginTransaction();
await tx1.GetGlobalTxLock(2);
// Cannot get the lock here
var tx2 = conn2.BeginTransaction();
(await tx2.TryGetGlobalTxLock(2)).ShouldBeFalse();
tx1.Rollback();
for (var j = 0; j < 5; j++)
{
if (await tx2.TryGetGlobalTxLock(2))
{
tx2.Rollback();
return;
}
await Task.Delay(250);
}
throw new Exception("Advisory lock was not released");
}
}
[Fact] // - too slow
public async Task global_session_locks()
{
using (var conn1 = new NpgsqlConnection(ConnectionSource.ConnectionString))
using (var conn2 = new NpgsqlConnection(ConnectionSource.ConnectionString))
using (var conn3 = new NpgsqlConnection(ConnectionSource.ConnectionString))
{
await conn1.OpenAsync();
await conn2.OpenAsync();
await conn3.OpenAsync();
await conn1.GetGlobalLock(24);
try
{
// Cannot get the lock here
(await conn2.TryGetGlobalLock(24)).ShouldBeFalse();
// Can get the new lock
(await conn3.TryGetGlobalLock(25)).ShouldBeTrue();
// Cannot get the lock here
(await conn2.TryGetGlobalLock(25)).ShouldBeFalse();
}
finally
{
await conn1.ReleaseGlobalLock(24);
await conn3.ReleaseGlobalLock(25);
}
}
}
[Fact] // -- too slow
public async Task tx_session_locks()
{
using (var conn1 = new NpgsqlConnection(ConnectionSource.ConnectionString))
using (var conn2 = new NpgsqlConnection(ConnectionSource.ConnectionString))
using (var conn3 = new NpgsqlConnection(ConnectionSource.ConnectionString))
{
await conn1.OpenAsync();
await conn2.OpenAsync();
await conn3.OpenAsync();
var tx1 = conn1.BeginTransaction();
await tx1.GetGlobalTxLock(4);
// Cannot get the lock here
var tx2 = conn2.BeginTransaction();
(await tx2.TryGetGlobalTxLock(4)).ShouldBeFalse();
// Can get the new lock
var tx3 = conn3.BeginTransaction();
(await tx3.TryGetGlobalTxLock(5)).ShouldBeTrue();
// Cannot get the lock here
(await tx2.TryGetGlobalTxLock( 5)).ShouldBeFalse();
tx1.Rollback();
tx2.Rollback();
tx3.Rollback();
}
}
}
}
| 31.22 | 87 | 0.51783 | [
"MIT"
] | Hawxy/weasel | src/Weasel.Postgresql.Tests/advisory_lock_usage.cs | 4,685 | C# |
using UnityEngine;
using System.Collections;
using System;
using UnityEngine.Rendering;
using UnityEngine.InputSystem;
using System.Diagnostics.Tracing;
namespace TimelineIso
{
public class PlayerPulseComponent : PlayerAbilityComponent
{
public MeshRenderer PulsePrefab;
public float FireDuration = .2f;
public float PulseDuration = .1f;
public float Force = 5f;
public float Falloff = 1f;
private bool busy;
public override void Initialize()
{
}
private void Fire()
{
// TODO spawn location
var pulse = Instantiate(this.PulsePrefab, this.transform);
pulse.transform.parent = null;
StartCoroutine(PulseRoutine(pulse.gameObject));
}
private IEnumerator PulseRoutine(GameObject pulse)
{
if (! Time.inFixedTimeStep)
{
Debug.Log("Wut");
}
pulse.GetComponent<Renderer>().material.SetFloat("_StartTime", Time.fixedTime);
pulse.GetComponent<Renderer>().material.SetFloat("_Duration", PulseDuration * 1f);
pulse.GetComponent<EventColliderComponent>().OnCollide.AddListener((Collider col) => this.OnCollision(pulse, col));
pulse.GetComponent<EventColliderComponent>().Duration = PulseDuration;
yield return new WaitForFixedSeconds(PulseDuration);
if (! Time.inFixedTimeStep)
{
Debug.Log("More understandable, but wut");
}
Destroy(pulse);
}
private void OnCollision(GameObject pulse, Collider collider)
{
if (collider.GetComponent<Enemy>() == null)
{
return;
}
//var direction = (collider.transform.position - pulse.transform.position).XZPlane();
var direction = this.transform.forward.XZPlane();
direction = direction.normalized;
collider.GetComponent<Impulse>().Displace(direction * Force, .2f);
return;
}
public override PlayerAbilityStatus Status()
{
return (busy) ? PlayerAbilityStatus.Running : PlayerAbilityStatus.Finished;
}
public override InputHandledStatus HandleInput(IInputEvent input)
{
if (input is CommandInput c && c.button.is_press && c.targetAbility == this && !busy)
{
StartCoroutine(RunFire());
return InputHandledStatus.Handled;
}
return InputHandledStatus.Deny;
}
public IEnumerator RunFire()
{
this.GetComponent<PlayerMovement>().SpeedMultiplier = 0;
this.busy = true;
yield return new WaitForFixedSeconds(FireDuration);
this.Fire();
yield return new WaitForFixedSeconds(FireDuration);
this.busy = false;
this.GetComponent<PlayerMovement>().SpeedMultiplier = 1f;
yield return null;
}
void Start()
{
}
public override void Finish()
{
}
}
}
| 31.356436 | 127 | 0.582886 | [
"MIT"
] | billymillions/Iso | Assets/Scripts/Character/PlayerAbilities/PlayerPulseComponent.cs | 3,169 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the timestream-write-2018-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Runtime;
namespace Amazon.TimestreamWrite.Model
{
/// <summary>
/// Base class for ListDatabases paginators.
/// </summary>
internal sealed partial class ListDatabasesPaginator : IPaginator<ListDatabasesResponse>, IListDatabasesPaginator
{
private readonly IAmazonTimestreamWrite _client;
private readonly ListDatabasesRequest _request;
private int _isPaginatorInUse = 0;
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
public IPaginatedEnumerable<ListDatabasesResponse> Responses => new PaginatedResponse<ListDatabasesResponse>(this);
internal ListDatabasesPaginator(IAmazonTimestreamWrite client, ListDatabasesRequest request)
{
this._client = client;
this._request = request;
}
#if BCL
IEnumerable<ListDatabasesResponse> IPaginator<ListDatabasesResponse>.Paginate()
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
PaginatorUtils.SetUserAgentAdditionOnRequest(_request);
var nextToken = _request.NextToken;
ListDatabasesResponse response;
do
{
_request.NextToken = nextToken;
response = _client.ListDatabases(_request);
nextToken = response.NextToken;
yield return response;
}
while (!string.IsNullOrEmpty(nextToken));
}
#endif
#if AWS_ASYNC_ENUMERABLES_API
async IAsyncEnumerable<ListDatabasesResponse> IPaginator<ListDatabasesResponse>.PaginateAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
PaginatorUtils.SetUserAgentAdditionOnRequest(_request);
var nextToken = _request.NextToken;
ListDatabasesResponse response;
do
{
_request.NextToken = nextToken;
response = await _client.ListDatabasesAsync(_request, cancellationToken).ConfigureAwait(false);
nextToken = response.NextToken;
cancellationToken.ThrowIfCancellationRequested();
yield return response;
}
while (!string.IsNullOrEmpty(nextToken));
}
#endif
}
} | 39.307692 | 150 | 0.665362 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/TimestreamWrite/Generated/Model/_bcl45+netstandard/ListDatabasesPaginator.cs | 3,577 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace ClientSlack.Controllers
{
[Route("api/[controller]")]
public class SampleDataController : Controller
{
private static string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet("[action]")]
public IEnumerable<WeatherForecast> WeatherForecasts()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
});
}
public class WeatherForecast
{
public string DateFormatted { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public int TemperatureF
{
get
{
return 32 + (int)(TemperatureC / 0.5556);
}
}
}
}
}
| 28.555556 | 110 | 0.531518 | [
"MIT"
] | xavperrin/Slack | Slack/ClientSlack/Controllers/SampleDataController.cs | 1,285 | C# |
public static class Settings
{
public static string Secret = "d41d8cd98f00b204e9800998ecf8427e";
}
| 20.8 | 69 | 0.778846 | [
"MIT"
] | vtspereira/Estagio_brg | estagio_brg/Settings.cs | 106 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Domain.Enumeration
{
public enum MessageRecordSendResult
{
Undefined = 0,
Finished = 1,
Unfinished = 2
}
}
| 15.857143 | 39 | 0.648649 | [
"MIT"
] | asheng71/WebProjectTemplate | Domain/Enumeration/MessageRecordSendResult.cs | 224 | C# |
using System;
using System.Net;
using Amazon.KeyManagementService.Model;
using LeapingGorilla.SecretStore.Aws.Exceptions;
using LeapingGorilla.Testing.Attributes;
using NSubstitute;
using NUnit.Framework;
namespace LeapingGorilla.SecretStore.Tests.AwsKmsKeyManagerTests.UnexpectedResponsesTests.EncryptTests
{
public class WhenEncryptAlwaysReturns500 : WhenTestingAwsKmsKeyManagerForUnexpectedResponses
{
private EncryptResponse _result;
private byte[] _data;
private Exception _ex;
[Given]
public void WeHaveData()
{
_data = new byte[15];
}
[Given]
public void ServiceReturnsFailCode()
{
_result = new EncryptResponse
{
CiphertextBlob = null,
HttpStatusCode = HttpStatusCode.InternalServerError
};
KmsService.EncryptAsync(Arg.Any<EncryptRequest>())
.Returns(_result);
}
[When]
public void EncryptIsCalled()
{
try
{
Manager.EncryptData(KeyId, _data);
}
catch (Exception e)
{
_ex = e;
}
}
[Then]
public void ExceptionShouldBeThrown()
{
Assert.That(_ex, Is.Not.Null);
}
[Then]
public void ExceptionShouldBeExpectedType()
{
Assert.That(_ex, Is.TypeOf<KeyManagementServiceUnavailableException>());
}
[Then]
public void ExceptionShouldHaveExpectedCode()
{
Assert.That(((KeyManagementServiceUnavailableException)_ex).LastStatusCode, Is.EqualTo(HttpStatusCode.InternalServerError));
}
[Then]
public void ShouldRetryExpectedNumberOfTimes()
{
KmsService.Received(3).EncryptAsync(Arg.Any<EncryptRequest>());
}
}
}
| 20.864865 | 127 | 0.736399 | [
"Apache-2.0"
] | LeapingGorillaLTD/secretstore | src/LeapingGorilla.SecretStore.Tests/AwsKmsKeyManagerTests/UnexpectedResponsesTests/EncryptTests/WhenEncryptAlwaysReturns500.cs | 1,546 | C# |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace LarchConsole {
public class Filter {
private readonly Regex _pattern;
private readonly string _text;
public bool OnEmptyMatchAll { get; set; }
public string Pattern { get; }
public Filter(string pattern, CampareType type = CampareType.WildCard, CompareMode mode = CompareMode.CaseIgnore) {
Pattern = pattern;
if (pattern == null) {
return;
}
var regexOptions = RegexOptions.None;
if (mode == CompareMode.CaseIgnore) {
regexOptions = RegexOptions.IgnoreCase;
}
switch (type) {
default:
case CampareType.WildCard:
if (pattern.Contains("*") || pattern.Contains("?")) {
_pattern = new Regex($"^{Regex.Escape(pattern).Replace(@"\?", ".").Replace(@"\*", ".*")}$", regexOptions);
} else {
_text = pattern;
}
break;
case CampareType.Regex:
_pattern = new Regex(pattern, regexOptions);
break;
}
}
public bool IsMatch(string value) {
if (value == null) value = string.Empty;
if (_text != null) {
return value == _text;
}
if (_pattern != null) {
return _pattern.IsMatch(value);
}
// if we have no filter pattern we do not filter
return OnEmptyMatchAll;
}
public Match<string> GetMatch(string model) {
return GetMatch(model, x => x);
}
public Match<T> GetMatch<T>(T model) {
return GetMatch(model, x => x.ToString());
}
public Match<T> GetMatch<T>(T model, Func<T, string> property) {
var value = property(model) ?? string.Empty;
if (_text != null) {
return new Match<T>() {
IsSuccess = _text == value,
Matches = GetMatchs(value),
Model = model,
Value = value
};
}
if (_pattern != null) {
return new Match<T>() {
IsSuccess = _pattern.IsMatch(value),
Matches = GetMatchs(value),
Model = model,
Value = value
};
}
// if we have no filter pattern we do not filter
return new Match<T>() {
IsSuccess = OnEmptyMatchAll,
Matches = GetMatchs(value),
Model = model,
Value = value
};
}
private IEnumerable<Group> GetMatchs(string value) {
if (_text != null) {
yield return new Group() {
Start = 0,
Stop = value.Length,
IsMatch = _text == value,
Num = 0
};
yield break;
}
if (_pattern != null) {
var matchs = _pattern.Matches(value);
for (var i = 0; i < matchs.Count; i++) {
for (var j = 0; j < matchs[i].Groups.Count; j++) {
yield return new Group() {
Start = matchs[i].Groups[j].Index,
Stop = matchs[i].Groups[j].Index + matchs[i].Groups[j].Length,
IsMatch = matchs[i].Groups[j].Success,
Num = j
};
}
}
yield break;
}
yield return new Group() {
Start = 0,
Stop = value.Length,
IsMatch = OnEmptyMatchAll,
Num = 0
};
}
}
public class Match<T> : IMatch {
public IEnumerable<Group> Matches { get; set; }
public T Model { get; set; }
public bool IsSuccess { get; set; }
public string Value { get; set; }
}
public interface IMatch {
IEnumerable<Group> Matches { get; set; }
bool IsSuccess { get; set; }
string Value { get; set; }
}
public class Group {
public int Start { get; set; }
public int Stop { get; set; }
public bool IsMatch { get; set; }
public int Num { get; set; }
}
public enum CompareMode {
CaseIgnore = 0,
ExactMatch = 2,
}
public enum CampareType {
WildCard = 0,
Regex = 1
}
} | 28.837349 | 130 | 0.442448 | [
"MIT"
] | r-Larch/LarchConsole | src/src/Filter.cs | 4,789 | C# |
using System;
using System.Threading.Tasks;
using Buttplug.Core;
using Buttplug.Core.Messages;
namespace Buttplug.Server.Test
{
internal class TestDevice : ButtplugDevice
{
public TestDevice(ButtplugLogManager aLogManager, string aName)
: base(aLogManager, aName, "Test")
{
MsgFuncs.Add(typeof(SingleMotorVibrateCmd), HandleSingleMotorVibrateCmd);
}
private Task<ButtplugMessage> HandleSingleMotorVibrateCmd(ButtplugDeviceMessage aMsg)
{
// BpLogger.Trace("Test Device got SingleMotorVibrateMessage");
return Task.FromResult<ButtplugMessage>(new Ok(aMsg.Id));
}
public void RemoveDevice()
{
InvokeDeviceRemoved();
}
public override void Disconnect()
{
RemoveDevice();
}
}
}
| 27 | 94 | 0.609428 | [
"Apache-2.0"
] | Orgasmscience/buttplug-csharp | Buttplug.Server.Test/TestDevice.cs | 893 | C# |
using AutoMapper;
using BlogTemplate.Core.Abstractions.Models;
using BlogTemplate.Infrastructure.Kentico.Xperience.Abstractions.PageTypes;
using BlogTemplate.Mvc.Kentico.Xperience.Models;
using CMS.DocumentEngine;
namespace BlogTemplate.Mvc.Kentico.Xperience.Mappings
{
public class AboutMappingProfile : Profile
{
public AboutMappingProfile( )
{
CreateMap<AboutNode, AboutViewModel>()
.ForMember( viewModel => viewModel.Meta, opt => opt.MapFrom( node => node ) )
.ForMember( viewModel => viewModel.OpenGraph, opt => opt.MapFrom( node => node ) );
CreateMap<AboutNode, MetaData>()
.IncludeBase<TreeNode, MetaData>();
CreateMap<AboutNode, OpenGraphData>()
.IncludeBase<TreeNode, OpenGraphData>();
}
}
}
| 29.137931 | 99 | 0.654438 | [
"MIT"
] | BizStream/xperience-blog-template | src/src/Mvc/Kentico/Xperience/Xperience/Mappings/AboutMappingProfile.cs | 845 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801
{
using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell;
/// <summary>
/// Collection of metadata for the app configuration snapshots that can be restored.
/// </summary>
[System.ComponentModel.TypeConverter(typeof(SiteConfigurationSnapshotInfoCollectionTypeConverter))]
public partial class SiteConfigurationSnapshotInfoCollection
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteConfigurationSnapshotInfoCollection"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollection"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollection DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new SiteConfigurationSnapshotInfoCollection(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteConfigurationSnapshotInfoCollection"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollection"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollection DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new SiteConfigurationSnapshotInfoCollection(content);
}
/// <summary>
/// Creates a new instance of <see cref="SiteConfigurationSnapshotInfoCollection" />, deserializing the content from a json
/// string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollection FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteConfigurationSnapshotInfoCollection"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal SiteConfigurationSnapshotInfoCollection(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollectionInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfo[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollectionInternal)this).Value, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfo>(__y, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteConfigurationSnapshotInfoTypeConverter.ConvertFrom));
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollectionInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollectionInternal)this).NextLink, global::System.Convert.ToString);
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteConfigurationSnapshotInfoCollection"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal SiteConfigurationSnapshotInfoCollection(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollectionInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfo[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollectionInternal)this).Value, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfo>(__y, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteConfigurationSnapshotInfoTypeConverter.ConvertFrom));
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollectionInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfigurationSnapshotInfoCollectionInternal)this).NextLink, global::System.Convert.ToString);
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Collection of metadata for the app configuration snapshots that can be restored.
[System.ComponentModel.TypeConverter(typeof(SiteConfigurationSnapshotInfoCollectionTypeConverter))]
public partial interface ISiteConfigurationSnapshotInfoCollection
{
}
} | 72.528986 | 672 | 0.721051 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Functions/generated/api/Models/Api20190801/SiteConfigurationSnapshotInfoCollection.PowerShell.cs | 9,872 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using GW2EIBuilders;
using GW2EIBuilders.JsonModels;
using GW2EIEvtcParser;
using GW2EIGW2API;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace GW2EIParser.tst
{
public class TestHelper
{
internal static readonly UTF8Encoding NoBOMEncodingUTF8 = new UTF8Encoding(false);
internal static readonly DefaultContractResolver DefaultJsonContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
private static readonly Version Version = new Version(1, 0);
private static readonly EvtcParserSettings parserSettings = new EvtcParserSettings(false, true, true, true, true, 2200);
private static readonly HTMLSettings htmlSettings = new HTMLSettings(false, false);
private static readonly RawFormatSettings rawSettings = new RawFormatSettings(true);
private static readonly CSVSettings csvSettings = new CSVSettings(",");
private static readonly HTMLAssets htmlAssets = new HTMLAssets();
internal static readonly string SkillAPICacheLocation = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/Content/SkillList.json";
internal static readonly string SpecAPICacheLocation = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/Content/SpecList.json";
internal static readonly string TraitAPICacheLocation = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/Content/TraitList.json";
internal static readonly GW2APIController APIController = new GW2APIController(SkillAPICacheLocation, SpecAPICacheLocation, TraitAPICacheLocation);
private class TestOperationController : ParserController
{
public TestOperationController()
{
}
public override void UpdateProgressWithCancellationCheck(string status)
{
}
}
public static ParsedEvtcLog ParseLog(string location, GW2EIGW2API.GW2APIController apiController)
{
var parser = new EvtcParser(parserSettings, apiController);
var fInfo = new FileInfo(location);
ParsedEvtcLog parsedLog = parser.ParseLog(new TestOperationController(), fInfo, out GW2EIEvtcParser.ParserHelpers.ParsingFailureReason failureReason);
if (failureReason != null)
{
failureReason.Throw();
}
return parsedLog;
}
public static string JsonString(ParsedEvtcLog log)
{
var ms = new MemoryStream();
var sw = new StreamWriter(ms, NoBOMEncodingUTF8);
var builder = new RawFormatBuilder(log, rawSettings, Version);
builder.CreateJSON(sw, false);
sw.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
public static string CsvString(ParsedEvtcLog log)
{
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
var builder = new CSVBuilder(log, csvSettings, Version);
builder.CreateCSV(sw);
sw.Close();
return sw.ToString();
}
public static string HtmlString(ParsedEvtcLog log)
{
var ms = new MemoryStream();
var sw = new StreamWriter(ms, NoBOMEncodingUTF8);
var builder = new HTMLBuilder(log, htmlSettings, htmlAssets, Version);
builder.CreateHTML(sw, null);
sw.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
public static JsonLog JsonLog(ParsedEvtcLog log)
{
var builder = new RawFormatBuilder(log, rawSettings, null);
return builder.JsonLog;
}
///////////////////////////////////////
///
//https://stackoverflow.com/questions/24876082/find-and-return-json-differences-using-newtonsoft-in-c
/// <summary>
/// Deep compare two NewtonSoft JObjects. If they don't match, returns text diffs
/// </summary>
/// <param name="source">The expected results</param>
/// <param name="target">The actual results</param>
/// <returns>Text string</returns>
public static StringBuilder CompareObjects(JObject source, JObject target)
{
var returnString = new StringBuilder();
foreach (KeyValuePair<string, JToken> sourcePair in source)
{
if (sourcePair.Value.Type == JTokenType.Object)
{
if (target.GetValue(sourcePair.Key) == null)
{
returnString.Append("Key " + sourcePair.Key
+ " not found" + Environment.NewLine);
}
else if (target.GetValue(sourcePair.Key).Type != JTokenType.Object)
{
returnString.Append("Key " + sourcePair.Key
+ " is not an object in target" + Environment.NewLine);
}
else
{
returnString.Append(CompareObjects(sourcePair.Value.ToObject<JObject>(),
target.GetValue(sourcePair.Key).ToObject<JObject>()));
}
}
else if (sourcePair.Value.Type == JTokenType.Array)
{
if (target.GetValue(sourcePair.Key) == null)
{
returnString.Append("Key " + sourcePair.Key
+ " not found" + Environment.NewLine);
}
else
{
returnString.Append(CompareArrays(sourcePair.Value.ToObject<JArray>(),
target.GetValue(sourcePair.Key).ToObject<JArray>(), sourcePair.Key));
}
}
else
{
JToken expected = sourcePair.Value;
JToken actual = target.SelectToken("['" + sourcePair.Key + "']");
if (actual == null)
{
returnString.Append("Key " + sourcePair.Key
+ " not found" + Environment.NewLine);
}
else
{
if (!JToken.DeepEquals(expected, actual))
{
returnString.Append("Key " + sourcePair.Key + ": "
+ sourcePair.Value + " != "
+ target.Property(sourcePair.Key).Value
+ Environment.NewLine);
}
}
}
}
return returnString;
}
/// <summary>
/// Deep compare two NewtonSoft JArrays. If they don't match, returns text diffs
/// </summary>
/// <param name="source">The expected results</param>
/// <param name="target">The actual results</param>
/// <param name="arrayName">The name of the array to use in the text diff</param>
/// <returns>Text string</returns>
public static StringBuilder CompareArrays(JArray source, JArray target, string arrayName = "")
{
var returnString = new StringBuilder();
for (int index = 0; index < source.Count; index++)
{
JToken expected = source[index];
if (expected.Type == JTokenType.Object)
{
JToken actual = (index >= target.Count) ? new JObject() : target[index];
returnString.Append(CompareObjects(expected.ToObject<JObject>(),
actual.ToObject<JObject>()));
}
else
{
JToken actual = (index >= target.Count) ? "" : target[index];
if (!JToken.DeepEquals(expected, actual))
{
if (string.IsNullOrEmpty(arrayName))
{
returnString.Append("Index " + index + ": " + expected
+ " != " + actual + Environment.NewLine);
}
else
{
returnString.Append("Key " + arrayName
+ "[" + index + "]: " + expected
+ " != " + actual + Environment.NewLine);
}
}
}
}
return returnString;
}
}
}
| 41.646789 | 174 | 0.523406 | [
"MIT"
] | Endaris/GW2-Elite-Insights-Parser | GW2EIParser.tst/TestHelper.cs | 9,081 | C# |
using System;
using ConsoleToolkit;
using ConsoleToolkit.ApplicationStyles;
using DbUp.Commands;
namespace DbUp
{
class Program : CommandDrivenApplication
{
static void Main(string[] args)
{
Toolkit.Execute<Program>(args);
}
#region Overrides of ConsoleApplicationBase
protected override void Initialise()
{
HelpCommand<HelpCommand>(h => h.Topic);
base.Initialise();
}
#endregion
}
}
| 19.269231 | 51 | 0.60479 | [
"MIT"
] | jamie-davis/SQLServerSnapshots | src/Demo/DbUp/Program.cs | 503 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace EstateApp.Data.Migrations
{
public partial class InitailAuthenticationMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
FullName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 42.429864 | 108 | 0.488962 | [
"MIT"
] | godwinoyale/real-estate | src/EstateApp.Data/Migrations/20200621171451_Initail Authentication Migration.cs | 9,379 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
namespace AinDecompiler
{
public partial class WordWrapForm2 : Form
{
WordWrapOptions wordWrapOptionsAttached;
WordWrapOptions wordWrapOptions;
AinFile ainFile;
WordWrapOptionsProfile currentProfile = null;
bool _ignoreEvents = false;
public WordWrapForm2()
{
InitializeComponent();
}
public WordWrapForm2(WordWrapOptions wordWrapOptions, AinFile ainFile)
{
this.wordWrapOptionsAttached = wordWrapOptions ?? new WordWrapOptions();
this.wordWrapOptions = this.wordWrapOptionsAttached.Clone();
this.ainFile = ainFile;
InitializeComponent();
}
private void WordWrapForm2_Load(object sender, EventArgs e)
{
try
{
_ignoreEvents = true;
ListProfiles();
if (listView1.Items.Count > 0)
{
listView1.Items[0].Selected = true;
listView1.Items[0].Focused = true;
}
}
finally
{
_ignoreEvents = false;
}
this.currentProfile = GetSelectedProfile();
ReadFields();
}
WordWrapOptionsProfile GetSelectedProfile()
{
var selectedItem = listView1.SelectedItems.OfType<ListViewItem>().FirstOrDefault();
if (selectedItem != null)
{
return selectedItem.Tag as WordWrapOptionsProfile;
}
return null;
}
private void ReadFields()
{
this.useVariableWidthFontCheckBox.Checked = wordWrapOptions.UseVariableWidthFont;
this.maintainIndentationCheckBox.Checked = wordWrapOptions.MaintainIndentation;
this.removeLineBreaksIfWordWrappingCheckBox.Checked = wordWrapOptions.RemoveLineBreaksIfWordWrapping;
this.useVariableWidthFontCheckBox.Checked = wordWrapOptions.UseVariableWidthFont;
this.neverUseWordWrapCheckBox.Checked = wordWrapOptions.Disabled;
this.kanjiWidthTextBox.Text = wordWrapOptions.TemplateKanjiWidth.ToString(CultureInfo.InvariantCulture);
if (currentProfile != null)
{
this.codeTextBox.Text = currentProfile.GetTriggerCodes();
charactersPerLineTextBox.Text = currentProfile.MaxCharactersPerLine.ToString();
linesPerMessageTextBox.Text = currentProfile.MaxLinesPerMessage.ToString();
}
}
private int SetFields()
{
wordWrapOptions.UseVariableWidthFont = this.useVariableWidthFontCheckBox.Checked;
wordWrapOptions.MaintainIndentation = this.maintainIndentationCheckBox.Checked;
wordWrapOptions.RemoveLineBreaksIfWordWrapping = this.removeLineBreaksIfWordWrappingCheckBox.Checked;
wordWrapOptions.UseVariableWidthFont = this.useVariableWidthFontCheckBox.Checked;
wordWrapOptions.Disabled = this.neverUseWordWrapCheckBox.Checked;
int failure = 0;
if (currentProfile != null)
{
failure |= (!currentProfile.SetTriggerCodes(this.codeTextBox.Text, this.ainFile)) ? 1 : 0;
int charactersPerLine;
if (int.TryParse(charactersPerLineTextBox.Text, out charactersPerLine))
{
currentProfile.MaxCharactersPerLine = charactersPerLine;
}
else
{
failure |= 2;
}
int linesPerMessage;
if (int.TryParse(linesPerMessageTextBox.Text, out linesPerMessage))
{
currentProfile.MaxLinesPerMessage = linesPerMessage;
}
else
{
failure |= 4;
}
}
double kanjiWidth;
if (double.TryParse(kanjiWidthTextBox.Text, out kanjiWidth))
{
wordWrapOptions.TemplateKanjiWidth = (float)kanjiWidth;
}
else
{
failure |= 8;
}
if (failure == 0)
{
errorProvider1.Clear();
}
return failure;
}
private void ListProfiles()
{
try
{
listView1.BeginUpdate();
listView1.Items.Clear();
for (int i = 0; i < wordWrapOptions.WordWrapOptionsProfiles.Count; i++)
{
var profile = wordWrapOptions.WordWrapOptionsProfiles[i];
var listItem = new ListViewItem(profile.ProfileName, listView1.Groups[0]);
listItem.Tag = profile;
listView1.Items.Add(listItem);
}
}
finally
{
listView1.EndUpdate();
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (_ignoreEvents)
{
return;
}
SetFields();
this.currentProfile = GetSelectedProfile();
ReadFields();
}
private void listView1_BeforeLabelEdit(object sender, LabelEditEventArgs e)
{
e.CancelEdit = false;
}
private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
if (e.CancelEdit == false && e.Label != null)
{
var listView = sender as ListView;
if (e.Item >= 0 && e.Item < listView1.Items.Count)
{
var item = listView.Items[e.Item];
var profile = item.Tag as WordWrapOptionsProfile;
if (profile != null)
{
profile.ProfileName = e.Label.Trim();
item.Text = profile.ProfileName;
}
}
}
}
private void addNodeToolStripButton_Click(object sender, EventArgs e)
{
var newProfile = new WordWrapOptionsProfile();
newProfile.ProfileName = "New wordwrap settings";
var newListItem = new ListViewItem(newProfile.ProfileName, listView1.Groups[0]);
wordWrapOptions.WordWrapOptionsProfiles.Add(newProfile);
listView1.Items.Add(newListItem);
newListItem.Selected = true;
newListItem.Focused = true;
newListItem.BeginEdit();
}
private void removeToolStripButton_Click(object sender, EventArgs e)
{
if (listView1.SelectedIndices.Count == 0)
{
return;
}
int selectedIndex = listView1.SelectedIndices.OfType<int>().FirstOrDefault();
if (selectedIndex >= 0 && selectedIndex < this.wordWrapOptions.WordWrapOptionsProfiles.Count && this.wordWrapOptions.WordWrapOptionsProfiles.Count > 1)
{
var profile = this.wordWrapOptions.WordWrapOptionsProfiles.GetOrNull(selectedIndex);
var item = this.listView1.Items[selectedIndex];
item.Tag = null;
if (currentProfile == profile)
{
currentProfile = null;
}
listView1.Items.RemoveAt(selectedIndex);
this.wordWrapOptions.WordWrapOptionsProfiles.RemoveAt(selectedIndex);
var focusedItem = listView1.FocusedItem;
if (focusedItem != null)
{
focusedItem.Selected = true;
}
else
{
listView1.Items[0].Selected = true;
}
}
}
private void okButton_Click(object sender, EventArgs e)
{
applyButton_Click(applyButton, e);
Close();
}
private void applyButton_Click(object sender, EventArgs e)
{
ApplyChanges();
//if (ApplyChanges != null)
//{
// ApplyChanges(this, EventArgs.Empty);
//}
}
private void ApplyChanges()
{
SetFields();
this.wordWrapOptionsAttached.AssignFrom(this.wordWrapOptions);
}
//public event EventHandler ApplyChanges;
private void cancelButton_Click(object sender, EventArgs e)
{
Close();
}
private void linesPerMessageTextBox_Validating(object sender, CancelEventArgs e)
{
int result = SetFields();
var control = sender as Control;
if (0 != (result & 4))
{
errorProvider1.SetError(control, "Invalid lines per message");
}
else
{
errorProvider1.SetError(control, "");
}
}
private void charactersPerLineTextBox_Validating(object sender, CancelEventArgs e)
{
int result = SetFields();
var control = sender as Control;
if (0 != (result & 2))
{
errorProvider1.SetError(control, "Invalid characters per line");
}
else
{
errorProvider1.SetError(control, "");
}
}
private void codeTextBox_Validating(object sender, CancelEventArgs e)
{
int result = SetFields();
var control = sender as Control;
if (0 != (result & 1))
{
errorProvider1.SetError(control, "Code contains errors");
}
else
{
errorProvider1.SetError(control, "");
}
}
private void selectFontButton_Click(object sender, EventArgs e)
{
using (var fontDialog = new FontDialog())
{
if (this.wordWrapOptions != null)
{
fontDialog.Font = new Font(this.wordWrapOptions.TemplateFontName, this.wordWrapOptions.TemplateFontSize, this.wordWrapOptions.TemplateFontBold ? FontStyle.Bold : FontStyle.Regular);
}
if (fontDialog.ShowDialog() == DialogResult.OK)
{
var font = fontDialog.Font;
this.wordWrapOptions.TemplateFontBold = (0 != (font.Style & FontStyle.Bold)) ? true : false;
this.wordWrapOptions.TemplateFontName = font.FontFamily.Name;
this.wordWrapOptions.TemplateFontSize = font.Size;
}
}
}
private void neverUseWordWrapCheckBox_CheckedChanged(object sender, EventArgs e)
{
DisableOrEnableAllControls(!this.neverUseWordWrapCheckBox.Checked);
}
private void DisableOrEnableAllControls(bool enabled)
{
this.useVariableWidthFontCheckBox.Enabled = enabled;
this.maintainIndentationCheckBox.Enabled = enabled;
this.removeLineBreaksIfWordWrappingCheckBox.Enabled = enabled;
this.useVariableWidthFontCheckBox.Enabled = enabled;
this.codeTextBox.Enabled = enabled;
this.linesPerMessageTextBox.Enabled = enabled;
this.charactersPerLineTextBox.Enabled = enabled;
this.listView1.Enabled = enabled;
this.toolStrip1.Enabled = enabled;
this.selectFontButton.Enabled = enabled;
this.lblCharactersPerLine.Enabled = enabled;
this.lblCode.Enabled = enabled;
this.lblLinesPerMessage.Enabled = enabled;
this.kanjiWidthTextBox.Enabled = enabled;
this.lblKanjiWidth.Enabled = enabled;
}
private void kanjiWidthTextBox_Validating(object sender, CancelEventArgs e)
{
int result = SetFields();
var control = sender as Control;
if (0 != (result & 8))
{
errorProvider1.SetError(control, "Invalid Kanji Width");
}
else
{
errorProvider1.SetError(control, "");
}
}
}
}
| 35.571429 | 202 | 0.532051 | [
"MIT"
] | UserUnknownFactor/AinDecompiler | AinDecompiler/WordWrapForm2.cs | 12,950 | C# |
using System;
namespace brainflow
{
/// <summary>
/// BrainFlowException class to notify about errors
/// </summary>
public class BrainFlowException : Exception
{
/// <summary>
/// exit code returned from low level API
/// </summary>
public int exit_code;
public BrainFlowException (int code) : base (String.Format ("{0}:{1}", Enum.GetName (typeof (CustomExitCodes), code), code))
{
exit_code = code;
}
}
}
| 25.05 | 132 | 0.57485 | [
"MIT"
] | BrovTec/brainflow | csharp-package/brainflow/brainflow/brainflow_exception.cs | 503 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.